could not autowire no beans of type found, for service in hybris - autowired

<!-- Total Customer service dao facade-->
<bean id="totalCustomersDao"
class="de.hybris.training.core.dao.impl.TotalCustomersDaoImpl">
<property name="flexibleSearchService" ref="flexibleSearchService"/>
</bean>
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
<property name="totalCustomersDao" ref="totalCustomersDao"/>
</bean>
<bean id="totalCustomerFacade" class="de.hybris.training.core.facade.impl.TotalCustomerFacadeImpl">
<property name="totalCustomerService" ref="totalCustomerService"/>
</bean>
<bean id="usersFindJob" class=" de.hybris.training.core.job.UsersFindJob"
parent="abstractJobPerformable" >
</bean>
this is xml.
This is facade class
public class TotalCustomerFacadeImpl implements TotalCustomerFacade {
//TODO autowired or resoucre not work
private TotalCustomerService totalCustomerService ;
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
public TotalCustomerService getTotalCustomerService() {
return totalCustomerService;
}
public void setTotalCustomerService(TotalCustomerService totalCustomerService) {
this.totalCustomerService = totalCustomerService;
}
here for
private TotalCustomerService totalCustomerService ;
when i put autorwired, it says
could not autowire no beans of type found
WHen i write resource or resource(name=totalCustomerService)
it gives null pointer.
this is serviceimpl
public class TotalCustomerServiceImpl implements TotalCustomerService {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
#Autowired
private TotalCustomersDao totalCustomersDao;
public TotalCustomersDao getTotalCustomersDao() {
return totalCustomersDao;
}
public void setTotalCustomersDao(TotalCustomersDao totalCustomersDao) {
this.totalCustomersDao = totalCustomersDao;
} public List<CustomerModel> getAllCustomersNames (String name) { LOG.info("***********************************");
LOG.info("***********************************");
LOG.info("*************************getAllCustomersNames::");
LOG.info("***********************************");
LOG.info("***********************************");
List<CustomerModel> customerModels = totalCustomersDao.findAllCustomersFromDao( name);
return customerModels;
}
those are interfaces
public interface TotalCustomerService {
List<CustomerModel> getAllCustomersNames (String name);
}
public interface TotalCustomerFacade {
List<String> findCustomerContainingName(String firstName);
}
how can i solve this?
the paths are they are all in
de.hybris.training.core
divided like
dao
facade
service
what can i do? I need to go for that service. I tried lots of times. added autowired. removed , let it without any annotations but still same.
Also this did not work
#Autowired
#Qualifier("totalCustomerService")
private TotalCustomerService totalCustomerService ;

remove whitespace! class=" de.hybris.training
Change
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
to
<bean id="totalCustomerService" class="de.hybris.training.core.impl.TotalCustomerServiceImpl">

it is because of whitespace
class=" de.
here

Related

Tomcat 8 JNDI Setup for DataSource (Converting from Tomcat 7)

I have an older Java application that I'm deploying to newer JBoss servers with Tomcat 8/Java 8 (up from Tomcat 7 and Java 7). I'm having some JNDI issues after deploying to the new servers. I'll get the error:
javax.naming.OperationNotSupportedException: Context is read only
Currently, I have a pooled datasource bean being created and then another bean that configures the JNDI reference.
<bean id="dataSourceBean" class="oracle.ucp.jdbc.PoolDataSourceFactory" factory-method="getPoolDataSource" >
<property name="URL" value="${URL}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="connectionFactoryClassName" value="${connectionFactoryClassName}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="validateConnectionOnBorrow" value="true"/>
<property name="inactiveConnectionTimeout" value="${inactiveConnectionTimeout}"></property>
<property name="fastConnectionFailoverEnabled" value="true"></property>
<property name="maxStatements" value="${maxStatements}"></property>
<property name="loginTimeout" value="${loginTimeout}"></property>
<property name="timeToLiveConnectionTimeout" value="${timeToLiveConnectionTimeout}"></property>
<property name="initialPoolSize" value="${initialPoolSize}"></property>
</bean>
<bean id="jndiConfiger" class="com.uprr.app.cam.common.util.DataBaseJndiConfig">
<property name="jndiName" value="java:comp/env/jdbc/com.uprr.app.cam.cam1_admin_Pool1TXDS"></property>
<property name="dataSource" ref="dataSourceBean"></property>
</bean>
And then the java class to configure it:
public class DataBaseJndiConfig implements InitializingBean {
private static final Logger log = Logger.getLogger(DataBaseJndiConfig.class);
private static boolean hasRun = false;
private String jndiName;
private DataSource dataSource;
private InitialContext ic;
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataBaseJndiConfig(){
try {
log.error("IN JNDI CONFIG");
if(hasRun==false){
ic= new InitialContext();
ic.createSubcontext("java:comp");
ic.createSubcontext("java:comp/env");
ic.createSubcontext("java:comp/env/jdbc");
}
} catch (Exception e) {
log.error("Exception in the constructor of DataBaseJndiConfig :"+e);
}
}
public void afterPropertiesSet() {
try {
log.error("SETTING JNDI PROPERTIES");
if(hasRun==false){
if (dataSource != null && jndiName != null) {
ic.bind(jndiName, dataSource);
hasRun=true;
}
}
} catch (Exception e) {
log.error("Exception in the afterPropertiesSet of DataBaseJndiConfig :"+e);
}
}
}
The error comes when I first try and do a createSubcontext()
I've read some other threads that mention having a context.xml file with a tag but am having trouble deciphering what should do in that tag
Is it basically the "dataSourceBean" that would be converted to a tag? Then I'm guessing I could eliminate the "jndiConfiger" bean and should just be able do the JNDI reference without doing all that binding?

How to integrate swaggerUI with spring secure Rest services?

I have my spring project war which contains Secure REST services.I need to integrate these Rest Services with swagger UI but everytime I am getting an exception like:-"HTTP-401 Full Authenticatuion required to access the resource" for my below snippet code:
This is the configuration class which load REst APIS of my project war file
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
#Bean
public Docket petApi() {
This is docket class which creates swagger documentation.
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()
.pathMapping("/").directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class);
}
}
This is the controller class which has customized method getdocumentation method which will internally invoke the spring controllers and get the documentation provided I am using springfox-swagger-ui 2.0 maven dependency.
#Controller
public class Swagger2Controller {
public static final String DEFAULT_URL = "/v2/api-docs";
#Value("${springfox.documentation.swagger.v2.host:DEFAULT}")
private String hostNameOverride;
#Autowired
private DocumentationCache documentationCache;
#Autowired
private ServiceModelToSwagger2Mapper mapper;
#Autowired
private JsonSerializer jsonSerializer;
#RequestMapping(value = { "/Vijay" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
#ResponseBody
public ResponseEntity<Json> getDocumentation(#RequestParam(value = "group", required = false) String swaggerGroup) {
String groupName = Optional.fromNullable(swaggerGroup).or("default");
Documentation documentation = this.documentationCache.documentationByGroup(groupName);
if (documentation == null) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
Swagger swagger = this.mapper.mapDocumentation(documentation);
swagger.host(hostName());
return new ResponseEntity(this.jsonSerializer.toJson(swagger), HttpStatus.OK);
}
private String hostName() {
if ("DEFAULT".equals(this.hostNameOverride)) {
URI uri = ControllerLinkBuilder.linkTo(Swagger2Controller.class).toUri();
String host = uri.getHost();
int port = uri.getPort();
if (port > -1) {
return String.format("%s:%d", new Object[] { host, Integer.valueOf(port) });
}
return host;
}
return this.hostNameOverride;
}
}
Any Help or suggestion will be highly appreciated. provided I have already written security as non in context.xml file of respective spring project like
<mvc:default-servlet-handler />
<mvc:resources mapping="/webjars/*" location="classpath:/META-INF/resources/webjars" />
<mvc:resources mapping="/swagger-resources/*" location="classpath:/META-INF/resources/" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<bean class="com.swagger.config.SwaggerConfig" />
<bean class="com.swagger.controller.Swagger2Controller" />
But still getting exception as mentioned above

Accessing CAS Released Attributes Using Spring Security

I'm having difficulty figuring out just how exactly one would access CAS released attributes in a servlet using Spring Security and Spring MVC. Traditionally, in a Spring-less implementation, I'd do something like this
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// Gets the user ID from CAS
AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
final Map<String, Object> attributes = principal.getAttributes();
String userId = (String) attributes.get("userid");
// ...
}
When creating a servlet using Spring MVC, but without Spring Security, there seemed to be basically no difference in accessing the attributes:
#RequestMapping("/")
public String welcome(HttpServletRequest request)
{
// Get the user ID from CAS
AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();;
final Map<String, Object> attributes = principal.getAttributes();
userId = (String) attributes.get("userid");
// ...
}
However, after implementing Spring Security, request.getUserPrincipal() returns a CasAuthenticationToken rather than an AttributePrincipal. From what I noticed, none of the retrievable objects and data from this contained any of the CAS released attributes.
After a bit of looking around, I did notice something with mentioning the GrantedAuthorityFromAssertionAttributesUserDetailsService class, so I changed my security context .xml from
<security:user-service id="userService">
<security:user name="user" password="user" authorities="ROLE_ADMIN,ROLE_USER" />
</security:user-service>
<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="authenticationUserDetailsService">
<bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<constructor-arg ref="userService" />
</bean>
</property>
<property name="serviceProperties" ref="serviceProperties" />
<property name="ticketValidator">
<bean class="org.jasig.cas.client.validation.Saml11TicketValidator">
<constructor-arg value="https://localhost:8443/cas" />
</bean>
</property>
<property name="key" value="casAuthProviderKey" />
</bean>
to
<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="authenticationUserDetailsService">
<bean class="org.springframework.security.cas.userdetails.GrantedAuthorityFromAssertionAttributesUserDetailsService">
<constructor-arg>
<list>
<value>userid</value>
</list>
</constructor-arg>
</bean>
</property>
<property name="serviceProperties" ref="serviceProperties" />
<property name="ticketValidator">
<bean class="org.jasig.cas.client.validation.Saml11TicketValidator">
<constructor-arg value="https://localhost:8443/cas" />
</bean>
</property>
<property name="key" value="casAuthProviderKey" />
</bean>
Then, through a considerably more roundabout method, I could access the userid attribute by doing something like this:
#RequestMapping("/")
public String welcome(HttpServletRequest request)
{
CasAuthenticationToken principal = (CasAuthenticationToken) request.getUserPrincipal();
UserDetails userDetails = principal.getUserDetails();
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) userDetails.getAuthorities();
Iterator<SimpleGrantedAuthority> it = authorities.iterator();
String userid = it.next().getAuthority();
// ...
}
However, besides being a little more lengthy than previous implementations, it doesn't seem possible to support map multiple attributes from CAS (say, if CAS were also releasing firstName and lastName attributes).
Is there a better way of setting up the security context .xml to allow easier access of these attributes, especially if there are multiples that I want to use in a web app?
I think I figured it out. Outside of setting the attributes as authorities, which may be useful if you're using those to determine permission (i.e. hasAuthority('username')), it seems like the only other way is to construct your own UserDetails and UserDetailsService classes.
For example, MyUser:
package my.custom.springframework.security.userdetails;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class MyUser extends User
{
private static final long serialVersionUID = 1L;
private String id;
private String lastName;
private String firstName;
public MyUser(
String username,
String password,
String id,
String lastName,
String firstName,
Collection<? extends GrantedAuthority> authorities)
{
super(username, password, authorities);
this.id = id;
this.lastName = lastName;
this.firstName = firstName;
}
public String getId()
{
return id;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
}
Then, borrowing some of the structure of GrantedAuthorityFromAssertionAttributesUserDetailsService and JdbcDaoImpl, I created a MyUserDetailsService:
package my.custom.springframework.security.userdetails;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.sql.DataSource;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.cas.userdetails.AbstractCasAssertionUserDetailsService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public final class MyUserDetailsService extends AbstractCasAssertionUserDetailsService
{
public static final String DEF_USERS_BY_ID_QUERY = "select ?, id, last_name, first_name " +
"from users " + "where id = ?";
public static final String DEF_AUTHORITIES_BY_ID_QUERY = "select role " +
"from roles join users on users.username = roles.username " +
"where users.id = ?";
private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD";
private JdbcTemplate jdbcTemplate;
private String usersByIdQuery;
private String authoritiesByIdQuery;
public MyUserDetailsService(DataSource dataSource)
{
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.usersByIdQuery = DEF_USERS_BY_ID_QUERY;
this.authoritiesByIdQuery = DEF_AUTHORITIES_BY_ID_QUERY;
}
protected MyUser loadUserDetails(Assertion assertion)
{
AttributePrincipal attributePrincipal = assertion.getPrincipal();
String username = attributePrincipal.getName();
String id = (String) attributePrincipal.getAttributes().get("userid");
MyUser user = loadUser(username, id);
Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();
dbAuthsSet.addAll(loadUserAuthorities(id));
List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthsSet);
return createMyUser(username, user, dbAuths);
}
protected MyUser loadUser(String username, String id)
{
return jdbcTemplate.queryForObject(usersByIdQuery, new String[] { username, id },
new RowMapper<MyUser>()
{
public MyUser mapRow(ResultSet rs, int rowNum) throws SQLException
{
String username = rs.getString(1);
String id = rs.getString(2);
String lastName = rs.getString(3);
String firstName = rs.getString(4);
return new MyUser(username, NON_EXISTENT_PASSWORD_VALUE, id, lastName, firstName,
AuthorityUtils.NO_AUTHORITIES);
}
});
}
protected List<GrantedAuthority> loadUserAuthorities(String id)
{
return jdbcTemplate.query(authoritiesByIdQuery, new String[] { id },
new RowMapper<GrantedAuthority>()
{
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException
{
// TODO Replace with rolePrefix variable
String roleName = "ROLE_" + rs.getString(1);
return new SimpleGrantedAuthority(roleName);
}
});
}
protected MyUser createMyUser(String username,
MyUser userFromUserQuery, List<GrantedAuthority> combinedAuthorities)
{
return new MyUser(username, userFromUserQuery.getPassword(),
userFromUserQuery.getId(), userFromUserQuery.getLastName(), userFromUserQuery.getFirstName(),
combinedAuthorities);
}
}
Finally, I set the authenticationUserDetailsService in my casAuthenticationProvider to use this class, passing in a global datasource from my container (Tomcat 6 in this case):
...
<property name="authenticationUserDetailsService">
<bean class="my.custom.springframework.security.userdetails.MyUserDetailsService">
<constructor-arg>
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/my/conn"/>
</constructor-arg>
</bean>
</property>
...

Grails autowire inside Spring converter

I have something like this...
class DomainConverter implements GenericConverter {
private Class<Domain> classOfDomain;
private Class<DomainCommand> classOfDomainCommand;
public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() {
Set<GenericConverter.ConvertiblePair> convertiblePairs = new HashSet<GenericConverter.ConvertiblePair>();
convertiblePairs.add(new GenericConverter.ConvertiblePair(classOfDomain, classOfDomainCommand));
convertiblePairs.add(new GenericConverter.ConvertiblePair(classOfDomainCommand, classOfDomain));
return convertiblePairs;
}
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (classOfDomain.equals(sourceType.getType())) {
return this.convert((Domain) source);
} else {
return this.convertBack((DomainCommand) source);
}
}
protected DomainCommand convert(Domain definition){
...
}
protected Domain convertBack(DomainCommand command){
...
}
}
Do I have to wire it within the class or add it to the resources.groovy?
How do I create the DomainCommand so that I still have my autowiring
Looking at the Spring documentation you can see an example of bean declaration:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="example.MyCustomConverter"/>
</list>
</property>
</bean>
So you need to declare your converter and also the conversionService in your resources.groovy file.

is there an equivalent of EndpointInterceptorAdapter for the client?

Is there an equivalent of EndpointInterceptorAdapter for the client?
Because i need to intercept outgoing and incoming messages from the client and do some work with them.
EndpointInterceptorAdapter intercepts only endpoint messages.
I think you can use the SmartEndpointInterceptor
public class SmartEndpointInterceptorImpl implements
SmartEndpointInterceptor
{
public boolean handleRequest(MessageContext messageContext, Object endpoint)
throws Exception
{
SaajSoapMessage soapSaajMsg = (SaajSoapMessage)messageContext.getRequest();
return true;
}
public boolean handleResponse(MessageContext messageContext, Object endpoint)
throws Exception {
return true;
}
//I omitted two more methods
}
Well, i found the answer.
You have to create a class that implements ClientInterceptor.
i.e.
package com.coral.project.interceptor;
public class WebServiceClientInterceptor implements ClientInterceptor {
#Override
public boolean handleRequest(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean handleResponse(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean handleFault(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return false;
}
}
and define in spring-ws config file:
<bean id="crmClient" class="com.coral.project.clients.CrmClient">
<property name="defaultUri" value="..."/>
<property name="marshaller" ref="jaxb2Marshaller" />
<property name="unmarshaller" ref="jaxb2Marshaller" />
<property name="interceptors">
<list>
<bean class="com.coral.project.interceptor.WebServiceClientInterceptor" />
</list>
</property>
</bean>
and that's it.

Resources