Openshift doesn't deploy persistence.xml? - java

Hello there internet community,
So I went into JAVA and started test things localy on my WildFly 8. Everything is OK with maven web projects, looks and works good. Now I decided to go to openshift as the first choice of free cloud for JAVA. I managed to do all needed to get my eclipse and enviorment to work/upload/update server. Then I decided to add MySQL with JPA/Hibernate and localy everything is OK. BUT, when I upload to openshift I get the following error:
2015-05-30 06:18:13,289 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC000001: Failed to start service jboss.deployment.unit."ROOT.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."ROOT.war".WeldStartService: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_45]
Caused by: java.lang.IllegalArgumentException: JBAS016069: Error injecting persistence unit into CDI managed bean. Can't find a persistence unit named in deployment ROOT.war
at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.getScopedPUName(WeldJpaInjectionServices.java:110)
at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.registerPersistenceContextInjectionPoint(WeldJpaInjectionServices.java:73)
at org.jboss.weld.injection.ResourceInjectionFactory$PersistenceContextResourceInjectionProcessor.getResourceReferenceFactory(ResourceInjectionFactory.java:313)
at org.jboss.weld.injection.ResourceInjectionFactory$PersistenceContextResourceInjectionProcessor.getResourceReferenceFactory(ResourceInjectionFactory.java:301)
at org.jboss.weld.injection.ResourceInjectionFactory$ResourceInjectionProcessor.createFieldResourceInjection(ResourceInjectionFactory.java:207)
at org.jboss.weld.injection.ResourceInjectionFactory$ResourceInjectionProcessor.createResourceInjections(ResourceInjectionFactory.java:182)
at org.jboss.weld.injection.ResourceInjectionFactory.discoverType(ResourceInjectionFactory.java:405)
at org.jboss.weld.injection.ResourceInjectionFactory.getResourceInjections(ResourceInjectionFactory.java:92)
at org.jboss.weld.injection.producer.ResourceInjector.(ResourceInjector.java:59)
at org.jboss.weld.injection.producer.ResourceInjector.of(ResourceInjector.java:49)
at org.jboss.weld.injection.producer.BeanInjectionTarget.(BeanInjectionTarget.java:62)
at org.jboss.weld.injection.producer.BeanInjectionTarget.createDefault(BeanInjectionTarget.java:46)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.chooseInjectionTarget(InjectionTargetFactoryImpl.java:128)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:87)
at org.jboss.weld.bean.ManagedBean.(ManagedBean.java:91)
at org.jboss.weld.bean.ManagedBean.of(ManagedBean.java:71)
at org.jboss.weld.bootstrap.AbstractBeanDeployer.createManagedBean(AbstractBeanDeployer.java:264)
at org.jboss.weld.bootstrap.BeanDeployer.createClassBean(BeanDeployer.java:228)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$2.doWork(ConcurrentBeanDeployer.java:78)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$2.doWork(ConcurrentBeanDeployer.java:75)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_45]
... 3 more
as you can see the error comes from
JBAS016069: Error injecting persistence unit into CDI managed bean. Can't find a persistence unit named in deployment ROOT.war
here is my PersistenceContext injection point:
<pre><code>
#SessionScoped
public class IndexWebBean implements Serializable {
private static final long serialVersionUID = 1L;
#PersistenceContext
EntityManager em;
#Inject
SettingsBean settingsBean;
private boolean isUserAdmin = true;
private String selectedTheme = "aristo";
private String aboutMessage;
private NotificationController notificationController;
public IndexWebBean() {}
#PostConstruct
public void Init() {}
}
</code></pre>
here is persistence.xml:
<pre><code>
<persistence-unit name="ROOT">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
<class>ROOT.ROOT.entity.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
</properties>
</persistence-unit>
</code></pre>
standalone.xml:
<pre><code>
<datasources>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<datasource jta="true" jndi-name="java:jboss/datasources/MySQLDS" pool-name="MySQL" enabled="true" use-ccm="true">
<connection-url>jdbc:mysql://localhost:3306/crafty</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>com.mysql</driver>
<security>
<user-name>XX</user-name>
<password>XX</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<timeout>
<set-tx-query-timeout>false</set-tx-query-timeout>
<blocking-timeout-millis>0</blocking-timeout-millis>
<idle-timeout-minutes>0</idle-timeout-minutes>
<query-timeout>0</query-timeout>
<use-try-lock>0</use-try-lock>
<allocation-retry>0</allocation-retry>
<allocation-retry-wait-millis>0</allocation-retry-wait-millis>
</timeout>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="com.mysql" module="com.mysql"/>
</drivers>
</datasources>
</code></pre>
(alot of text has been outputed, so quick reminder: localy eveyrthing works like a charm)
So I went with "rhc ssh -a appname" and checked that in wildfly/standalone/deployments/ROOT.war IS compiled in standalone WAR file, while in local system the whole project is folder based - it's not compiled to WAR. That's NOT especialy a bad thing, but the point is that when I unziped the WAR, I checked if folder structure is the same as local folder structure. It seems that it's NOT. There is not META-INF in ROOT.war/WEB-INF/classes where persistence.xml actually stands ... that was a strange one! What I did is to add #PersistenceContext(unitName="ROOT") to em injection point, manualy create that folder (META-INF), manualy upload my persistence.xml from local computer, and rename ROOT.war.failed to ROOT.war.dodeply to re-deploy, and it worked. But then I made some changes to the code localy, again it worked like a charm, published to openshift thru eclipse and still openshift complied my ROOT.war to webarch and META-INF and standalone.xml are nowhere to be found which yet leaded to the same error. So my question is: what am I doing wrong if everything works great localy, and doesn't when is uploaded to openshift? Thanks in advance for your time.
PS.: English is not my native sorry for any errors. I hope everything is readable and understandable. Any more additional info I will provide on demand.

Related

Infinispan drops connection to MYSQL 5.7 database

We have Keycloak in HA, which we have configured with a external Infinispan cluster for sessions, clientSessions & authenticationSessions.
Everything works under containers in a similar approach like the one performed under https://github.com/albertoSoto/keycloak-infinispan-cluster
The project runs KC 15.0.2 with Wildfly (migration to quarkus to be done), and in that case, uses Infinispan 11.0.9 to perform the external data persistence to Mysql 5.7. The driver used is the latest one, using https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.28/mysql-connector-java-8.0.28.jar as suggested by Oracle. The connection driver is com.mysql.cj.jdbc.Driver.
The project starts nice, but after random time, mysql drops the connection and the Infinispan cluster can't reconnect.
In a trial to make it work, I have been able to use Agroal configuration, based in a properties file like it's at the bottom of this message.
The content of that agroal property file, that overrides JPA behavior in the project is the following:
org.infinispan.agroal.metricsEnabled=false
org.infinispan.agroal.minSize=10
org.infinispan.agroal.maxSize=100
org.infinispan.agroal.initialSize=20
org.infinispan.agroal.acquisitionTimeout_s=1
org.infinispan.agroal.validationTimeout_m=1
org.infinispan.agroal.leakTimeout_s=10
org.infinispan.agroal.reapTimeout_m=10
org.infinispan.agroal.maxLifetime_m=10
org.infinispan.agroal.autoCommit=true
org.infinispan.agroal.jdbcTransactionIsolation=READ_COMMITTED
org.infinispan.agroal.jdbcUrl=jdbc:mysql://mysql:3306/infinispan
org.infinispan.agroal.driverClassName=com.mysql.cj.jdbc.Driver
org.infinispan.agroal.principal=keycloak
org.infinispan.agroal.credential=password
The error shown after the connection is closed from the db is the following:
[1;31m21:55:31,052 ERROR (jgroups-319,vi-infinispan-1-5379) [org.infinispan.interceptors.impl.InvocationContextInterceptor] ISPN000136: Error executing command RemoveCommand on Cache 'clientSessions', writing keys [WrappedByteArray{bytes=0304090000000E\j\a\v\a\.\u\t\i\l\.\U\U\I\DBC9903F798\m85\/000000020000000C\l\e\a\s\t\S\i\g\B\i\t\s\$000000000B\m\o\s\t\S\i\g\B\i\t\s\$00168D0C\z8AB49FBA9B\C118A06A0DB\D82... (85 bytes), hashCode=73644551}] org.infinispan.remoting.RemoteException: ISPN000217: Received exception from vi-infinispan-0-53111, see cause for remote stack trace
at org.infinispan.remoting.transport.ResponseCollectors.wrapRemoteException(ResponseCollectors.java:25)
at org.infinispan.remoting.transport.ValidSingleResponseCollector.withException(ValidSingleResponseCollector.java:37)
at org.infinispan.remoting.transport.ValidSingleResponseCollector.addResponse(ValidSingleResponseCollector.java:21)
at org.infinispan.remoting.transport.impl.SingleTargetRequest.addResponse(SingleTargetRequest.java:73)
at org.infinispan.remoting.transport.impl.SingleTargetRequest.onResponse(SingleTargetRequest.java:43)
at org.infinispan.remoting.transport.impl.RequestRepository.addResponse(RequestRepository.java:52)
at org.infinispan.remoting.transport.jgroups.JGroupsTransport.processResponse(JGroupsTransport.java:1402)
at org.infinispan.remoting.transport.jgroups.JGroupsTransport.processMessage(JGroupsTransport.java:1305)
at org.infinispan.remoting.transport.jgroups.JGroupsTransport.access$300(JGroupsTransport.java:131)
at org.infinispan.remoting.transport.jgroups.JGroupsTransport$ChannelCallbacks.up(JGroupsTransport.java:1445)
at org.jgroups.JChannel.up(JChannel.java:784)
at org.jgroups.stack.ProtocolStack.up(ProtocolStack.java:913)
at org.jgroups.protocols.FRAG3.up(FRAG3.java:165)
at org.jgroups.protocols.FlowControl.up(FlowControl.java:343)
at org.jgroups.protocols.FlowControl.up(FlowControl.java:343)
at org.jgroups.protocols.pbcast.GMS.up(GMS.java:876)
at org.jgroups.protocols.pbcast.STABLE.up(STABLE.java:243)
at org.jgroups.protocols.UNICAST3.deliverMessage(UNICAST3.java:1049)
at org.jgroups.protocols.UNICAST3.addMessage(UNICAST3.java:772)
at org.jgroups.protocols.UNICAST3.handleDataReceived(UNICAST3.java:753)
at org.jgroups.protocols.UNICAST3.up(UNICAST3.java:405)
at org.jgroups.protocols.pbcast.NAKACK2.up(NAKACK2.java:592)
at org.jgroups.protocols.VERIFY_SUSPECT.up(VERIFY_SUSPECT.java:132)
at org.jgroups.protocols.FailureDetection.up(FailureDetection.java:186)
at org.jgroups.protocols.FD_SOCK.up(FD_SOCK.java:254)
at org.jgroups.protocols.MERGE3.up(MERGE3.java:281)
at org.jgroups.protocols.Discovery.up(Discovery.java:300)
at org.jgroups.protocols.TP.passMessageUp(TP.java:1396)
at org.jgroups.util.SubmitToThreadPool$SingleMessageHandler.run(SubmitToThreadPool.java:87)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.infinispan.persistence.spi.PersistenceException: Error while removing string keys from database
at org.infinispan.marshall.exts.ThrowableExternalizer.readObject(ThrowableExternalizer.java:234)
at org.infinispan.marshall.exts.ThrowableExternalizer.readObject(ThrowableExternalizer.java:42)
at org.infinispan.marshall.core.GlobalMarshaller.readWithExternalizer(GlobalMarshaller.java:728)
at org.infinispan.marshall.core.GlobalMarshaller.readNonNullableObject(GlobalMarshaller.java:709)
at org.infinispan.marshall.core.GlobalMarshaller.readNullableObject(GlobalMarshaller.java:358)
at org.infinispan.marshall.core.BytesObjectInput.readObject(BytesObjectInput.java:32)
at org.infinispan.remoting.responses.ExceptionResponse$Externalizer.readObject(ExceptionResponse.java:49)
at org.infinispan.remoting.responses.ExceptionResponse$Externalizer.readObject(ExceptionResponse.java:41)
at org.infinispan.marshall.core.GlobalMarshaller.readWithExternalizer(GlobalMarshaller.java:728)
at org.infinispan.marshall.core.GlobalMarshaller.readNonNullableObject(GlobalMarshaller.java:709)
at org.infinispan.marshall.core.GlobalMarshaller.readNullableObject(GlobalMarshaller.java:358)
at org.infinispan.marshall.core.GlobalMarshaller.objectFromObjectInput(GlobalMarshaller.java:192)
at org.infinispan.marshall.core.GlobalMarshaller.objectFromByteBuffer(GlobalMarshaller.java:221)
at org.infinispan.remoting.transport.jgroups.JGroupsTransport.processResponse(JGroupsTransport.java:1394)
... 25 more
Caused by: java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
We do use JDBC_PING for the cluster connection and 2 nodes are active. They register themselves properly and everything works like a charm, until the timeout is set.
The base configuration that I have placed is the following:
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:11.0 https://infinispan.org/schemas/infinispan-config-11.0.xsd
urn:infinispan:server:11.0 https://infinispan.org/schemas/infinispan-server-11.0.xsd"
xmlns="urn:infinispan:config:11.0"
xmlns:server="urn:infinispan:server:11.0">
<!--
Generic XML definition located under
https://docs.jboss.org/infinispan/11.0/configdocs/
-->
<jgroups>
<stack-file name="default-udp" path="default-jgroups.xml"/>
<stack-file name="default-tcp" path="default-jgroups-tcp.xml"/>
<stack-file name="gce" path="default-jgroups-google.xml"/>
<stack-file name="k8s" path="default-jgroups-kubernetes.xml"/>
<stack-file name="kc-udp" path="default-keycloak-jgroups-udp.xml"/>
<stack-file name="custom-k8s-jdbc" path="custom-jgroups-kubernetes-jdbc.xml"/>
<stack-file name="custom-tcp-jdbc" path="custom-jgroups-tcp-jdbc.xml"/>
</jgroups>
<cache-container name="default" statistics="${env.INFINISPAN_CACHE_STATISTICS:false}">
<serialization marshaller="org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller">
<white-list>
<class>java.util.UUID</class>
<regex>org.keycloak.models.sessions.infinispan.*</regex>
</white-list>
</serialization>
<serialization marshaller="org.infinispan.commons.marshall.JavaSerializationMarshaller">
<white-list>
<class>java.util.UUID</class>
<regex>org.keycloak.models.sessions.infinispan.*</regex>
</white-list>
</serialization>
<transport cluster="${infinispan.cluster.name:cluster}" stack="${infinispan.cluster.stack:default-udp}"
node-name="${infinispan.node.name:}"/>
<replicated-cache-configuration name="sessions-cfg" mode="SYNC" start="EAGER"
statistics="${env.INFINISPAN_CACHE_STATISTICS:false}">
<state-transfer timeout="${infinispan.statetransfer.timeout:600000}"/>
<encoding media-type="application/x-jboss-marshalling"/>
<expiration lifespan="900000000000000000"/>
</replicated-cache-configuration>
<distributed-cache-configuration name="distributed-cache-cfg">
<encoding media-type="application/x-jboss-marshalling"/>
<expiration lifespan="900000000000000000"/>
<persistence passivation="false">
<string-keyed-jdbc-store shared="true" xmlns="urn:infinispan:config:store:jdbc:11.0">
<connection-pool properties-file="${env.PROPERTIES_FILE:/opt/infinispan/server/conf/connection-pool.properties}" />
<string-keyed-table drop-on-exit="false"
prefix="ISPN">
<id-column name="ID_COLUMN" type="VARCHAR(255)"/>
<!-- Blob generates error on KC. We increase it to a safe max size (65K per row)
<data-column name="DATA_COLUMN" type="BLOB" />
-->
<data-column name="DATA_COLUMN" type="VARBINARY(50000)"/>
<timestamp-column name="TIMESTAMP_COLUMN" type="BIGINT"/>
<segment-column name="SEGMENT_COLUMN" type="INT"/>
</string-keyed-table>
</string-keyed-jdbc-store>
</persistence>
<state-transfer timeout="${infinispan.statetransfer.timeout:600000}"/>
</distributed-cache-configuration>
<!--https://infinispan.org/docs/stable/titles/configuring/configuring.html#distributed-caches_clustered-caches-->
<!--https://infinispan.org/docs/stable/titles/configuring/configuring.html#configuring-jdbc-cache-stores_persistence-->
<distributed-cache name="sessions" owners="2" configuration="distributed-cache-cfg">
</distributed-cache>
<distributed-cache name="clientSessions" owners="2" configuration="distributed-cache-cfg">
</distributed-cache>
<distributed-cache name="authenticationSessions" owners="2" configuration="distributed-cache-cfg">
</distributed-cache>
</cache-container>
<!-- Original at v11 - -->
<server xmlns="urn:infinispan:server:11.0">
<interfaces>
<interface name="public">
<inet-address value="${infinispan.bind.address:0.0.0.0}"/>
</interface>
</interfaces>
<socket-bindings default-interface="public" port-offset="0">
<socket-binding name="default" port="11222"/>
</socket-bindings>
<security>
<security-realms>
<security-realm name="default">
<properties-realm groups-attribute="Roles">
<user-properties path="users.properties" relative-to="infinispan.server.config.path"
plain-text="true"/>
<group-properties path="groups.properties" relative-to="infinispan.server.config.path"/>
</properties-realm>
</security-realm>
</security-realms>
</security>
<endpoints socket-binding="default" security-realm="default">
<hotrod-connector name="hotrod">
<authentication>
<sasl mechanisms="SCRAM-SHA-512 SCRAM-SHA-384 SCRAM-SHA-256 SCRAM-SHA-1 DIGEST-SHA-512 DIGEST-SHA-384 DIGEST-SHA-256 DIGEST-SHA DIGEST-MD5 PLAIN"
qop="auth" server-name="infinispan"/>
</authentication>
</hotrod-connector>
<rest-connector name="rest">
<authentication mechanisms="DIGEST BASIC"/>
</rest-connector>
</endpoints>
</server>
</infinispan>
The thing is... what are am I doing wrong?
There is not too much information about it. Can anyone help?
Thank you!
Unfortunately I think you have stumbled across a bug with the persistence availability check that prevents stores from reconnecting if an exception is thrown ISPN-13863. I have just created a PR, however the fix will only be available in the Infinispan 14.x stream.

java web app and Postgres on websphere-liberty

I'm deploying a working Tomcat webapp on websphere-liberty on docker. The webapp connects to a postgres data source on docker. In websphere when I try to get connection with
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/postgres");
Connection conn = ds.getConnection();
my web.xml is setted as:
<resource-ref>
<description>postgreSQL Connection</description>
<res-ref-name>jdbc/postgres</res-ref-name>
<res-type>javax.sql.XADataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I get the following error
javax.naming.NamingException: CWNEN1001E: The object referenced by the java:comp/env/jdbc/postgres JNDI name could not be instantiated.
If the reference name maps to a JNDI name in the deployment descriptor bindings for the application
performing the JNDI lookup, make sure that the JNDI name mapping in the deployment descriptor binding is correct.
If the JNDI name mapping is correct, make sure the target resource
can be resolved with the specified name relative to the default initial context.
[Root exception is com.ibm.wsspi.injectionengine.InjectionException: CWNEN0030E: The
server was unable to obtain an object instance for the java:comp/env/jdbc/postgres reference.
The exception message was: CWNEN1004E: The server was unable to find the jdbc/postgres default binding with the javax.sql.XADataSource type for
the java:comp/env/jdbc/postgres reference.]
I exlude that is a problem with docker network. What I have setted wrong? Is something in my websphere-liberty?
server.xml is
<server description="Default server">
<!-- Enable features -->
<featureManager>
<feature>webProfile-7.0</feature>
<feature>adminCenter-1.0</feature>
<feature>jdbc-4.0</feature>
</featureManager>
<quickStartSecurity userName="admin" userPassword="password"/>
<!-- Define the host name for use by the collective.
If the host name needs to be changed, the server should be
removed from the collective and re-joined. -->
<!-- <variable name="defaultHostName" value="localhost" /> -->
<!-- Define an Administrator and non-Administrator -->
<basicRegistry id="basic">
<user name="admin" password="admin" />
<user name="nonadmin" password="nonadminpwd" />
</basicRegistry>
<!-- Assign 'admin' to Administrator -->
<administrator-role>
<user>admin</user>
</administrator-role>
<!-- <keyStore id="defaultKeyStore" password="Liberty" /> -->
<httpEndpoint id="defaultHttpEndpoint"
host="*"
httpPort="9080"
httpsPort="9443" />
<remoteFileAccess>
<writeDir>${server.config.dir}</writeDir>
</remoteFileAccess>
<library id="postgres-lib">
<fileset dir="/arturial/project/" includes="postgresql-9.4.1208.jre6.jar"/>
</library>
<dataSource id="jdbc-Prima_WA_db" jndiName="jdbc/postgres" type="javax.sql.DataSource">
<jdbcDriver libraryRef="postgres-lib"/>
<connectionManager numConnectionsPerThreadLocal="10" id="connectionManager" minPoolSize="1"/>
<!-- <properties.oracle user="postgres" password="postgres" -
url="jdbc:postgres://172.17.0.3:5432/Prima_WA_db"/> -->
</dataSource>
<!--
<applicationManager updateTrigger="disabled"/>
<application id="primawebapp" name="primawebapp" location="war/primawebapp" type="war">
<classLoader delegation="parentLast" commonLibraryRef="postgres-lib"/>
</application>
-->
</server>
Try this;
DataSource ds = (DataSource)ctx.lookup("jdbc/postgres");
Also, a different way.
Your <datasource> must have properties configured under it, otherwise there is no way for Liberty to know how to connect to your database.
For postgresql, try the following configuration:
<dataSource id="jdbc-Prima_WA_db" jndiName="jdbc/postgres">
<jdbcDriver libraryRef="postgres-lib"/>
<properties serverName="172.17.0.3" portNumber="5432" databaseName="Prima_WA_db"
user="postgres" password="postgres"/>
</dataSource>
Of course, using the proper values that correspond to the postgresql instance that you are running on.
Looks like your datasource definition might be incomplete, try updating it with the following:
<dataSource type="javax.sql.XADataSource" ...
<jdbcDriver javax.sql.XADataSource="org.postgresql.xa.PGXADataSource" ...

JBoss 7 & EJB3 | Where should I define datasource

I'm new to Jboss and I don't understand where should I define the database connection data like url, username, password etc..
Here is my multimodule project:
app-root
app-api
- src
- pom.xml
app-ear
- src
- pom.xml
app-ejb
- src
- pom.xml
pom.xml
My persinstence.xml located unter app-root/app-ejb/src/main/config/default/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ejb3_jpa_myapp_pu" transaction-type="JTA">
<description>Jboss Test application</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jdbc/MyApp</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
And finaly my simple Service:
#Stateless
#Remote(IService.class)
public class ServiceImpl implements IService{
#PersistenceContext(unitName = "ejb3_jpa_myapp_pu")
private EntityManager em;
#Override
public void doSomeJob() {
// [...]
}
}
I know I have to define the database connection properties but where can I do that?
You need to define the data source in the standalone XML file that your JBoss instance is using. JBoss does not ship with database drivers so there are two steps:
1) Create a JBoss module for the database drivers (eg MySQL, Oracle, Postgres etc)
2) Create the datasource definition
Step 1) needs only to be done once, ie many MySQL datasources can use the same MySQL JBoss module.
Step 2) An example datasource configuration for MySQL would be:
<datasources>
<datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
<connection-url>jdbc:mysql://localhost:3306/EJB3</connection-url>
<driver>com.mysql</driver>
<transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
<pool>
<min-pool-size>10</min-pool-size>
<max-pool-size>100</max-pool-size>
<prefill>true</prefill>
</pool>
<security>
<user-name>test</user-name>
<password>test</password>
</security>
<statement>
<prepared-statement-cache-size>32</prepared-statement-cache-size>
<share-prepared-statements/>
</statement>
</datasource>
<drivers>
<driver name="com.mysql" module="com.mysql">
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
The above can be automated using the JBoss CLI. Also creating the JBoss modules can also be automated for example using the smartics-jboss-modules-maven-plugin see Generate an xml file with all dependencies with maven for more info.

Using multiple datasources with Wildfly

I am using multiple datasources in my java web-application.
Here is Wildfly configuration (standalone mode):
<datasource jta="false" jndi-name="java:jboss/datasources/DS1" pool-name="DS1" enabled="true" use-ccm="false">
<connection-url>URL1</connection-url>
<driver>ojdbc7</driver>
<security>
<user-name>login</user-name>
<password>password</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
<datasource jta="false" jndi-name="java:jboss/datasources/DS2" pool-name="DS2" enabled="true" use-ccm="false">
<connection-url>URL2</connection-url>
<driver-class>org.h2.Driver</driver-class>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
Jboss.xml in my ejb subproject:
<session>
<ejb-name>Bean1</ejb-name>
<resource-description>
<res-ref-name>DS1</res-ref-name>
<jndi-name>java:jboss/datasources/DS1</jndi-name>
</resource-description>
</session>
<session>
<ejb-name>Bean2</ejb-name>
<resource-description>
<res-ref-name>DS2</res-ref-name>
<jndi-name>java:jboss/datasources/DS2</jndi-name>
</resource-description>
</session>
In EJB Bean1/Bean2 datasources are called via
#Resource(name="DS1/DS2")
private DataSource dataSource;
....
Connection connection = dataSource.getConnection();
Using shown configuration I have faced following problems :
I can access datasource only if it is set as a default in <default-bindings> section of my standalone-full.xml. If it is empty, I get
"JBAS014771: Services with missing/unavailable dependencies"
pointing to the list of datasources used in beans during deployment.
If I set DS1 as a default one, next time DS2 is injected, it will contain
LocalManagedConnectionFactory
pointing to DS1 in dataSource.mcf variable
As I've understood from this topic
Why different persistence units with separated data sources query the same data source?
this problem may be caused by container-managed persistance.
But in given case I am not using any ORM. So I am only able to manipulate datasources using jndi and server configuration.
So is there any way I can resolve this situation by using some additional wildfly configuration / any manipulations with application or I have to use ORM and manage persistance by myself ?
Thanks for replies.
it's recommended to use an ORM (JPA in best case), so you will use entityManager and persitence.xml for using multiple data sources.
<persistence-unit name="DB1_PU">
<jta-data-source>java:jboss/datasources/ds1</jta-data-source>
</persistence-unit>
<persistence-unit name="DB2_PU">
<jta-data-source>java:jboss/datasources/ds2</jta-data-source>
</persistence-unit>
and you can call the DS like :
#PersistenceContext(unitName = "DB1_PU")
protected EntityManager entityManager1;
#PersistenceContext(unitName = "DB2_PU")
protected EntityManager entityManager2;

WildFly LDAP Connection JNDI

We are in the process of moving from Glassfish to WildFly. In Glassfish we setup our LDAP server and use it for authentication and we also reference it with JNDI for us within the application for things such as searching users, etc. I am wondering if there is a way to setup the LDAP connection in the standalone.xml file in WildFly for reference via JNDI in the application like we currently do. I have setup LDAP for authentication and that works but I do not know how to reference that connection for use in our application.
In Wildfly you can use Naming Subsystem for binding a Ldap context, in particular External Context Federation binding type:
External Context Federation
Federation of external JNDI contexts, such as a LDAP context, are
achieved by adding External Context bindings to the global bindings
configuration, through the external-context XML element
For example:
<subsystem xmlns="urn:jboss:domain:naming:2.0">
<bindings>
<external-context name="java:global/federation/ldap/example" class="javax.naming.directory.InitialDirContext" module="org.jboss.as.naming" cache="true">
<environment>
<property name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory" />
<property name="java.naming.provider.url" value="ldap://ldap.example.com:389" />
<property name="java.naming.security.authentication" value="simple" />
<property name="java.naming.security.principal" value="uid=admin,ou=system" />
<property name="java.naming.security.credentials" value="secret" />
</environment>
</external-context>
</bindings>
<remote-naming/>
</subsystem>
Ref: WildFly 8
- Naming Subsystem Configuration
I hope this help.

Categories

Resources