I have a issue with my Spring.Net configuration where its not injecting an object. I have a CommService to which an object named GeneralEmail is injected to. Here is the configuration:
<!-- GeneralMail Object -->
<object id="GeneralMailObject" type="CommUtil.Email.GeneralEmail, CommUtil">
<constructor-arg name="host" value="xxxxx.com"/>
<constructor-arg name="port" value="25"/>
<constructor-arg name="user" value="xxxx#xxxxx.com"/>
<constructor-arg name="password" value="xxxxx"/>
<constructor-arg name="template" value="xxxxx"/>
</object>
<!-- Communication Service -->
<object id="CommServiceObject" type="TApp.Code.Services.CommService, TApp">
<property name="emailService" ref="GeneralMailObject" />
</object>
The communication service object is again injected to many other aspx pages & service. In one scenario, I need to call the commnucation service from an static WebMethod. I try doing:
CommService cso = new CommService();
But when i try to get the emailService object, its null! why didn't the spring inject the GeneralMail object into my cso object? What am I doing wrong and how do I access the object from spring container.
Thanks in advance for the suggestions and solutions.
Reagrds,
Abdel Olakara
IApplicationContext ctx = ContextRegistry.GetContext();
CommService cso= (CommService)ctx.GetObject("CommServiceObject");
Related
I want to use the OpenID Connect client with Spring Java annotation.
Unfortunately, the sample Mitre ID Connect client is based on XML.
I managed to load XML by #ImportResource("classpath:servlet-context.xml")
but it would be much better to have pure Java annotation based solution.
I could not translate the following XML stuff into Spring Annotation:
<security:http auto-config="false" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"
pattern="/**">
<security:custom-filter before="PRE_AUTH_FILTER" ref="openIdConnectAuthenticationFilter" />
<security:logout />
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="openIdConnectAuthenticationProvider" />
</security:authentication-manager>
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="http://localhost:10239/test" />
</bean>
<util:set id="namedAdmins" value-type="org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority">
<bean class="org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority">
<constructor-arg name="subject" value="XXX" />
<constructor-arg name="issuer" value="http://localhost:10239/test" />
</bean>
</util:set>
The bean xml tag is similar to the #bean annotation. See http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
The util:set tag is similar to a method that returns a set of type org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority. However this method has the #bean annotation as well.
For security related tags you can extend WebSecurityConfigurerAdapter
see https://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/
I'm using spring mvc and dwr, I already made some tests and my configuration works, but now that I'm trying to access the database from the script I get a NullPointerException on this line:
List<Citas> citas = citasManager.select();
Obviously that means that the instance of "citasManager" is not being sent to the script but the property is defined on the bean, so I don't know the correct way I should define my bean so that the class "People" gets the instance.
My bean is defined as follows:
<bean id="dwr" class="dwr.People" scope="session">
<dwr:remote javascript="People">
<dwr:include method="createCrowd" />
<dwr:include method="getMatchingFromLargeCrowd" />
</dwr:remote>
<property name="citasManager" ref="citasManager" />
</bean>
I didn't know I was supossed to declare the setter method too. Even to everywhere else spring manages them on it's own.
<bean id="dwr" class="dwr.People" scope="session">
<dwr:remote javascript="People">
<dwr:include method="createCrowd" />
<dwr:include method="getMatchingFromLargeCrowd" />
<dwr:include method="setCitasManager" />
</dwr:remote>
<property name="citasManager" ref="citasManager" />
</bean>
I'm trying to achieve so that Thymeleaf can work together with Spring MVC 3 and use 2 view resolvers, one for jsp and one for html templates. I'd like my Thymeleaf ServletContextTemplateResolver to be asked first to attempt to resolve a view and if it can't find one, pass on to the Spring MVC 3 InternalResourceViewResolver.
I've set the order value of ServletContextTemplateResolver to 1 this way:
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="order" value="1" />
<property name="cacheable" value="false" />
</bean>
and the order of InternalResourceViewResolver" to 2 in the same fashion:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="order" value="2" />
</bean>
As I understand it from the docs the highest order is consulted last.
In the "views" folder I have one "index.jsp" and one "index.html" and my general idea is that first ServletContextTemplateResolver will be asked to attempt resolving and it will resolve to "index.html" if there is one, and only if no suitable view can be found by ServletContextTemplateResolver will the InternalResourceViewResolver be asked to resolve the view.
But the result I have is that when InternalResourceViewResolver is active, it resolves all views no matter what. If I comment it out then ServletContextTemplateResolver resolves fine.
Are these resolvers impossible to pair up in this fashion? What's the alternative?
Thymeleaf throws an error when trying to find pages outside of their view resolver instead of passing it onto the next view resolver. By setting the excludeViewNames, skips trying to resolve the view name within Thymeleaf. See my example code below.
/**
* Configures a {#link ThymeleafViewResolver}
*
* #return the configured {#code ThymeleafViewResolver}
*/
#Bean
public ThymeleafViewResolver thymeleafAjaxViewResolver()
{
String[] excludedViews = new String[]{
"login", "logout"};
AjaxThymeleafViewResolver resolver = new AjaxThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
/*
* This is how we get around Thymeleaf view resolvers throwing an error instead of returning
* of null and allowing the next view resolver in the {#see
* DispatcherServlet#resolveViewName(String, Map<String, Object>, Locale,
* HttpServletRequest)} to resolve the view.
*/
resolver.setExcludedViewNames(excludedViews);
return resolver;
}
I have made a project which is built on Maven+Spring 3.1+Spring MVC 3.1+Hibernate 4.1
In the transaction if I use the code:
Session session=sessionFactory.getCurrentSession();
session.save(user);
It gives the exception at the getCurrentSession():
SEVERE: Servlet.service() for servlet appServlet threw exception
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1024)
at com.company.cv.dao.UserDAO.saveUser(UserDAO.java:30)
at com.company.cv.service.UserService.saveUser(UserService.java:20)
at com.company.cv.HomeController.saveUser(HomeController.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
But if I use openSession instead of getCurrentSession no exceptions and code transaction completes successfully:
Session session = sessionFactory.openSession();
session.save(user);
What is the reason?
Thanks for the help
My applicationContext.xml:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/companycv" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.company.cv.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
servlet-context.xml:
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.company.cv" />
My service code:
#Service
public class UserService implements UserServiceIntf{
#Autowired
UserDAOIntf userDAO;
#Transactional
public void saveUser(User user) {
userDAO.saveUser(user);
}
}
My DAO code:
#Repository
public class UserDAO implements UserDAOIntf {
#Autowired
SessionFactory sessionFactory;
public void saveUser(User user) {
Session session=sessionFactory.getCurrentSession();
session.save(user);
}
}
You need add #Transactional annotation above your service method calling DAO method save. And since you have txManager defined in your app context you need not to manually manage the transactions.
One thing that I have observed you are doing wrong is that you are mixing the usage of Hibernate transaction API with the Spring managed transactions management abstraction. This is strictly not advised.
Session session=sessionFactory.getCurrentSession();
Transaction tx=session.beginTransaction(); // This is using Hibernate transaction API
session.save(user);
sessionFactory.getCurrentSession().save(user);
tx.commit();// This is using Hibernate transaction API
In the above code you are using hibernate transaction api to manage the transaction along with the Spring transaction management (when you annotate your Service method with transactional annotation)
You need to only use this
Session session=sessionFactory.getCurrentSession();
session.save(user);
sessionFactory.getCurrentSession().save(user);
Also as pointed out by others you have got duplicate datasource definitions listed.
And you mention that you can’t get sessionFactory which does not make sense as it is injected via Spring and you say that in the other case you have access to sessionFactory. There is no reason why this should happen.
UPDATE
So you are saying that you do have sessionFactory accessible in both cases but it’s not working in case of getCurrentSession. Having made all the changes suggested, the best advise will be to see what’s happening under the hood by enabling the Hibernate logging and Spring framework logging in log4j configuration ( if you are using log4j) track the relevant activity.
Your log4j configuration file would be something like this
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=<file-path>
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger
log4j.rootLogger=INFO, file
# Hibernate and Spring logging
log4j.logger.org.hibernate=DEBUG
log4j.logger.org.springframework.transaction=DEBUG
This would give you a clear picture.
It was because of Hibernate4. If you look at the Hibernate4 DOC like I should have done in the first place ( :D ) Hibernate4 you have openSession every time. I think Hibernate guys made it so that noobies like me will be forced to use new session every time. Because session is not thread safe. FYI Hibernate openSession() vs getCurrentSession()
I'm writing a WebScript in Alfresco using JS controller and I want to make a HTTP request to the local HTTP resource. This resource is a Java-based app and gives me its own REST API.
My WebScript is not a Share Component: so I don't have a remote object to call another webscript.
How can I make a HTTP request to the local resource (something like '/sdo/documents/getName?type=fl') from a WebScript?
EDIT: Alfresco is overriding the Spring Surf webscripts.container bean removing the remote definition (in web-scripts-application-context.xml of remote-api):
<bean id="webscripts.container" class="org.alfresco.repo.web.scripts.RepositoryContainer" parent="webscripts.abstractcontainer">
<property name="name"><value>Repository</value></property>
<property name="scriptObjects">
<map merge="true">
<entry key="paging">
<ref bean="webscripts.js.paging"/>
</entry>
</map>
<!-- ..... -->
</bean>
I suggest you include it again as a custom Javascript API root level object.
The remote root object comes from the Spring Surf framework, meaning you have it regardless of being developing your Web Scripts against the Alfresco repository or Share. As a proof, here's the source for a Web Script available in the public Alfresco CMIS server (-> Alfresco repository instance, admin/admin if you are asked to login):
var serviceUrl = (args.service === null) ? "/api/repository" : args.service;
var conn = remote.connect("alfresco");
var result = conn.get(stringUtils.urlEncodeComponent(serviceUrl));
var service = atom.toService(result.response);
var workspace = service.workspaces.get(0);
model.repo = workspace.getExtension(atom.names.cmisra_repositoryInfo);
The following snippet is taken from spring-surf-application-context.xml as found inside spring-webscripts-1.0.0.CI-SNAPSHOT.jar of Alfresco 3.4.0, which is where the remote root object gets its definition:
<bean id="webscripts.container" parent="webscripts.abstractcontainer" class="org.springframework.extensions.webscripts.LocalWebScriptRuntimeContainer">
<property name="name"><value>Spring Surf Container</value></property>
<property name="registry" ref="webscripts.registry" />
<property name="searchPath" ref="webframework.webscripts.searchpath" />
<property name="templateProcessorRegistry" ref="webframework.webscripts.registry.templateprocessor" />
<property name="scriptProcessorRegistry" ref="webframework.webscripts.registry.scriptprocessor" />
<property name="scriptParameterFactoryRegistry" ref="webscripts.web.scriptparameterfactoryregistry" />
<property name="configService" ref="web.config" />
<property name="scriptObjects">
<map merge="true">
<entry key="remote" value-ref="webframework.webscripts.scriptremote" />
</map>
</property>
<property name="processorModelHelper" ref="processor.model.helper"/>
<property name="extensibilityModuleHandler" ref="webscripts.extensibility.handler"/>
</bean>
<bean id="webframework.webscripts.scriptremote" class="org.springframework.extensions.webscripts.ScriptRemote">
<property name="configService" ref="web.config"/>
<property name="connectorProvider" ref="webframework.connector.provider"/>
</bean>