i just installed a OpenLDAP server and trying to connect, add, get users,groups on it.
Since i 'm very new on ldap it would be very nice if you share tutorials about spring-ldap :/
So here's my bind code:
User class:
public class User implements Serializable{
private String id;
private String userName;
private String firstName;
private String lastName;
private String email;
private String password;
private String department;
private String groups[];
}
save method:
public User save( final User user ){
init();
Name dn = buildDn( user );
Attributes attributes = buildAttributes( user );
logger.info( "trying to save DN " + dn + " and attributes " + attributes );
ldapTemplate.bind( dn, null, attributes );
// Update Groups
for( String group : user.getGroups() ){
try{
DistinguishedName groupDn = new DistinguishedName();
groupDn.add( "ou", "Groups" );
groupDn.add( "cn", group );
DirContextOperations context = ldapTemplate.lookupContext( groupDn );
context.addAttributeValue( "memberUid", user.getUserName() );
ldapTemplate.modifyAttributes( context );
}
catch( Exception e ){
e.printStackTrace();
}
}
logger.info( "successfuly saved " );
return user;
}
buildDN:
private Name buildDn( final User user ){
DistinguishedName dn = new DistinguishedName();
dn.add( "ou", "People" );
if( user.getDepartment() != null ){
dn.add( "ou", user.getDepartment() );
}
dn.add( "uid", user.getUserName() );
return dn;
}
buildAttributes:
private Attributes buildAttributes( final User user ){
Attributes attrs = new BasicAttributes();
BasicAttribute ocattr = new BasicAttribute( "objectClass" );
// ocattr.add( "person" );
ocattr.add( "inetOrgPerson" );
attrs.put( ocattr );
attrs.put( "cn", user.getFirstName() );
// attrs.put( "rdn", "uid" ); // TODO check how to assign rdn
attrs.put( "sn", user.getLastName() );
attrs.put( "userPassword", "{SHA}" + this.encrypt( user.getPassword() ) );
attrs.put( "mail", user.getEmail() );
return attrs;
}
and here's the exception:
org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - No Such Object]; nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name 'uid=sercan,ou=People'
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:183)
at org.springframework.ldap.core.LdapTemplate.executeWithContext(LdapTemplate.java:820)
at org.springframework.ldap.core.LdapTemplate.executeReadWrite(LdapTemplate.java:812)
at org.springframework.ldap.core.LdapTemplate.bind(LdapTemplate.java:990)
at com.***.usr.mng.library.service.impl.UserServiceImpl.save(UserServiceImpl.java:101)
at com.***.usr.mng.library.handler.impl.UserHandlerImpl.saveUser(UserHandlerImpl.java:45)
at com.***.usr.mng.library.handler.impl.UserManagementHandlerImpl.handleRequest(UserManagementHandlerImpl.java:62)
at com.***.usr.mng.service.controller.UserManagementController.processRequest(UserManagementController.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name 'uid=sercan,ou=People'
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3112)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3033)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2840)
at com.sun.jndi.ldap.LdapCtx.c_bind(LdapCtx.java:420)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_bind(ComponentDirContext.java:295)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.bind(PartialCompositeDirContext.java:215)
at javax.naming.directory.InitialDirContext.bind(InitialDirContext.java:182)
at org.springframework.ldap.core.LdapTemplate$21.executeWithContext(LdapTemplate.java:992)
at org.springframework.ldap.core.LdapTemplate.executeWithContext(LdapTemplate.java:817)
While the code you present will certainly work for doing what you want there are a couple of things included in the library that will make things easier for you.
The simplest approach is to use the Object-Directory-Mapping - ODM - feature, which pretty much removes all boiler plate and uses declarative mapping on the domain classes instead.
If you decide to continue using DirContextAdapter I would encourage you to take full advantage of what it can do (more specifically you can submit a DirContextOperation instance directly to the designated bind method):
Name dn = buildDn(user);
DirContextAdapter context = new DirContextAdapter(dn);
context.setAttributeValues("objectclass", new String[] {"top", "person"});
context.setAttributeValue("cn", user.getFullname());
// populate more attributes
ldapTemplate.bind(context);
The reference documentation has plenty of examples, and there are also a couple of sample applications included with the source to help you get started (there's one simple sample using ODM, another one using DirContextOperations, and finally a complete user admin application using ODM).
Finally, please note that the DistinguishedName class is deprecated in version 2.x; you should use the LdapNameBuilder or the utility methods in LdapUtils for working with Distinguished Names (which you will typically not have to do if you use ODM).
I found the solution,
dn.add( "ou", "People" );
i'm trying to add person to People organizational unit, but it does not exist !
Thanks.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Working on a Spring MVC based project, I am getting the following code while I try to save review (Bean). I am able to get the data into controller successfully but for some reason getting a NULL pointer exception while saving.
Here is the code
-- JSP--
<div class="col-md-12">
<div class="p-b">
<cf:form action="${pageContext.request.contextPath}/reviews/add" id="reviewAction" modelAttribute="review" method="post" accept-charset="utf-8">
<div style="display:none">
<cf:input path="tutorId" type="hidden" name="tutorId" id="tutorId" value="" />
<cf:input path="studentId" type="hidden" name="studentId" id="studentId" value="${sessionScope.user.userId}" />
</div>
<label>Your Comment / Review</label>
<cf:textarea path="reviewMessage" name="reviewMessage" required="required"/>
<p class="text-right"><input type="submit" class="btn btn-default btn-sm" name="submit" value="Post"> </p>
</cf:form>
</div>
</div>
<cf:hidden path="userId" id="userId"/>
<script type="text/javascript">
$(document).ready(function () {
console.log("Calling getTutorId()");
getTutorId();
});
function getTutorId()
{
$('#tutorId').attr('value',$('#userId').val());
}
</script>
-- Controller --
#RequestMapping (value = "/add" , method = RequestMethod.POST)
public String addReview(#Valid #ModelAttribute Review review , BindingResult bindingResult, Model model) {
try {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getAllErrors().iterator().next().toString());
return "FindTutor";
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String newDate = dateFormat.format(date); //06/08/2016 15:59:48
review.setDate(newDate);
review.setReviewStatus("Disapproved");
//Just for testing purposes
System.out.println(review.getStudentId());
System.out.println(review.getTutorId());
System.out.println(review.getDate());
System.out.println(review.getReviewMessage());
System.out.println(review.getReviewStatus());
//Just for testing purposes
reviewBL.saveReview(review);
List<Subject> subjectList = subjectBL.getAllSubjects();
List<User> userList = manageUserBL.getAllUsers();
model.addAttribute("subjectList", subjectList);
model.addAttribute("userList", userList);
} catch (Exception e) {
e.printStackTrace();
}
return "FindTutor";
}
-- Business Logic Class --
#Service
public class ReviewBL {
private ReviewsMongoRepository reviewsMongoRepository;
public void saveReview(Review review)
{
if (StringUtils.isEmpty(review.getId())) {
review.setId(null);
}
reviewsMongoRepository.save(review);
}
}
-- Bean Class --
#Document (collection = "reviews")
public class Review {
#Id
private String Id;
private String tutorId;
private String studentId;
private String date;
private String reviewMessage;
private String reviewStatus;
// plus constructors also all of the getters and setters
}
I am getting the following error message, and as you can see the data (Model Attribute is successfully been captured in the controller but is not being saved in the database due to a NULL pointer exception error that I can't seem to find out why
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /reviews/add
java.lang.NullPointerException
at edu.bnu.fyp.stp.bl.ReviewBL.saveReview(ReviewBL.java:23)
at edu.bnu.fyp.stp.web.controller.student.ReviewController.addReview(ReviewControll er.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at edu.bnu.fyp.stp.web.filter.SessionFilter.doFilter(SessionFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
574939f19fcf9da523b63f8b // ID 1 (String)
57493a3e9fcf9da523b63f8c // ID 2 (String)
28/05/2016 13:16:59 //Date (String)
Great Tutor // Message (String)
Disapproved //Status (String)
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /WEB-INF/jsp/FindTutor.jsp
I was able to resolve this issue. It was because I didn't apply #Autowired on reviewsMongoRepository so it wasn't linked with the review bean. I corrected this and now it is working. Thank you
Inside ReviewBL.saveReview you are calling reviewsMongoRepository.save(review)
But I can see you havent initialized reviewsMongoRepository, this is just a reference type reffering to "nothhing." It might be the cause of your Null Pointer exception
I am currently trying to export content to a csv/xls file using primefaces exporter classes. I am generating a datatable component from javacode and pass it to the exporter class. It works fine, but I get very often a the following exception:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
I understand the exception, but not why it is thrown. The following message is called as an actionlistener by a primefaces command button:
public void export(MyBeanBeanClass bean, MyTable myTable, String format) {
FacesContext context = FacesContext.getCurrentInstance();
Exporter exporter = ExporterFactory.getExporterForType(format);
DataTable table = new DataTable();
String beanName = this.lookupManagedBeanName(bean);
List<Object[]> exportList = new ArrayList<Object[]>();
String outputFileName = "export";
boolean isPageOnly = false;
boolean isSelectionOnly = false;
String encodingType = "iso-8859-1";
MethodExpression preProcessor = null;
MethodExpression postProcessor = null;
// creating <p:datatable> component from java code -> see balusc's blog
// http://balusc.blogspot.de/2006/06/using-datatables.html#PopulateDynamicDatatable
// prepare datasource for export
for (MyRow row : myTable) {
Object[] rowContent = new Object[row.columnCount()];
for (int i = 0; i < rowContent.length; i++) {
rowContent[i] = row.get(i);
}
exportList.add(rowContent);
}
bean.setExportList(exportList);
// create primefaces datatable <p:datatable>
table.setValueExpression("value", createValueExpression("#{" + beanName + ".exportList}", List.class));
table.setVar("row");
// create columns and rows
for (int i = 0; i < myTable.getColumnCount(); i++) {
// Create <p:column>.
Column column = new Column();
table.getChildren().add(column);
// Create <h:outputText value="dynamicHeaders[i]"> for <f:facet name="header"> of column.
HtmlOutputText header = new HtmlOutputText();
header.setValue(this.getColumnTitle(this.getRenderedColumnNames().get(i)));
column.setHeader(header);
// Create <h:outputText value="#{dynamicItem[" + i + "]}"> for the body of column.
HtmlOutputText output = new HtmlOutputText();
output.setValueExpression("value", createValueExpression("#{row[" + i + "]}", String.class));
column.getChildren().add(output);
}
// export
try {
exporter.export(context, table, outputFileName, isPageOnly, isSelectionOnly, encodingType, preProcessor, postProcessor);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here's the xhtml of the command button:
<h:form>
<p:commandButton value="#{cc.attrs.exportXLS}" style="margin-top: 5px; width: 100%"
actionListener="#{cc.attrs.view.export(cc.attrs.bean, cc.attrs.view.tableOfData, "xls")}"
ajax="false" />
</h:form>
some information: bean is a simple viewscoped bean which stores the generated list (in function) for exporting it.
myTable contains the data which should be exported (will be transfered into an list of object array in function)
format contains "csv" or "xls".
here is the stacktrace:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:678)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:837)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.createResponseWriter(FaceletViewHandlingStrategy.java:1197)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:408)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:612)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
anybody got an idea why I get this excpetion?
kind regards
Alex
I solved the problem by adding the following line after the export call:
context.responseComplete();
I'll explain the situation.
I have an application web, java + spring + hibernate. Actually, i want to integrate DWR with Spring, so I did all the configuration and I think what I did works fine since I get this windows:
Now, we can focus on the findUsername(String username) methodo inside the dwr code:
#Autowired
UserBo userBo;
public boolean findUsername(String username) {
System.out.println("I'm in the DWR");
try {
User user = userBo.findByUsername(username);
if(user != null) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
System.out.println(e.toString());
return false;
}
}
And this is the code of userBo.findByUsername(String username) methodo:
public User findByUsername(String username) {
System.out.println("I'm in the BO");
return userDao.findByUsername(username);
}
And the DAO Code:
#Transactional
public User findByUsername(String username) {
session = sessionFactory.openSession();
System.out.println("I'm in the DAO");
String hql = "FROM User Tab WHERE Tab.username= :username";
Query query = session.createQuery(hql);
query.setParameter("username", username);
#SuppressWarnings("unchecked")
List<User> userFound = (List<User>) query.list();
if (userFound.size() > 0) {
session.close();
return userFound.get(0);
}
return null;
}
But when the code reach userBo.findByUsername(username); method call i get the NullPointerException.
I'm pretty sure the bo + day working good because I've used it in some other part of the application.
I don't understand the problem.
Can someone help me?
EDIT: The StackTrace
lcc.dwr.CCServiceDWR.findUsername(CCServiceDWR.java:26)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
org.directwebremoting.spring.DwrController.handleRequestInternal(DwrController.java:234)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
If spring context is fully initialized spring guarantees that all #autowired fields are not-null beans.
However if you call some bean's method before spring context is fully initialized, the #autowired field can be null.
Check if you call findUsername(String username) before context is ready and if yes - this may be the reason...
If you want to do some call and be sure that context is ready try such pattern:
#Component
public class SpringContextMonitor implements ApplicationListener<ApplicationEvent> {
#Autowired
private SomeDao dao;
...
#Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
onStart((ContextRefreshedEvent) event);
}
}
private void onStart(ContextRefreshedEvent event) {
// do your initialization here
dao.getSomething();
dao2.getSomething();
...
}
...
}
In that code, method onStart is call just after context become ready.
Found the problem: I misses this line in the dwr-servlet.xml
<context:component-scan base-package="lcc.*" />
I'm looking for a how to add a component in my table. My table is using a JPAContainer as datasource. I'm trying using addContainerProperty but doesn't work and returns an exception.
I'm trying this
private final CustomJPAContainer<Curriculum> datasource = new CustomJPAContainer<Curriculum>(Curriculum.class);
Button btnView = new Button();
Table tabela = new Table("",datasource);
tabela.addContainerProperty("View", Button.class, null);
//exception
java.lang.UnsupportedOperationException
at com.vaadin.addon.jpacontainer.JPAContainer.addContainerProperty(JPAContainer.java:666)
at com.vaadin.ui.AbstractSelect.addContainerProperty(AbstractSelect.java:806)
at com.vaadin.ui.Table.addContainerProperty(Table.java:4260)
at br.ind.ibg.views.VisualizarCurriculum.buildLayout(VisualizarCurriculum.java:58)
at br.ind.ibg.views.VisualizarCurriculum.<init>(VisualizarCurriculum.java:36)
at br.ind.ibg.utils.MenuSistema$1.menuSelected(MenuSistema.java:60)
at com.vaadin.ui.MenuBar.changeVariables(MenuBar.java:186)
at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:396)
at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:221)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Any idea ?
/** edited */
I solved the problem using setGeneratedColumn()
Here how I did.
public class ButtonColumnGenerator implements Table.ColumnGenerator{
private static final long serialVersionUID = 1L;
#Override
public Object generateCell(Table source, Object itemId, Object columnId) {
Property prop = source.getItem(itemId).getItemProperty(columnId);
Button btnView = new Button();
btnView.setData(itemId);
btnView.setDescription("Curriculum: " + itemId);
btnView.setIcon(new ThemeResource("../icons/eye.png"));
btnView.setWidth("20px");
btnView.setHeight("20px");
btnView.setStyleName(Reindeer.BUTTON_LINK);
return btnView;
}
}
/*** my app */
Button btnView = new Button();
Table tabela = new Table("",datasource);
tabela.setVisibleColumns(new Object[]{"idCurriculum", "nome", "cpf"});
tabela.setColumnHeaders(new String[] {"#", "Nome", "Cpf"});
tabela.addGeneratedColumn("", new ButtonColumnGenerator());
now works !
Adding UI components to the data source of a select component (Table, Tree, TreeTable, ComboBox, ...) is the wrong approach for your problem. The container data source of a Table component only contains the data model of the table and not the components that will display this data.
So, instead of adding properties to the JPAContainer (which is disallowed for this container as it handles its properties internally), you set a custom com.vaadin.ui.TableFieldFactory to your table with Table.setTableFieldFactory(TableFieldFactory fieldFactory).
I have a form that inserts into a database however before I preform the insert I check if there are existing records. I am unable to insert the record and I am getting a StackOverflow Error.
Can someone tell me what causes this error and what I can do to get rid of it? If I remove the check hasRecords the code preforms fine. Its almost like the code doesn't want to access the database at this point. I have created different types of function to preform he check here for records but at this point I keep getting the same error StackOverflow
Code
com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
public String getMonitoringStDate(Integer crimeRecNo,
Integer socialSecurityNumber) throws Exception {
return this.getMonitoringStDate(crimeRecNo, socialSecurityNumber);
}
DAO for getMonitoringStDate
public String getMonitoringStDate(Integer crimeRecNo, Integer socialSecurityNumber){
//select the minimum start date in event there is several records although this will not be allowed
String sql = "select IFNULL(min(monitoringStDate),'0') as monitoringStDate from tblmonitoring where crimeRecNo = ? and socialSecurityNumber = ?";
String monitoringStDate = (String)getJdbcTemplate().queryForObject(sql, new Object[]{crimeRecNo,socialSecurityNumber}, String.class);
return monitoringStDate;
}
I also have the following listeners registered:
Listeners
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
Code
DAO
public boolean hasMonitoringRecord(Integer crimeRecNo, Integer socialSecurityNumber){
//select a count of monitoring records there should be only one monitoring record
String sql = "select count(*) as monitoringStDate from tblmonitoring where crimeRecNo = ? and socialSecurityNumber = ?";
Integer count = (Integer)getJdbcTemplate().queryForObject(sql, new Object[]{crimeRecNo,socialSecurityNumber}, Integer.class);
if(count > 0 ){
return true;
}else{
return false;
}
}
Controller
if(result.hasErrors()){
myMonitoringTypeList.put("monitoringTypeList",this.monitoringTypeManager.getListOfMonitoringType());
model.addAttribute("icon", "ui-icon ui-icon-circle-close");
model.addAttribute("results", "Error: Unable to Save Record!");
model.addAttribute("monitoringType",myMonitoringTypeList);
model.addAttribute("monitoring",monitoring);
model.addAttribute("records", session.getAttribute("records"));
model.addAttribute("crimeRecNo",session.getAttribute("crimeRecNo"));
//return the user to the page they were on initially not the first page but the one with the error
return new ModelAndView("monitoringList","page",session.getAttribute("page"));
}else{
int crimeRecNo = monitoring.getCrimeRecNo();
int socialSecurityNumber = monitoring.getSocialSecurityNumber();
logger.info("No errors going to process records");
logger.info("CrimeRecNo is " + monitoring.getCrimeRecNo());
logger.info("SocialSecurity Number is " + monitoring.getSocialSecurityNumber());
//check if a record already exists. if one exist do an update else do an insert
//to check if the record exists we can simply get the start date
String dbMonitoringStDate = monitoringManager.getMonitoringStDate(crimeRecNo,socialSecurityNumber);
logger.info("The dbMonitoringStDate is " + dbMonitoringStDate);
if(monitoringManager.hasMonitoringRecord(crimeRecNo, socialSecurityNumber)){
logger.info("Has monitoring record");
//do an update
monitoringManager.updateMonitoringRecord(monitoring);
model.addAttribute("icon", "ui-icon ui-icon-circle-check");
model.addAttribute("results", "Record Was Updated");
}else {
logger.info("Does not have monitoring record");
//do an insert
monitoringManager.saveMonitoringRecord(monitoring);
model.addAttribute("icon", "ui-icon ui-icon-circle-check");
model.addAttribute("results", "Record Was Saved");
}
Error
7035 [http-bio-8084-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#6f138f45
7035 [http-bio-8084-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:972)
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:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.StackOverflowError
at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
at com.crimetrack.service.MonitoringManager.getMonitoringStDate(MonitoringManager.java:60)
Look at your method definition:
public String getMonitoringStDate(Integer crimeRecNo,
Integer socialSecurityNumber) throws Exception {
return this.getMonitoringStDate(crimeRecNo, socialSecurityNumber);
}
The only thing this method does is calling itself. So obviously, you have an infinite recursion loop.