MongoDB IntelliJ: How to configure custom jar project from my war project - spring

I work with IntelliJ, Spring, Maven, Tomcat7 and MongoDB
I have 2 projects:
JAR: this should be an auth service
WAR: this has my auth service as a dependency
Now I have following bean configuration in my war project:
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and quering the documents in the database -->
<bean id="jwt" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="ProjectDB" />
</bean>
<!-- Use this post processor to translate any MongoExceptions
thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- ########################################################################### -->
<!-- Configuration for auth -->
<!-- ########################################################################### -->
<!-- MongoTemplate for connecting and quering the documents in the database -->
<bean id="auth" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="ProjectDB-auth" />
</bean>
My WAR project should use ProjectDB and auth service the ProjectDB-auth
Injection in my WAR project -> #Autowired private MongoTemplate jwt;
Injection in my JAR project -> #Autowired private MongoTemplate auth;
This works fine, but I have an other mongoDB configuration XML file in my JAR project which will be completely ignored (will be never imported in my application context).
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and quering the documents in the database -->
<bean id="test" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="AuthDBBase-notInUse" />
</bean>
<!-- Use this post processor to translate any MongoExceptions
thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
I need to remove this file, but then IntelliJ can not resolve dependency for #Autowired private MongoTemplate auth;
I think everything is wrong with my configuration although this works correctly. But how to configure both my projects the right way?

I think everything is perfectly OK with your setup.
You want to create a JAR to be used by any client, in this case your WAR. You have a dependency on a database. You can leave this dependency undeclared by omitting any Spring configuration in the JAR. This would not be clean. Also, your IDE complains because it cannot check the validity of your project.
It is better to declare that dependency, quite similar to header files in C or Maven dependencies with scope provided. Add that Spring configuration to the project as you did. Tell the users of your library to either include that configuration into their own, or to use that configuration as documentation to see which beans just need to exist for your artifact to work.

Related

Mongo DB Authentication Failed With Spring (REST)

Still now I'm using mongodb version 2.6.9 with spring (REST). In the authentication part, I have edited the mongod.conf file and enabled
auth = true
And added the below codes in spring - applicationContext.xml file
<mongo:mongo host="localhost" port="27017" id="mongo" />
<mongo:db-factory id="mongoDbFactory"
mongo-ref="mongo"
host="localhost"
port="27017"
dbname="********"
username="******"
password="********"
/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- Start ## Bean mapping for Restlet service -->
<bean id="basecampComponent" class="org.restlet.ext.spring.SpringComponent">
<property name="defaultTarget" ref="autoRestletAppliction" />
</bean>
<bean id="autoRestletAppliction" class="com.jiit.restlet.frontcontroller.FirstStepsApplication">
<property name="inboundRoot" ref="router" />
</bean>
<bean name="router" class="org.restlet.ext.spring.SpringBeanRouter" />
And the jar's i have used, for the above configuration,
mongo-java-driver-2.12.1.jar &
spring-data-mongodb-1.2.0.RELEASE.jar
Now, I want to upgrade my mongodb to 3.4 Version. And I have tried to edit the mongod.conf file and enabled the security,
security.authorization: enabled
And I have added admin and mydb with users and tried to connect with mongodb client like robomongo and its works fine.
The problem is i'm not able to connect with spring to mongodb.
I have updated the jars to latest version but its not working. Could you please help me ?
I had a similar kind of problem a few days back. But then I stumbled upon this http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/ and it solved all my problems of mongodb connectivity through spring.
They have provided a proper explanations and how you could connect to your mongodb with or without credentials.

Spring WorkManagerTaskExecutor cannot initialize in websphere

i want use Websphere work manager for executing async jobs in jee context but i have problem with creating spring WorkManager.
bean definition:
<bean id="taskExecutor" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor"> <property name="workManagerName" value="wm/default" /> </bean>
this definition i found in websphere help. But problem is this ends with noClassDefFound. I noticed pckg org.springframework.scheduling.commonj is missing from spring-context since version 2.x.x
Is it replaced with org.springframework.jca.work.WorkManagerTaskExecutor ?
when i use this other spring class, i get error:
Caused by: org.springframework.jndi.TypeMismatchNamingException:
Object of type [class com.ibm.ws.asynchbeans.WorkManagerImpl]
available at JNDI location [wm/default] is not assignable to
[javax.resource.spi.work.WorkManager]
so whats deal here? thx
was - 7.0.0.23
spring - 3.1.2
Class org.springframework.scheduling.commonj.WorkManagerTaskExecutor resides in spring-context-support-3.1.2.RELEASE.jar
Configuration succeeds with javax.resource.spi.work.WorkManager in applicationContext-service.xml in deployment.....
In my case deployment fails for bean injection org.springframework.scheduling.commonj.WorkManagerTaskExecutor as it fails to take WorkManager JNDI Configured in Application Server.... I just replaced javax.resource.spi.work.WorkManager. And so far it is success deployment.
I yet to see application works fine with it.
<bean id="taskExecutor" class="javax.resource.spi.work.WorkManager">
<property name="workManagerName" value="wm/default" />
</bean>
In our scenario we were managed it by ThreadPoolTaskExecutor instead of WorkManagerTaskExecutor
Here is configuration that comes in ApplicationContext.xml
<!--
<bean id="rtSenderTaskExecutor"
class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
<property name="workManagerName">
<value>${org.quartz.threadPool.jndi}</value>
</property>
</bean> -->
<!-- Local Thread Pool -->
<bean id="rtSenderTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="${org.quartz.threadPool.corePoolSize}" />
<property name="maxPoolSize" value="${org.quartz.threadPool.maxPoolSize}" />
<property name="queueCapacity" value="${org.quartz.threadPool.queueCapacity}" />
<property name="keepAliveSeconds" value="${org.quartz.threadPool.keepAliveSeconds}"></property>
</bean>

Spring - Jaxb2Marshaller - How to Automatically Add JAXB2 Classes using Annotations

I am using Spring 3.1.x and CXF 2.6.1 for REST services. I using jaxbXmlProvider as shown below.
<jaxrs:server ...
<jaxrs:providers>
<ref bean="jaxbXmlProvider" />
</jaxrs:providers>
...
</jaxrs:server>
<bean id="jaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
<property name="jaxbElementClassNames" ref="elements" />
</bean>
<util:list id="elements">
<value>com.model.City</value>
<value>com.model.Cities</value>
</util:list>
I would like to use jaxb2-marshaller for scanning all the POJOS in a package(com.model). Any usage help is appreciated.
You can call a method of another bean that provides the list of classes something like:
<property name="jaxbElementClassNames" value="#{ myBean.classNamesFromPackage}"/>
Configure myBean that takes package name as a property and has getClassNamesFromPackage method:
<bean id="myBean" class="x.y.z.MyBean">
<property name="packageName" value="com.model" />
</bean>
In getClassNamesFromPackage method of MyBean, you can use the code suggested in How do I read all classes from a Java package in the classpath?.

How invoke a Spring Integration application from your CXF endpoint

i'm using Apache CXF web services and Spring Integration and i don't now how to invoke a Spring Integration application from your CXF endpoint.
I have experience working on Apache Camel and is very easy to resolve this problem...but in Spring Integration i don't have any idea....
My lines code are:
In webservices-definition-beans.xml:
<!-- Load CXF modules from cxf.jar -->
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<!--Exposing the HelloWorld service as a SOAP service -->
<bean id="jaxbBean"
class="org.apache.cxf.jaxb.JAXBDataBinding"
scope="prototype"/>
<bean id="jaxws-and-aegis-service-factory"
class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"
scope="prototype">
<property name="dataBinding" ref="jaxbBean"/>
<property name="serviceConfigurations">
<list>
<bean class="org.apache.cxf.jaxws.support.JaxWsServiceConfiguration"/>
<bean class="org.apache.cxf.aegis.databinding.AegisServiceConfiguration"/>
<bean class="org.apache.cxf.service.factory.DefaultServiceConfiguration"/>
</list>
</property>
</bean>
<jaxws:endpoint id="helloWorld"
serviceName="HelloWorldService"
implementorClass="com.datys.cxf.HelloWorldService"
address="/HelloWorld">
<jaxws:serviceFactory>
<ref bean="jaxws-and-aegis-service-factory"/>
</jaxws:serviceFactory>
</jaxws:endpoint>
In service-definition-beans.xml:
<gateway id="HelloWorldService"
default-request-channel="requestStrings"
default-reply-channel="replyStrings"
service-interface="com.datys.cxf.HelloWorldService">
<method name="sayHello"/>
</gateway>
<channel id="requestStrings"/>
<channel id="replyStrings"/>
<!--<channel id="filesOut"/>-->
<service-activator input-channel="requestStrings"
output-channel="filesOut"
ref="handler" method="handleString"/>
<file:outbound-channel-adapter id="filesOut"
directory="file:D:/OUTPUT"/>
<beans:bean id="handler" class="org.springframework.integration.samples.filecopy.Handler"/>
But when i deploy and call web services with client-webservices return this error:
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Could not instantiate service class com.datys.cxf.HelloWorldService because it is an interface.
at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:171)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:94)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:240)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:210)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:103)
at $Proxy29.sayHello(Unknown Source)
Probably the simplest option is to configure a <gateway>. That allows you to provide any interface that you can inject into your endpoint and invoke it to initiate a message flow. Under the covers, the interface is implemented in the same way as other "ProxyFactoryBean" implementations in Spring (e.g. remoting via RMI, HttpInvoker, etc).
Here's a relevant section from the reference manual:
http://static.springsource.org/spring-integration/docs/2.1.x/reference/htmlsingle/#gateway-proxy

Spring DB2 JPA Entity Manager Problem

I'm trying to configure Spring, JPA and DB2 in order to have the entity manager instance to be used in my spring controllers but according how I have configured Spring this not happens.
These are the two attempts of configuration of spring:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" />
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="em" />
</bean>
<bean id="em"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fileUtility" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="database" value="DB2" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
the second is this:
<!-- Entity manager factory bean. -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sample" />
</bean>
<!-- Entity manager bean. -->
<bean id="em" factory-bean="entityManagerFactory"
factory-method="createEntityManager" />
and the entity manager is injected in this way:
<bean id="messageService" class="utilities.services.impl.MessageServiceImpl">
<property name="entityManager" ref="em" />
</bean>
but I have always this exception:
Caused by: java.lang.IllegalArgumentException: methods with same signature createEntityManager() but incompatible return types: [interface com.ibm.websphere.persistence.WsJpaEntityManager, interface org.apache.openjpa.persistence.OpenJPAEntityManagerSPI]
I don't know how can be fixed. Has anyone encountered this problem?
Thanks in advance.
[EDIT]
This is my persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<persistence-unit name="fileUtility"
transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:db2://localhost:50000/db2admin" />
<property name="openjpa.ConnectionDriverName" value="COM.ibm.db2.jdbc.app.DB2Driver" />
<property name="openjpa.ConnectionUserName" value="db2admin" />
<property name="openjpa.ConnectionPassword" value="XXXX" />
<property name="openjpa.FlushBeforeQueries" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
<persistence-unit name="fileUtility2" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>file_ds</jta-data-source>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72"/>
</properties>
</persistence-unit>
</persistence>
WebSphere has a JPA implementation bundled. So no need to add openjpa to your lib. In fact, WebSphere is using OpenJPA, so you are not losing anything. Look here for more details
When using a jda-data-source, you need to have transaction-type="JTA". Also, you should not specify connection properties - they are specified in the datasource.
And get rid of the <provider> - the document I linked says:
If no JPA provider is configured in the element of the persistence.xml file within an EJB module, the default JPA provider that is currently configured for this server is used
I believe you're doing the wrong configuration, because you're configuring it "à la Tomcat". If you're using a Java EE application server, such as WAS, you should:
In Spring application context xml file
configure the DAO bean by a <bean> definition
configure the JNDI definition for the datasource created in the application server via a
<jee:jndi-lookup>
definition; the
name
attribute should be
persistence/XXX, where XXX shall match the
<persistence-unit name="XXX" transaction-type="JTA">
in persistence.xml file
The id attribute in the
<jee:jndi-lookup id=YYY> should point to the
name=YYY parameter of the Entity Manager definition in the DAO, this is to say,
#PersistenceContext(name=YYY) EntityManager em;
Specify
<tx:annotation-driven /> and
<tx:jta-transaction-manager />
In file
web.xml of your web app you should include a definition using the xml tag
<persistence-unit-ref> whose
<persistence-unit-ref-name> parameter shall be the
persistence/XXX JNDI name as specified in persistence.xml (shown above).
Finally, you should create a JNDI definition in the application server (AS dependant) that defines the JNDI name for the JDBC connection. This name should match the
<jta-data-source> xml tag in the persistence.xml file, and it is the only link between the JPA definition and the JDBC defined in the application server.
To round up:
Application Context Spring file
<bean class="DAO implementation class" />
<jee:jndi-lookup id="YYY" jndi-name="persistence/XXX" />
<tx:annotation-driven />
<tx:jta-transaction-manager />
persistence.xml file
<persistence-unit name="XXX" transaction-type="JTA">
<jta-data-source>jdbc/DSN</jta-data-source>
</persistence-unit>
web.xml file
...
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/XXX</persistence-unit-ref-name>
</persistence-unit-ref>
...
DAO (only #PersistenceContext shown)
...
#PersistenceContext(name = "YYY")
EntityManager em;
...
Application Server: jdbc/DSN links to the connection definition, where the driver for the DBM is. Depends on both the AS and the DBM used.
Thus, you may see the connection between the DAO -> Spring Application Context file -> persistence.xml and web.xml files -> Application Server JNDI names. IF you're using a full Java EE application server (such as WAS, Weblogic or GlassFish) you don't have to use Spring interface modules; only defnitions in the app server (see Spring documentation, section 12.6.3).

Resources