Cannot find datasource in Java Adapter in IBM MobileFirst - db2

I have created a DataSource in MobileFirst server.xml:
<dataSource jndiName="jdbc/QAIWDB2">
<jdbcDriver libraryRef="DB2Lib"/>
<properties databaseName="QAIWPRD" password="pass" portNumber="99999" serverName="xyz.com" user="user"/>
</dataSource>
When I am trying to access it from a Java Adpater I am getting an error while deploying the adapter
Adapter deployment failed: An object could not be obtained for name
jdbc/QAIWDB2.
The code in Java Adapter is
static DataSource ds = null;
static Context ctx = null;
public static void init() throws NamingException {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("jdbc/QAIWDB2");
}

Try the DB2 JNDI definition proposal mentioned in this answer: https://stackoverflow.com/a/17851124/1530814.
Of course, change the values to yours...
<dataSource jndiName="jdbc/db2" type="javax.sql.DataSource">
<jdbcDriver>
<library>
<fileset dir="/usr/lib/java/ibm-db2-universal-driver" includes="db2jcc4.jar, db2jcc_license_cisuz.jar, db2jcc_license_cu.jar"/>
</library>
</jdbcDriver>
<properties databaseName="DB2T" portNumber="21020" serverName="db2t.lvm.de password=" ... " user=" ... "/>
</dataSource>

Related

Liberty class loading issues or problem with hibernate (migrating tomcat app on liberty)?

i have to deploy a multi-module application in ear on Liberty Server 20 in my Eclipse. This application use hibernate as provider jpa2 and Derby client + driver derby-10.12.1.1.jar(as shared fileset). Persistence.xml is configured with non jta.
This is server.xml:
<enterpriseApplication id="rubrica-ear" location="rubrica-ear.ear" name="rubrica-ear"/>
<dataSource jndiName="jdbc/TestappDS" type="javax.sql.ConnectionPoolDataSource">
<properties.derby.client createDatabase="false" databaseName=".rubrica"></properties.derby.client>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared"></fileset>
</library>
</jdbcDriver>
</dataSource>
My .rubrica db location is in /usr/home.
Because I dont want to start a server derby on console but automatically, i do taht in a #WebListener class:
#WebListener
public class ReqListener implements ServletContextListener {
static final Logger log = LoggerFactory.getLogger(ReqListener.class);
PrintWriter pw = new PrintWriter(System.out);
private NetworkServerControl derbyserver;
#Override
public void contextInitialized(ServletContextEvent arg0) {
try {
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.rubrica";
// Set the db system directory and startup Server Derby for incoming connections.
System.setProperty("derby.system.home", systemDir);//il db viene salvato qui
derbyserver = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
derbyserver.start(pw);
log.info("Apache derby settings ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (derbyserver!=null){
...
}
}
When i deploy i get this error
[ERROR] An error occurred in the org.hibernate.ejb.HibernatePersistence persistence provider when attempting to create the entity manager factory of the testapp persistence unit container. The following error occurred: java.lang.NullPointerException
at org.hibernate.engine.jdbc.spi.TypeInfo.extractTypeInfo(TypeInfo.java:128)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:163)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
at com.ibm.ws.jpa.management.JPAPUnitInfo.createEMFactory(JPAPUnitInfo.java:919)
at [internal classes]
When I debug on Liberty i see that Hibernate classes running before the #WebListener code (this is not the same thing in Tomcat), how can i resolve this issue? Something about class loading settings?
I try derby Embedded instead, but problem still araise again, in server.xml:
<properties.derby.embedded createDatabase="create" databaseName="C:/Users/myuser/.rubrica" shutdownDatabase="false"/>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared-libs"/>
</library>
</jdbcDriver>
Thanks
Roberto

how to unwrap PostgreSQL connection from the IBM WSJdbc41Connection

I have been trying to unwrap PostgreSQL connection from the IBM JNDI (WebSphere liberty ) and have had no luck please any help with that :
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("jdbc/indi");
Connection cnx = dataSource.getConnection();
I get this exception :
java.lang.ClassCastException:
com.ibm.ws.rsadapter.jdbc.v41.WSJdbc41Connection cannot be cast to
org.postgresql.PGConnection
I tried :
if(cnx.isWrapperFor(PGConnectionPoolDataSource.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.ds.jdbc4.AbstractJdbc4SimpleDataSource.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.core.v3.ConnectionFactoryImpl.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.jdbc2.AbstractJdbc2Connection.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.jdbc3.AbstractJdbc3Connection.class)) {
//unwrap
}
Thanks
If you would like to unwrap a JDBC object (DataSource, Connection, etc) to a vendor-specific interface, the JDBC driver in the configured <datSource> must be available to the application classloader. The configuration will look something like this:
<application location="oraclejdbcfat.war" >
<!-- expose the 'DBLib' containing the JDBC driver jar to the app classloader -->
<classloader commonLibraryRef="DBLib"/>
</application>
<library id="DBLib">
<fileset dir="${server.config.dir}/postgresql/" includes="*.jar"/>
</library>
<dataSource jndiName="jdbc/myDS">
<jdbcDriver libraryRef="DBLib"/>
<properties .../>
</dataSource>
From there, you can unwrap the object in the same way you were doing before, namely:
DataSource ds = InitialContext.doLookup("jdbc/myDS");
Connection conn = ds.getConnection();
PGConnection pgConn = conn.unwrap(org.postgresql.PGConnection.class);
Also, there is an enableConnectionCasting boolean attribute on <dataSource> configuration which will automatically call unwrap for you upon getConnection().
<dataSource jndiName="jdbc/myDS" enableConnectionCasting="true">
Then the java code is a bit simpler:
DataSource ds = InitialContext.lookup("jdbc/indi");
PGConnection pgConn = (PGConnection) ds.getConnection();

Is it possible to explicitly dictate which EJB Receiver is used within JBoss EAP 6?

I am trying to make remote calls to multiple servers running on one instance of JBoss EAP 6 from a client server running on a separate instance of JBoss EAP 6. I have configured for JBoss-to-JBoss remote communication, and have read about scoped EJB client contexts, but the two do not appear to be compatible. Currently, I have two EJB Receivers configured (one for each remote server), but it appears when I try to make a remote call, the initialized Context randomly selects the EJB Receiver it will use. It would seem reasonable that I can force which EJB Receiver is used when the Context is initialized if I have the remote ip and port, or the remote connection name, but alas, I don't know the the secret handshake.
host.xml:
<security-realm name="ejb-security-realm">
<server-identities>
<secret value="ZWpiUEBzc3cwcmQ="/>
</server-identities>
</security-realm>
domain.xml:
<subsystem xmlns="urn:jboss:domain:remoting:1.2">
<connector name="remoting-connector" socket binding="remoting" security-realm="ApplicationRealm"/>
<outbound-connections>
<remote-outbound-connection name="remote-ejb-connection" outbound-socket-binding-ref="mpg1-app1" username="ejbuser" security-realm="ejb-security-realm">
<properties>
<property name="SASL_POLICY_NOANONYMOUS" value="false"/>
<property name="SSL_ENABLED" value="false"/>
</properties>
</remote-outbound-connection>
<remote-outbound-connection name="remote-ejb-connection2" outbound-socket-binding-ref="mpg2-app1" username="ejbuser" security-realm="ejb-security-realm">
<properties>
<property name="SASL_POLICY_NOANONYMOUS" value="false"/>
<property name="SSL_ENABLED" value="false"/>
</properties>
</remote-outbound-connection>
</outbound-connections>
</subsystem>
...
<socket-binding-group name="full-sockets" default-interface="public">
...
<socket-binding name="remoting" port="44447"/>
<outbound-socket-binding name="mpg1-app1">
<remote-destination host="localhost" port="44452"/>
</outbound-socket-binding>
<outbound-socket-binding name="mpg2-app1">
<remote-destination host="localhost" port="44453"/>
</outbound-socket-binding>
</socket-binding-group>
jboss-ejb-client.xml
<jboss-ejb-client xmlns="urn:jboss:ejb-client:1.0">
<client-context>
<ejb-receivers>
<remoting-ejb-receiver outbound-connection-ref="remote-ejb-connection"/>
<remoting-ejb-receiver outbound-connection-ref="remote-ejb-connection2"/>
</ejb-receivers>
</client-context>
</jboss-ejb-client>
The remote call:
Context ctx = null;
final Properties props = new Properties();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
try {
ctx = new InitialContext(props);
MyInterfaceObject ourInterface = ctx.lookup("ejb:" + appName + "/" + moduleName + "/" + beanName + "!"
+ viewClassName);
ourInteface.refreshProperties();//remote method call
}
Any Help would be greatly appreciated!
have you try cluster-node-selector
jboss-ejb-client.xml
<!-- if an outbound connection connect to a cluster a list of members is provided after successful connection.
To connect to this node this cluster element must be defined.
-->
<clusters>
<!-- cluster of remote-ejb-connection-1 -->
<cluster name="ejb" security-realm="ejb-security-realm-1" username="test" cluster-node-selector="org.jboss.as.quickstarts.ejb.clients.selector.AllClusterNodeSelector">
<connection-creation-options>
<property name="org.xnio.Options.SSL_ENABLED" value="false" />
<property name="org.xnio.Options.SASL_POLICY_NOANONYMOUS" value="false" />
</connection-creation-options>
</cluster>
</clusters>
</client-context>
</jboss-ejb-client>
Selector Implementation
#Override
public String selectNode(final String clusterName, final String[] connectedNodes, final String[] availableNodes) {
if (availableNodes.length == 1) {
return availableNodes[0];
}
// Go through all the nodes and point to the one you want
for (int i = 0; i < availableNodes.length; i++) {
if (availableNodes[i].contains("someoneYouInterestIn")) {
return availableNodes[i];
}
}
final Random random = new Random();
final int randomSelection = random.nextInt(availableNodes.length);
return availableNodes[randomSelection];
}
For more information you can check
https://access.redhat.com/documentation/en/red-hat-jboss-enterprise-application-platform/7.0/developing-ejb-applications/chapter-8-clustered-enterprise-javab

ActiveMQ producer XA transaction

I am trying to configure my custom ActiveMQ producer to use XA transaction. Unfortunately it does't work as expected because messages are sent to queue immediately instead of waiting for transactions to commit.
Here is the producer:
public class MyProducer {
#Autowired
#Qualifier("myTemplate")
private JmsTemplate template;
#Transactional
public void sendMessage(final Order order) {
template.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
ObjectMessage message = new ActiveMQObjectMessage();
message.setObject(order);
return message;
}
});
}
}
And this is template and connection factory configuration:
<bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/activemq/ConnectionFactory" />
</bean>
<bean id="myTemplate" class="org.springframework.jms.core.JmsTemplate"
p:connectionFactory-ref="jmsConnectionFactory"
p:defaultDestination-ref="myDestination"
p:sessionTransacted="true"
p:sessionAcknowledgeModeName="SESSION_TRANSACTED" />
As you can see I am using ConnectionFactory initiated via JNDI. It is configured on JBoss EAP 6.3:
<subsystem xmlns="urn:jboss:domain:resource-adapters:1.1">
<resource-adapters>
<resource-adapter id="activemq-rar.rar">
<module slot="main" id="org.apache.activemq.ra"/>
<transaction-support>XATransaction</transaction-support>
<config-property name="ServerUrl">
tcp://localhost:61616
</config-property>
<connection-definitions>
<connection-definition class-name="org.apache.activemq.ra.ActiveMQManagedConnectionFactory" jndi-name="java:/activemq/ConnectionFactory" enabled="true" use-java-context="true" pool-name="ActiveMQConnectionFactoryPool" use-ccm="true">
<xa-pool>
<min-pool-size>1</min-pool-size>
<max-pool-size>20</max-pool-size>
</xa-pool>
</connection-definition>
</connection-definitions>
</resource-adapter>
</resource-adapters>
</subsystem>
When I debug I can see that JmsTemplate is configured properly:
it has a reference to valid connection factory org.apache.activemq.ra.ActiveMQConnectionFactory
connection factory has a reference to valid transaction manager: org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl
session transacted is set to true
session acknowledge mode is set to SESSION_TRANSACTED(0)
Do you have any idea why these messages are pushed to the queue immediately and they are not removed when transaction is rolled back (e.g. when I throw exception at the end of "sendMessage" method?
You need to show the rest of your configuration (transaction manager etc).
It looks like you don't have transactions enabled in the application context so the template is committing the transaction itself.
Do you have <tx:annotation-driven/> in the context?

ASP.NET Routing in rest service not working in IIS

I created a simple rest service with routing enabled. The routing is properly working when i run it locally i.e using asp.net development server. But when I deploy the application in IIS (IIS 7.5) then it and try to access the method in the service i get the error HTTP 404.0 Not found. Here is my code :
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class HelloWorldService
{
[WebGet(UriTemplate = "Date")]
public DateTime Date()
{
return System.DateTime.Now;
}
}
Global.asax:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("ServiceData", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
Web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
I also Enabled HTTP Redirection Feature under
Windows Features -> Internet Information Services -> Word Wide Web services -> Common HTTP Features
I also tried Adding handlers like
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
Also i have tried all the other solutions that were suggested on the web but nothing works. Thanks in advance for any help.
Something is wrong with your RegisterRoutes(). It should be:
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("HelloWorldService", new WebServiceHostFactory(), typeof(HelloWorldService)));
}