I am migrating an application from older version of wicket to wicket 8. Some pages are working ok (simple pages such as login). These pages does not use the extension mechanism.
When I access to a page that has the mechanism it doesn't work. I don't know if this is a bug but I tried everything and couldn't find a solution.
I am using wicket 8.0.0-M5 (i kwnow that is not a stable release). Anybody had the same problem?
Here is my code:
WerklijstPageXXX.html
<html xmlns:wicket>
<body>
<wicket:extend>
<div wicket:id="panelXXX"></div>
</wicket:extend>
</body>
WerklijstPanelXXX.html
<wicket:head xmlns:wicket>
</wicket:head>
<wicket:panel xmlns:wicket>
<div wicket:id="filter">
<div wicket:id="label"></div>
</div>
</wicket:panel>
WerklijstPageXXX.java
public class WerklijstPageXXX extends BasePage {
private WerklijstPanelXXX werklijstPanel;
public WerklijstPageXXX() {
werklijstPanel = new WerklijstPanelXXX("panelXXX"){};
add(werklijstPanel);
}
#Override
public Panel getContextPanel(String id)
{
return werklijstPanel.getWerklijstFilterPanel();
}
WerklijstPanelXXX.java
public abstract class WerklijstPanelXXX extends Panel {
private static final Logger LOG = LoggerFactory
.getLogger(WerklijstPanelXXX.class);
private Panel filterPanel;
public WerklijstPanelXXX(String id) {
super(id);
WebMarkupContainer upperPanel = new WebMarkupContainer("filter");
filterPanel = new Panel("filterPanel") {
};
add(upperPanel);
upperPanel.add(new Label("label"));
}
public Panel getWerklijstFilterPanel() {
return filterPanel;
}
EDIT:
BasePage.html (part of it)
<div id="body" class="body">
<div id="aside" class="aside">
<div wicket:id="contextPanel"></div>
</div>
<div id="content" class="content">
<div class="padding">
<wicket:child></wicket:child>
</div>
</div>
</div>
BasePage.java
#Override
protected void onInitialize() {
super.onInitialize();
add(getContextPanel("contextPanel"));
addTabMenu();
addMenu();
addPatientBar();
}
Error:
Root cause:
org.apache.wicket.WicketRuntimeException: The component(s) below failed to render. Possible reasons could be that:
1) you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered),
2) if your components were added in a parent container then make sure the markup for the child container includes them in .
[WerklijstPanelXXX [Component id = panelXXX, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX, type = nl.philips.raris.web.werklijst.WerklijstPanelXXX, isVisible = true, isVersioned = true], children = [WebMarkupContainer [Component id = filter]]]
[WebMarkupContainer [Component id = filter, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX:filter, type = org.apache.wicket.markup.html.WebMarkupContainer, isVisible = true, isVersioned = true], children = [Component id = label]]
[Component id = label, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX:filter:label, type = org.apache.wicket.markup.html.basic.Label, isVisible = true, isVersioned = true]
[Panel [Component id = filterPanel, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = filterPanel, type = org.apache.wicket.markup.html.panel.Panel, isVisible = true, isVersioned = true]]
at org.apache.wicket.Page.checkRendering(Page.java:662)
at org.apache.wicket.Page.onAfterRender(Page.java:805)
at org.apache.wicket.markup.html.WebPage.onAfterRender(WebPage.java:209)
at org.apache.wicket.Component.afterRender(Component.java:919)
at org.apache.wicket.Component.render(Component.java:2335)
at org.apache.wicket.Page.renderPage(Page.java:987)
at org.apache.wicket.request.handler.render.WebPageRenderer.renderPage(WebPageRenderer.java:124)
at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:236)
at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912)
at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204)
at org.apache.wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:137)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
The Java and HTML component trees should match.
Your HTML states: <div wicket:id="*contextPanel*"></div>, but your Java code returns a Panel with id filterPanel instead.
public WerklijstPageXXX() {
werklijstPanel = new WerklijstPanelXXX("panelXXX"){};
add(werklijstPanel);
}
#Override
public Panel getContextPanel(String id) // HERE id is ignored
{
return werklijstPanel.getWerklijstFilterPanel(); // This returns a panel with id `filterPanel`
}
Related
I want to add Paging functionality in Spring Boot + Spring Data JPA App, I have Repository :
#Repository
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findAllByOrderByPostIdDesc(Pageable pageable);
}
and in Service class I have :
#Service
public class PostService {
#Autowired
private PostRepository postRepository;
public List<Post> findAll(Pageable pageable) {
return postRepository.findAllByOrderByPostIdDesc(pageable);
}
}
in the end Controller is
#Controller
public class HomeController {
#Autowired
private PostService postService;
#GetMapping(value = "/")
public String getHomePage(Model model, Pageable pageable){
model.addAttribute("postList", postService.findAll(pageable));
return "home";
}
}
the code above on http://localhost:8080 mapping I get all the records as response, but if I pass page and size params as http://localhost:8080/?page=0&size=1 I get paging working.
Now I want to make http://localhost:8080/?page=0&size=1 by default landing page address, and in HTML code how can I dynamically update values of params page and size which is :
<ul class="pagination justify-content-center mb-4">
<li class="page-item">
<a class="page-link" th:href="#{/(page=0,size=1)}">← Older</a>
</li>
<li class="page-item disabled">
<a class="page-link" th:href="#{/(page=0,size=1)}">Newer →</a>
</li>
</ul>
I have tried a many tricks but none worked for me!!
Update
I tried and added this class as suggested but #Nyle Hassan,
#Configuration
public class DefaultView extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers( ViewControllerRegistry registry ) {
registry.addViewController( "/" ).setViewName( "forward:/?page=0&size=10" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers( registry );
}
}
it resulted in :
2019-01-01 17:26:43.484 ERROR 3824 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] threw exception
java.lang.StackOverflowError: null
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:597) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:597) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:597) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:597) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:597) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
the code above on http://localhost:8080 mapping I get all the records as response
Are you sure about this? Which version of Spring Boot are you using? I checked latest version (2.1.1) and calling http://localhost:8080 without any query parameters will instantiate a Pageable object with page = 0, size = 20, no sorting. Just try to set a debug point to org.springframework.data.web.PageableHandlerMethodArgumentResolver#resolveArgument to learn, how Spring performs this binding.
This argument resolver also comes with an annotation, which allows you to change defaults, which are used, when query parameters are not present. You can use it like this:
#GetMapping(value = "/")
public String getHomePage(Model model, #PageableDefault(page=0, size = 1) Pageable pageable) {
...
}
Page 0 is annotation default, so this has the same effect:
#GetMapping(value = "/")
public String getHomePage(Model model, #PageableDefault(size = 1) Pageable pageable) {
...
}
in HTML code how can I dynamically update values of params page and size
Next time, please post two separate questions, but here it goes:
First, change List<Post> to Page<Post> in your repository and service. In your controller, bind the result to the model:
Page<Post> page = postService.findAll(pageable);
model.addAttribute("page", page); // page.getContent() contains the List<Page> now
And in the view, use the page to render paging links, e.g. like this:
<li class="page-item">
<a class="page-link" th:if="${page.hasPrevious()}" th:href="#{/(page=${page.previousPageable().getPageNumber()},size=${page.getSize()})}">← Older</a>
</li>
<li class="page-item disabled">
<a class="page-link" th:if="${page.hasNext()}" th:href="#{/(page=${page.nextPageable().getPageNumber()},size=${page.getSize()})}">Newer →</a>
</li>
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 learning wicket framework and while working with ajax I tried one example in which I want to display a panel with selected radio button's company name. But while doing this I am getting some error. Here I mentioned all details from my coding:
Test.java
public class Test extends WebPage {
private static final List<String> companies = Arrays.asList(new String[] {"Google","Microsoft","Yahoo"});
private ArrayList<String> compSelected = new ArrayList<String>();
private Panel panel;
public Test(final PageParameters parameters) {
final RadioChoice<String> companyList =
new RadioChoice<String>("companyNames",new Model(compSelected),companies);
companyList.add(new AjaxFormChoiceComponentUpdatingBehavior() {
#Override
protected void onUpdate(AjaxRequestTarget target) {
if("Google".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Google");
}
else if("Microsoft".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Microsoft");
}
else{
panel = new Panel1("panel1","Yahoo");
}
panel.setOutputMarkupId(true);
target.addComponent(panel);
}});
Form<?> form = new Form<Void>("form");
add(form);
form.add(companyList);
form.add(panel);
this.add(form);
}
}
Test.html
<form wicket:id="form">
<label><b>Company List:</b></label><br>
<span wicket:id="companyNames">radio button list will goes here</span><br>
<span wicket:id = "panel1" class="panel">panel goes here</span>
</form>
Panel1.java
#SuppressWarnings("serial")
public class Panel1 extends Panel{
public Panel1(String id,String cName) {
super(id);
add(new Label("msg", "selected company is:"+ cName));
}
}
Panel1.html
<body>
<wicket:panel>
<span wicket:id="msg">message goes here</span>
</wicket:panel>
</body>
WicketMessage: Can't instantiate page using constructor public demo.wicket.ajax.Test(org.apache.wicket.PageParameters) and argument Root cause:java.lang.IllegalArgumentException: argument child may not be null at org.apache.wicket.MarkupContainer.add(MarkupContainer.java:131) at demo.wicket.ajax.Test.(Test.java:46) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.apache.wicket.session.DefaultPageFactory.createPage(DefaultPageFactory.java:188) at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:65) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.newPage(BookmarkablePageRequestTarget.java:299) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.getPage(BookmarkablePageRequestTarget.java:321) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.processEvents(BookmarkablePageRequestTarget.java:234) at org.apache.wicket.request.AbstractRequestCycleProcessor.processEvents(AbstractRequestCycleProcessor.java:92) at org.apache.wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:1250) at org.apache.wicket.RequestCycle.step(RequestCycle.java:1329) at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1428) at org.apache.wicket.RequestCycle.request(RequestCycle.java:545) at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:468) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:301) 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:503) 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:314) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)
I am not sure what I did wrong here. can someone please help me to figure it out?
The problem is form.add(panel);. panel is null at that time. You initialize it in #onUpdate() but it is executed only after a click(?) on the radio buttons.
Solution:
Change panel type to WebMarkupContainer and initialize it in the page's constructor. Call panel.setOutputMarkupId(true) also in the constructor so the <span wicket:id="panel1"...> has an id in the rendered HTML and being able to be referenced later with JS to replace/update it. In #onUpdate() use something like panel = panel.replaceWith(new Panel1(panel.getId(), choice.getModelObject())); target.add(panel);
I am working with canvas.js charts.I need to populate date from servlet into the chart.I have tried a process but data is not coming to the Chart.I am posting the code i have tried..
In the Jsp end
<html>
<head>
<title>Chart JS Library Demo</title>
<style>
</style>
</head>
<body>
<canvas id="canvas" height="500" width="500"></canvas>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript" src="ts-chart-script.js"></script>
</body>
</html>
The js i am using for fetching the servlet
var TUTORIAL_SAVVY ={
/*Makes the AJAX calll (synchronous) to load a Student Data*/
loadStudentData : function(){
var formattedstudentListArray =[];
$.ajax({
async: false,
url: "StudentJsonDataServlet",
dataType:"json",
success: function(studentJsonData) {
console.log(studentJsonData);
$.each(studentJsonData,function(index,aStudent){
formattedstudentListArray.push([aStudent.mathematicsMark,aStudent.computerMark,aStudent.historyMark,aStudent.litratureMark,aStudent.geographyMark]);
});
}
});
return formattedstudentListArray;
},
/*Crate the custom Object with the data*/
createChartData : function(jsonData){
console.log(jsonData);
return {
labels : ["Mathematics", "Computers", "History","Literature", "Geography"],
datasets : [
{
fillColor : "rgba(255,0,0,0.3)",
strokeColor : "rgba(0,255,0,1)",
pointColor : "rgba(0,0,255,1)",
pointStrokeColor : "rgba(0,0,255,1)",
/*As Ajax response data is a multidimensional array, we have 'student' data in 0th position*/
data : jsonData[0]
}
]
};
},
/*Renders the Chart on a canvas and returns the reference to chart*/
renderStudenrRadarChart:function(radarChartData){
var context2D = document.getElementById("canvas").getContext("2d"),
myRadar = new Chart(context2D).
Radar(radarChartData,{
scaleShowLabels : false,
pointLabelFontSize : 10
});
return myRadar;
},
/*Initalization Student render chart*/
initRadarChart : function(){
var studentData = TUTORIAL_SAVVY.loadStudentData();
chartData = TUTORIAL_SAVVY.createChartData(studentData);
radarChartObj = TUTORIAL_SAVVY.renderStudenrRadarChart(chartData);
}
};
$(document).ready(function(){
TUTORIAL_SAVVY.initRadarChart();
});
Servlet i am using
package com.servlet;
#WebServlet("/StudentJsonDataServlet")
public class StudentJsonDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentJsonDataServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Student> listOfStudent = getStudentData();
Gson gson = new Gson();
String jsonString = gson.toJson(listOfStudent);
response.setContentType("application/json");
response.getWriter().write(jsonString);
}
private List<Student> getStudentData() {
List<Student> listOfStudent = new ArrayList<Student>();
Student s1 = new Student();
s1.setName("Sandeep");
s1.setComputerMark(75);
s1.setMathematicsMark(26);
s1.setGeographyMark(91);
s1.setHistoryMark(55);
s1.setLitratureMark(36);
listOfStudent.add(s1);
return listOfStudent;
}
}
Student Class
public class Student {
private String name;
private int ComputerMark;
private int MathematicsMark;
private int GeographyMark;
private int HistoryMark;
private int LitratureMark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getComputerMark() {
return ComputerMark;
}
public void setComputerMark(int computerMark) {
ComputerMark = computerMark;
}
public int getMathematicsMark() {
return MathematicsMark;
}
public void setMathematicsMark(int mathematicsMark) {
MathematicsMark = mathematicsMark;
}
public int getGeographyMark() {
return GeographyMark;
}
public void setGeographyMark(int geographyMark) {
GeographyMark = geographyMark;
}
public int getHistoryMark() {
return HistoryMark;
}
public void setHistoryMark(int historyMark) {
HistoryMark = historyMark;
}
public int getLitratureMark() {
return LitratureMark;
}
public void setLitratureMark(int litratureMark) {
LitratureMark = litratureMark;
}
}
This codes i am using as my chart and servlet interaction but getting error in the log that ,it is not finding the Gson.But i have included the jar .I am using gson-2.2.4.jar for it.
SEVERE: Servlet.service() for servlet [com.servlet.StudentJsonDataServlet] in context with path [/jQueryMenu] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.google.gson.Gson
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at com.servlet.StudentJsonDataServlet.doGet(StudentJsonDataServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
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:171)
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:408)
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:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Put the Gson jar where Tomcat will find it and load it.
From the Apache Tomcat documentation:
A class loader is created for each web application that is deployed in
a single Tomcat instance. All unpacked classes and resources in the
/WEB-INF/classes directory of your web application, plus classes and
resources in JAR files under the /WEB-INF/lib directory of your web
application, are made visible to this web application, but not to
other ones.
We are using Wicket 6+ and have a strange error on FileUpload.writeTo(file).
It's happening only to certain types of files (docx,xlsx,java) and only in one form. The same exact code works to attach files just fine in other places. Any help? Thank you.
HTML:
<div wicket:id="filesInput"/>
Java:
add(new org.apache.wicket.markup.html.form.upload.MultiFileUploadField("filesInput",
new PropertyModel<Collection<FileUpload>>(this, "uploads"), 5));
Error thrown on line fileUpload.writeTo(file); when called from form onSubmit.
private void writeToFile(FileUpload fileUpload, Attachment attachment) {
if (fileUpload == null) {
return;
}
File file = AttachmentUtils.getFile(attachment, jtracHome);
try {
fileUpload.writeTo(file);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
Error log:
2013-05-03 12:57:23,731 [http-bio-8084-exec-9] ERROR [org.apache.wicket.DefaultExceptionMapper] - Unexpected error occurred
org.apache.wicket.WicketRuntimeException: Method onFormSubmitted of interface org.apache.wicket.markup.html.form.IFormSubmitListener targeted at [SpaceItemViewForm [Component id = form]] on component [SpaceItemViewForm [Component id = form]] threw an exception
at org.apache.wicket.RequestListenerInterface.internalInvoke(RequestListenerInterface.java:268)
at org.apache.wicket.RequestListenerInterface.invoke(RequestListenerInterface.java:216)
at org.apache.wicket.core.request.handler.ListenerInterfaceRequestHandler.invokeListener(ListenerInterfaceRequestHandler.java:240)
at org.apache.wicket.core.request.handler.ListenerInterfaceRequestHandler.respond(ListenerInterfaceRequestHandler.java:226)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:840)
at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:254)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:211)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:282)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:244)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:188)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:267)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
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:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.InvocationTargetException
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:601)
at org.apache.wicket.RequestListenerInterface.internalInvoke(RequestListenerInterface.java:258)
... 31 more
Caused by: java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\aeb\AppData\Roaming\NetBeans\7.2.1\apache-tomcat-7.0.27.0_base\temp\upload_9108b655_6177_4450_8e82_a767f101dd40_1997755963.tmp (The system cannot find the file specified)
at info.jtrac.JtracImpl.writeToFile(JtracImpl.java:405)
at info.jtrac.JtracImpl.storeScopeOfWork(JtracImpl.java:2053)
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:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
at $Proxy11.storeScopeOfWork(Unknown Source)
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:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy12.storeScopeOfWork(Unknown Source)
at info.jtrac.wicket.SpaceItemViewFormPanel$SpaceItemViewForm.onSubmit(SpaceItemViewFormPanel.java:433)
at org.apache.wicket.markup.html.form.Form$9.component(Form.java:1246)
at org.apache.wicket.markup.html.form.Form$9.component(Form.java:1240)
at org.apache.wicket.util.visit.Visits.visitPostOrderHelper(Visits.java:274)
at org.apache.wicket.util.visit.Visits.visitPostOrder(Visits.java:245)
at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1239)
at org.apache.wicket.markup.html.form.Form.process(Form.java:921)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:767)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:700)
... 36 more
Caused by: java.io.FileNotFoundException: C:\Users\aib\AppData\Roaming\NetBeans\7.2.1\apache-tomcat-7.0.27.0_base\temp\upload_9108b655_6177_4450_8e82_a767f101dd40_1997755963.tmp (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.apache.wicket.util.upload.DiskFileItem.write(DiskFileItem.java:439)
at org.apache.wicket.markup.html.form.upload.FileUpload.writeTo(FileUpload.java:234)
at info.jtrac.JtracImpl.writeToFile(JtracImpl.java:402)
So this is the code where the exception is coming from:
if (!outputFile.renameTo(file))
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream(new FileInputStream(outputFile));
out = new BufferedOutputStream(new FileOutputStream(file));
Streams.copy(in, out);
}
finally
{
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
javadoc:
This method is only guaranteed to work once, the first time it is invoked for a
particular item. This is because, in the event that the method renames a temporary file, that
file will no longer be available to copy or rename again at a later time.
The exception is coming from the opening of the "outputFile" File - as if it is no longer there. Is it possible the renameTo succeeded to do something with the file, but the renameTo method still returned with false? Can you set a breakpoint there and see what is happening? Maybe somehow you DO call it twice?
From renameTo's javadoc:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
I just ran the wicket MultiUploadPage example and everything is working.
Give us more details about your page structure, what's different about your page?
WicketApplication.java
public class WicketApplication extends WebApplication {
private Folder uploadFolder = null;
#Override
public Class<? extends WebPage> getHomePage(){
return HomePage.class;
}
public Folder getUploadFolder(){
return uploadFolder;
}
#Override
public void init(){
super.init();
getResourceSettings().setThrowExceptionOnMissingResource(false);
uploadFolder = new Folder(System.getProperty("java.io.tmpdir"), "wicket-uploads");
uploadFolder.mkdirs();
getApplicationSettings().setUploadProgressUpdatesEnabled(true);
}
}
HomePage.java
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
private final FileListView fileListView;
public HomePage(final PageParameters parameters){
Folder uploadFolder = getUploadFolder();
final FeedbackPanel uploadFeedback = new FeedbackPanel("uploadFeedback");
add(uploadFeedback);
final FileUploadForm simpleUploadForm = new FileUploadForm("simpleUpload");
add(simpleUploadForm);
add(new Label("dir", uploadFolder.getAbsolutePath()));
fileListView = new FileListView("fileList", new LoadableDetachableModel<List<File>>(){
private static final long serialVersionUID = 1L;
#Override
protected List<File> load(){
return Arrays.asList(getUploadFolder().listFiles());
}
});
add(fileListView);
}
private class FileListView extends ListView<File>{
private static final long serialVersionUID = 1L;
public FileListView(String name, final IModel<List<File>> files){
super(name, files);
}
#Override
protected void populateItem(ListItem<File> listItem){
final File file = listItem.getModelObject();
listItem.add(new Label("file", file.getName()));
listItem.add(new Link<Void>("delete"){
private static final long serialVersionUID = 1L;
#Override
public void onClick(){
Files.remove(file);
info("Deleted " + file);
}
});
}
}
private class FileUploadForm extends Form<Void>{
private static final long serialVersionUID = 1L;
private final Collection<FileUpload> uploads = new ArrayList<FileUpload>();
public FileUploadForm(String name){
super(name);
setMultiPart(true);
add(new MultiFileUploadField("fileInput", new PropertyModel<Collection<FileUpload>>(this, "uploads"), 5, true));
setMaxSize(Bytes.kilobytes(100000));
}
#Override
protected void onSubmit(){
for (FileUpload upload : uploads){
File newFile = new File(getUploadFolder(), upload.getClientFileName());
try{
newFile.createNewFile();
upload.writeTo(newFile);
HomePage.this.info("saved file: " + upload.getClientFileName());
} catch (Exception e){
throw new IllegalStateException("Unable to write file");
}
}
}
}
private Folder getUploadFolder(){
return ((WicketApplication) Application.get()).getUploadFolder();
}
}
HomePage.html
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Apache Wicket Quickstart</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="Stylesheet" />
</head>
<body>
The multi upload field is based on javascript found
<a target="_blank" href="http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/">here</a>.
<br />
<br /> Wicket can also handle file uploads via AJAX, please see AJAX
examples section. AJAX Functionality is not included in this example to
keep things simple.
<br />
<br />
<form wicket:id="simpleUpload">
<fieldset>
<legend>Upload form</legend>
<p>
<div wicket:id="fileInput" class="mfuex" />
</p>
<input type="submit" value="Upload!" />
</fieldset>
</form>
<div><span wicket:id="uploadFeedback" /></div>
<div>
<h4>Current files in <span wicket:id="dir">(dir)</span>:</h4>
<table>
<tr wicket:id="fileList">
<td width="200"><span wicket:id="file">(file)</span></td>
<td><img src="delete.gif" border="0" /></td>
</tr>
</table>
</div>
</body>
</html>