I need to display the files & folders hierarchically in a Kendo UI treeview which gets loaded from the file system using Java on the back end. I also need to load the contents of the files when they are clicked.
Can anyone suggest how to accomplish this?
I accomplished loading the hierarchy structure by creating two java files.
I got some folders and files inside D:/sampleFileExplorer.Using java file Api we read the file and subdirectories structure and put it inside the ArrayList of Type .In TestJava.java getFileExplorer(folder,finalList) is the method which construct the Arraylist and return it.you need to call this method from Kendo jsp and we get the result as json format.
FileExplorer.java
import java.util.ArrayList;
import java.util.List;
public class FileExplorer {
private String id;
private String text;
private boolean hasFiles;
private List<FileExplorer> items = new ArrayList<FileExplorer>();
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public List<FileExplorer> getItems() {
return this.items;
}
public void setItems(List<FileExplorer> items) {
this.items = items;
}
public boolean isHasFiles() {
return this.hasFiles;
}
public void setHasFiles(boolean hasFiles) {
this.hasFiles = hasFiles;
}
}
TestJava.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class TestJava {
public static void main(String[] args) {
TestJava t=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
t.getFileExplorer(folder,finalList);
t.displayFileExplorer(folder,finalList);
}
public List<FileExplorer> getFileExplorer(File folder,List<FileExplorer> finalList){
finalList = getFileOrDirectoryList(folder,finalList);
return finalList;
}
public void displayFileExplorer(File folder,List<FileExplorer> finalList){
finalList = getFileOrDirectoryList(folder,finalList);
for(FileExplorer file : finalList){
System.out.println(file.getId()+" "+file.getText()+" "+file.getItems().size()+" ");
displaySubLevels(file.getItems());
}
}
public void displaySubLevels(List<FileExplorer> subList){ //display subdirectory's content
if(subList != null){
for(FileExplorer subFile : subList){
System.out.println(subFile.getId()+" "+subFile.getText()+" "+subFile.getItems().size()+" ");
if(subFile.getItems().size()>0){
displaySubLevels(subFile.getItems());
}
}
}
}
public List<FileExplorer> getFileOrDirectoryList(File folder, List<FileExplorer> fileList){
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if(file.isDirectory()){
FileExplorer d1 = new FileExplorer();
d1.setId(file.getPath());
d1.setText(file.getName());
if(file.list().length>0)
{
d1.setHasFiles(true);
}
else
{
d1.setHasFiles(false);
}
File folder1 = new File(d1.getId());
List<FileExplorer> subList = new ArrayList<FileExplorer>();
subList = getFileOrDirectoryList(folder1, subList);
d1.setItems(subList);
fileList.add(d1);
}else{
FileExplorer f1 = new FileExplorer();
f1.setId(file.getPath());
f1.setText(file.getName());
f1.setHasFiles(false);
fileList.add(f1);
}
}
return fileList;
}
}
hello.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5.1">
<html>
<head>
<title></title>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value="/resources/styles/kendo.common.min.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/styles/kendo.default.min.css"/>" rel="stylesheet"/>
<script src="<c:url value="/resources/js/jquery.min.js"/>"></script>
<script src="<c:url value="/resources/js/kendo.all.min.js"/>"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="example" class="k-content">
<div id="treeview" class="demo-section"></div>
<script>
(function($) {
var homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: '<c:url value="/welcome/list/"/>',
dataType: "json"
}
},
schema: {
model: {
hasChildren: "hasFiles",
children: "items"
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous
,
dataTextField: "text"
});
})(jQuery);
</script>
</div>
<div>
</div>
</body>
</html>
My Spring Controller
HelloWorld.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/welcome/")
public class HelloWorld {
#RequestMapping(value = { "fileExplorer/"}, method = RequestMethod.GET )// , produces = "application/json")
public String readScenarioDateSetup(#ModelAttribute("userId")String userId,BindingResult result,Model model)throws Exception{
TestJava remote=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
Iterable<FileExplorer> fileExp= remote.getFileExplorer(folder,finalList);
model.addAttribute("fileExp",fileExp);
return "hello";
}
#RequestMapping(value = {"/list/"}, method = RequestMethod.GET )
public #ResponseBody Iterable<FileExplorer> readScenarioDateSetup()throws Exception{
TestJava remote=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
Iterable<FileExplorer> fileExp= remote.getFileExplorer(folder,finalList);
return fileExp;
}
}
After Deployed into your server ..Type url
http://://welcome/fileExplorer/ you get the result..
There may be better ways to achieve this but this is how I achieved this.
Related
I am working on a Spring project in eclipse. Here I'm taking data from the user and storing it in an array. I want the data stored in an array to display on a JSP page. I have used MVC, but the data is not displaying. When I run the project and call the url for JSP page the array gets displayed in the console but not on the webpage.
console output:
JSP Output:
Controller class
#Controller
public class WebController {
#Autowired
public StoreService service;
List<Store> allStore=new ArrayList<Store>();
#GetMapping( value = "/")
public String home()
{
return "index";
}
#RequestMapping(value="/addstore", method=RequestMethod.GET)
String addStore(#ModelAttribute("store") Store s)
{
System.out.println("Display add store details page");
return "addStore";
}
#RequestMapping(value="/saveStore", method=RequestMethod.POST)
public String addinStore(#ModelAttribute("store") Store s) {
service.saveStore(s);
System.out.println(s);
return "redirect:/";
}
#RequestMapping(value="/viewStore",method=RequestMethod.GET)
public ModelAndView listallStore()
{
allStore=service.showAllStore();
System.out.println(allStore);
return new ModelAndView("listStore","Yves",allStore);
}
JSP page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="dd" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 style="padding-left: 45%; ">Store Details</h1>
<Table class="user-detail">
<thead>
<tr>
<th>Store Name</th>
<th>Store Contact Number</th>
<th>Store Address</th>
</tr>
</thead>
<tbody>
<dd:forEach var="lone" items="${Yves}">
<tr><td>${lone.name}</td><td>${lone.contactNumber}</td><td>${lone.localities}</td></tr>
</dd:forEach>
</tbody>
</Table>
</body>
</html>
Service
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class StoreService {
#Autowired
private StoreDAO sd;
public Store saveStore(Store s) {
return sd.saveStore(s);
}
public List<Store> showAllStore(){
return sd.showAllStore();
}
}
DAO
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class StoreDAO {
List<Store> store = new ArrayList<Store>();
public Store saveStore(Store s) {
store.add(s);
return s;
}
public List<Store> showAllStore(){
return store;
}
}
Bean/Model
import java.util.Arrays;
public class Store {
String name;
String contactNumber;
String[] localities;
public Store() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String[] getLocalities() {
return localities;
}
public void setLocalities(String[] localities) {
this.localities = localities;
}
public Store(String name, String contactNumber, String[] localities) {
super();
this.name = name;
this.contactNumber = contactNumber;
this.localities = localities;
}
#Override
public String toString() {
return "Store [name=" + name + ", contactNumber=" + contactNumber + ", localities="
+ Arrays.toString(localities) + "]";
}
}
Problem; window.external is null for child windows
I have a WinForms application that contains a CEFSharp Chromium browser control on the main form. The complete code is provided here; note this is not my application but a much simpler example that shows the problem.
public partial class Form1 : Form
{
private WebInteropAPI _objForScripting;
public Form1()
{
InitializeComponent();
Load += OnFormLoaded;
_objForScripting = new WebInteropAPI();
}
private void OnFormLoaded(object sender, EventArgs e)
{
SetupBrowser();
_browser.Load("http://localhost:80");
}
private void SetupBrowser()
{
_browser.JavascriptObjectRepository.ResolveObject += ResolveObject;
_browser.FrameLoadStart += FrameLoadStart;
}
private void FrameLoadStart(object sender, FrameLoadStartEventArgs e)
{
_browser.ExecuteScriptAsync("CefSharp.DeleteBoundObject(\"external\"); CefSharp.RemoveObjectFromCache(\"external\"); CefSharp.BindObjectAsync(\"external\");");
}
private void ResolveObject(object sender, JavascriptBindingEventArgs e)
{
var repo = e.ObjectRepository;
if (e.ObjectName == "external" && repo != null && _objForScripting != null)
{
BindingOptions options = BindingOptions.DefaultBinder;
options.CamelCaseJavascriptNames = false;
try
{
repo.Register("external", _objForScripting, true, options);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
}
Here is the WebInteropAPI class for completeness
public class WebInteropAPI
{
public string Push(string name, string payload)
{
Debug.WriteLine("#### Push() name:" + name + " payload:" + payload + " ####");
return payload;
}
public void PushData(string payload)
{
Debug.WriteLine("#### PushData() payload:" + payload + " ####");
}
}
On form load I register my interop and navigate the browser to a local HTML page on my machine; it looks as follows
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
</head>
<body>
<p>
<button onclick="myFunction()">Invoke Push Data on Host</button>
Launch child iFrame
</p>
<script type="text/javascript">
$('.open-popup').click(function(e) {
e.preventDefault();
window.open(this.href, '_blank', 'width=1000,height=750');
});
</script>
<script>
function myFunction() {
window.external.Push("This is the name property","This is the payload data property");
}
</script>
</body>
</html>
Running the application results in the rather fetching UI
Clicking the button does indeed invoke the method on my WebInteropAPI
However; clicking the link to open a new child window and then clicking the button results in an error
Any help is greatly appreciated.
UPDATE; I've found something that works but I'm unsure if it's good or bad from a standards point of view.
My updated Forms view now looks like;
public partial class Form1 : Form
{
private FrameHelper _frameHelper;
private JSObjectHelper _jsObjectHelper;
public Form1()
{
InitializeComponent();
Load += OnFormLoaded;
}
private void OnFormLoaded(object sender, EventArgs e)
{
SetupBrowser();
_browser.Load("http://localhost:80");
}
private void SetupBrowser()
{
_jsObjectHelper = new JSObjectHelper(new WebInteropAPI());
_frameHelper = new FrameHelper();
_browser.JavascriptObjectRepository.ResolveObject += (s, a) =>
{
_jsObjectHelper.ResolveObject(a);
};
_browser.FrameLoadStart += (s, a) =>
{
_frameHelper.FrameLoadStart(_browser);
};
_browser.LifeSpanHandler = new LifeSpanHandler(_frameHelper, _jsObjectHelper);
}
}
The magic now happens in the LifeSpanHandler
public class LifeSpanHandler : ILifeSpanHandler
{
private readonly FrameHelper _frameHelper;
private readonly JSObjectHelper _jsObjectHelper;
private ChromiumWebBrowser _browser;
public LifeSpanHandler(FrameHelper frameHelper, JSObjectHelper jsObjectHelper)
{
_frameHelper = frameHelper;
_jsObjectHelper = jsObjectHelper;
}
public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser){}
public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser){}
public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
_browser = new ChromiumWebBrowser(string.Empty);
_browser.Bounds = ((ChromiumWebBrowser)chromiumWebBrowser).Bounds;
_browser.BrowserSettings = ((ChromiumWebBrowser)chromiumWebBrowser).BrowserSettings;
_browser.FrameLoadStart += (s, a) => { _frameHelper.FrameLoadStart(_browser); };
_browser.JavascriptObjectRepository.ResolveObject += (s, a) => { _jsObjectHelper.ResolveObject(a); };
newBrowser = _browser;
return false;
}
}
And for completeness; here's the frame helper and the JsObjectHelper
public class FrameHelper
{
public void FrameLoadStart(IWebBrowser browser)
{
browser.ExecuteScriptAsync("CefSharp.DeleteBoundObject(\"external\"); CefSharp.RemoveObjectFromCache(\"external\"); CefSharp.BindObjectAsync(\"external\");");
}
}
public class JSObjectHelper
{
private readonly WebInteropAPI _objForScripting;
public JSObjectHelper(WebInteropAPI objForScripting)
{
_objForScripting = objForScripting;
}
public WebInteropAPI ObjForScripting { get; }
public void ResolveObject(JavascriptBindingEventArgs e)
{
var repo = e.ObjectRepository;
if (e.ObjectName == "external" && repo != null && _objForScripting != null)
{
BindingOptions options = BindingOptions.DefaultBinder;
options.CamelCaseJavascriptNames = false;
try
{
repo.Register("external", _objForScripting, true, options);
}
catch
{
}
}
}
}
I want to implement server side paging,sorting and filtering in kendo grid ui with script in angular js but problem is paging is not working.
First 10 records are displaying but when i click on page no 2 then server side call is not going and no records are displayed.
Source:http://demos.telerik.com/kendo-ui/grid/angular
This is my View:
<link href="~/css/kendo.common-material.min.css" rel="stylesheet" />
<link href="~/css/kendo.rtl.min.css" rel="stylesheet" />
<link href="~/css/kendo.material.min.css" rel="stylesheet" />
<div class="table-responsive" ng-controller="GridDemoCtrl">
<kendo-grid options="mainGridOptions">
</kendo-grid>
</div>
<!-- jQuery -->
<script src="~/vendor/jquery/jquery.min.js"></script>
<!-- Angular -->
<script src="~/vendor/angular/angular.js"></script>
<script src="~/js/kendo.all.min.js.js"></script>
My Script:
app.controller('GridDemoCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.mainGridOptions = {
dataSource: {
transport: {
read: {
url: "../Holiday/GetListofHolidays",
contentType: "application/json",
type: "POST"
}
},
schema: {
data: "Data",
total: "Total",
},
pageSize: 10,
serverPaging: true
},
pageable: true,
columns: [
{
field: "HolidayName",
title: "Holiday Name"
},
{
field: "HolidayDiscription",
title: "Holiday Description"
}
]
};
}]);
My Controller:
[HttpPost]
public ActionResult GetListofHolidays(DataSourceRequest command)
{
var holidayList = _holidayService.GetAllHolidays(command.Page - 1, command.PageSize,null);
var gridModel = new DataSourceResult
{
Data = holidayList.Select(x =>
{
var holidayModel = new HolidayModel();
holidayModel.HolidayName = x.HolidayDiscription;
holidayModel.HolidayDate = x.HolidayDate;
holidayModel.HolidayDiscription = x.HolidayDiscription;
return holidayModel;
}),
Total = holidayList.TotalCount,
};
return Json(gridModel);
}
public class DataSourceRequest
{
public int Page { get; set; }
public int PageSize { get; set; }
public DataSourceRequest()
{
this.Page = 1;
this.PageSize = 10;
}
}
public class DataSourceResult
{
public object ExtraData { get; set; }
public IEnumerable Data { get; set; }
public object Errors { get; set; }
public int Total { get; set; }
}
So please anybody can guide me whats the problem with my code and why paging is not working???
You need to let Kendo handle the paging, etc. Ensure the LINQ (are you using an ORM like Entity Framework?) in your query does not execute the query yet and have GetAllHolidays() return an IQueryable. holidayList.ToDataSourceResult() will add the paging, sorting and filtering and execute the query.
Try this:
[HttpPost]
public ActionResult GetListofHolidays([DataSourceRequest]DataSourceRequest request)
{
IQueryable<HolidayModel> holidayList = _holidayService.GetAllHolidays();
return Json(holidayList.ToDataSourceResult(request));
}
I have just recently started learning Tapestry, trying to make my own Celebrity Collector application.
Everything worked fine, until I wanted to provide a database support instead of mocked database.
I'm using Hibernate 3.6 with Tapestry 5.3.7.
I have configured my database like this:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:target\database</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hbm2ddl.auto">create-drop</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
</session-factory>
</hibernate-configuration>
My DAO interface and implementation looks like this:
package com.example.addressbook.data;
import java.util.List;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import com.example.addressbook.entities.Celebrity;
public interface CelebrityDao {
#CommitAfter
int count();
#CommitAfter
void add(Celebrity celebrity);
#CommitAfter
Celebrity get(long id);
#CommitAfter
List<Celebrity> getAll();
#CommitAfter
List<Celebrity> getRange(long startIndex, long endIndex);
#PostInjection
void prepare();
}
package com.example.addressbook.data.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
public class CelebrityDaoImpl implements CelebrityDao {
#Inject
protected Session session;
public void add(Celebrity celebrity) {
session.persist(celebrity);
}
public Celebrity get(long id) {
Criteria criteria = session.createCriteria(Celebrity.class);
criteria.add(Restrictions.eq("id", id));
Celebrity celebrity = (Celebrity) criteria.uniqueResult();
return celebrity;
}
public List<Celebrity> getAll() {
Criteria criteria = session.createCriteria(Celebrity.class);
List rawResults = criteria.list();
List<Celebrity> results = new ArrayList<Celebrity>();
for (Object object : rawResults) {
results.add((Celebrity) object);
}
return results;
}
public List<Celebrity> getRange(long startIndex, long endIndex) {
Criteria criteria = session.createCriteria(Celebrity.class);
criteria.add(Restrictions.between("id", startIndex, endIndex));
List rawResults = criteria.list();
List<Celebrity> results = new ArrayList<Celebrity>();
for (Object object : rawResults) {
results.add((Celebrity) object);
}
return results;
}
public void prepare() {
// adding some initial records in the database
}
public int count() {
return getAll().size();
}
}
My ShowAll class is here:
package com.example.addressbook.pages;
import java.text.Format;
import java.util.List;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.grid.GridDataSource;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
import com.example.addressbook.model.User;
import com.example.addressbook.util.CelebrityEncoder;
import com.example.addressbook.util.CelebritySelectModel;
import com.example.addressbook.util.Formats;
import com.example.addressbook.util.HibernateEntityDataSource;
public class ShowAll {
#SessionState
private User user;
private boolean userExists;
#Inject
private CelebrityDao dao;
#InjectPage
private Details detailsPage;
#Property
private Celebrity celebrity;
#Inject
private BeanModelSource beanModelSource;
#Inject
private Messages messages;
String onActivate() {
if (!userExists)
return "Index";
return null;
}
#OnEvent(component = "detailsLink")
Object onShowDetails(long id) {
Celebrity celebrity = dao.get(id);
detailsPage.setCelebrity(celebrity);
System.err.println("Requested ID: " + id);
System.err.println("Result: " + celebrity.getLastName());
return detailsPage;
}
public BeanModel<Celebrity> getModel() {
return beanModelSource.createDisplayModel(Celebrity.class, messages);
}
public List<Celebrity> getAllCelebrities() {
return this.dao.getAll();
}
public Format getDateFormat() {
return Formats.getDateFormat();
}
public User getUser() {
return user;
}
public GridDataSource getCelebritySource() {
return new HibernateEntityDataSource<Celebrity>(Celebrity.class, dao);
}
public SelectModel getCelebrityModel() {
return new CelebritySelectModel(getAllCelebrities());
}
public ValueEncoder<Celebrity> getCelebrityEncoder() {
return new CelebrityEncoder(dao);
}
#Persist
private Celebrity selectedCelebrity;
public Celebrity getSelectedCelebrity() {
return selectedCelebrity;
}
public void setSelectedCelebrity(Celebrity selectedCelebrity) {
this.selectedCelebrity = selectedCelebrity;
}
public String getSelectedCelebrityName() {
if (selectedCelebrity == null) {
return "";
}
return selectedCelebrity.getFirstName() + " " + selectedCelebrity.getLastName();
}
}
And here is how I add new ones:
package com.example.addressbook.pages;
import org.apache.tapestry5.ioc.annotations.Inject;
import com.example.addressbook.data.CelebrityDao;
import com.example.addressbook.entities.Celebrity;
public class AddCelebrity {
private Celebrity celebrity;
#Inject
private CelebrityDao dao;
public void onActivate() {
System.out.println("OnActivate: " + dao.getAll().toString());
if (celebrity == null) {
celebrity = new Celebrity();
}
}
public Celebrity getCelebrity() {
return celebrity;
}
public void setCelebrity(Celebrity celebrity) {
this.celebrity = celebrity;
}
Object onSuccess() {
dao.add(celebrity);
System.out.println("All celebrities: " + dao.getAll().toString());
return ShowAll.class;
}
}
The problem is the following:
When I first come to ShowAll page, my records are pulled from the database and rendered.
When I refresh the page, the records are removed magically and nothing is displayed. The database is empty (dao.getAll() returns and empty list)
When I add a new Celebrity via AddCelebrity page, it is inserted into the database, but as the page is refreshed, the magic happens again and the database is empty again.
I have binded my DAO interface and implementation in AppModule class:
public static void bind(ServiceBinder binder) {
binder.bind(SupportedLocales.class, SupportedLocalesImpl.class);
binder.bind(CelebrityDao.class, CelebrityDaoImpl.class);
}
HELP!! :)
The answer was to add another method to AppModule class
#Match("*Dao")
public static void adviseTransactions(HibernateTransactionAdvisor advisor,
MethodAdviceReceiver receiver) {
advisor.addTransactionCommitAdvice(receiver);
}
So that Tapestry could actually do something with #CommitAfter annotation on my DAO methods.
i have a program that generates a 2 question test from an SQL DB by question and by answers, the questions are selected randomly by a question id. the problem I'm having is when run normally from net beans the the questions don't randomize in fact on a new system that hasn't run before it doesn't show any questions. but when it is debugged with break points it works perfectly fine. i had something like this happen to another program a while ago and not sure how i fixed it, i believe it was an issue between caching and the math Random.
welcome page load to the quizzical controller which on init generates a test in TestDA servlet
package org.citatscc.quiz.controller;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.citatscc.quiz.business.*;
import org.citatscc.quiz.business.TestTaker;
import org.citatscc.quiz.data.TestDA;
public class Quizzical extends HttpServlet {
//the test will be available to all threads
//eventually each TestTaker will store their Test in a Session
private Test myQuiz=null;
#Override
public void init(){
String testName = getServletConfig().getInitParameter("QuizName");
//generate the basic Test which will be used to create each TestTaker's myQuiz
myQuiz = TestDA.generateTest(testName);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("myQuiz", myQuiz);
//here we are simply showing the test generated from the database
String action = request.getParameter("action");
String url = "/QuizView.jsp";
if(action == null)
{
url = "/QuizMain.jsp";
}
else if(action.equals("AddTest"))
{
url = "/QuizAdd.jsp";
}
else if(action.equals("addNewTest"))
{
addNewTest(request);
}
RequestDispatcher dispatch = getServletContext().getRequestDispatcher(url);
dispatch.forward(request, response);
}
public boolean addNewTest(HttpServletRequest request)
{
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
TestDA
package org.citatscc.quiz.data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.citatscc.quiz.business.Question;
import org.citatscc.quiz.business.Test;
public class TestDA{
public static Test generateTest(String testName) {
List<Question> questions = new ArrayList<Question>();
Test test = null;
boolean sameNum = true;
int randNum1 = 0;
int randNum2 = 0;
while(sameNum == true)
{
randNum1 = getRandomNumber();
randNum2 = getRandomNumber();
if(randNum1 == 0 || randNum2 == 0 || randNum1 > 7 || randNum2 > 7 ||
randNum1 == 6 || randNum2 == 6)
{
sameNum = true;
}
else
{
if(randNum1 != randNum2)
{
sameNum = false;
}
}
}
String questionID1 = getQuestionID(randNum1);
String questionID2 = getQuestionID(randNum2);
try {
String questionTxt1 = getQuestionStringByQID(questionID1);
String questionTxt2 = getQuestionStringByQID(questionID2);
questions.add(getAnswers(questionTxt1, questionID1));
questions.add(getAnswers(questionTxt2, questionID2));
test = new Test(testName,questions);
} catch (Exception ex) {
String message = ex.getMessage();
}
return test;
}
public static Question getAnswers(String questionTxt, String questionID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
int counter = 0;
int correctAnswer = 0;
ArrayList<String> answers = new ArrayList<String>();
String preparedQuery = "SELECT * FROM `answers` WHERE `qID` = " + questionID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
while (resultSet.next())
{
answers.add(resultSet.getString(2));
if(resultSet.getInt(3) == 1)
{
correctAnswer = counter;
}
else
{
counter++;
}
}
Question question = new Question(questionTxt, answers, correctAnswer);
return question;
}
public static String getQuestionStringByQID(String qID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
String preparedQuery = "SELECT `question` FROM `questions` WHERE `qID` = " + qID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
String questionText = "";
while (resultSet.next())
{
questionText = resultSet.getString(1);
}
connection.close();
return questionText;
}
public static int getRandomNumber()
{
Random rnd = new Random();
int randomNum = rnd.nextInt(8);
return randomNum;
}
public static String getQuestionID(int randNum)
{
int intqID = randNum * 111;
String qID = "" + intqID;
return qID;
}
public static void insertQuestion(String qID, String qText, List<String>qChoices, int correct)throws SQLException{
String preparedQuestion = "INSERT INTO questions VALUES(?,?)";
}
public static void upDateQuestion(String qID, String qText, List<String>qChoices, int correct) throws SQLException{
}
}
after init is finished it redirects to a menu jsp, after a link to take a test is clicked it hits the quizzical controller before being redirected to QuizView.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Quiz View</title>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="cit" uri="/WEB-INF/tld/test.tld" %>
<%#taglib prefix="includes" tagdir="/WEB-INF/tags/" %>
<%# page import="org.citatscc.quiz.business.Test, org.citatscc.quiz.business.Question" %>
<%# page import="java.util.*" %>
<link href="quiz.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="top"><includes:Header image="cit_logo.jpg" alt="cit logo image" tagline="${myQuiz.testName}"/></div>
<div id="leftnav">
</div>
<div id="content">
<form action="Quiz" method="post">
<c:forEach var="question" items="${myQuiz.questionList}" varStatus="qCount">
<h2>${qCount.count}. ${question.questionText} </h2>
<c:forEach var="choice" items="${question.choices}" varStatus="choiceCount" >
<!-- custom tag here -->
<cit:quiz_choiceButton groupName="choice${qCount.count}" text="${choice}" value="${choiceCount.index}" />
</c:forEach>
<br />
</c:forEach>
<input type="submit" name="done" value="Submit" />
</form>
</div>
<div id="footer"><includes:Footer /></div>
</div>
</body>
</html>
any help is appreciated.
The servlet method init() is called once during servlet initialisation. So, you have the same Test for all your following requests.
private Test myQuiz=null;
has the same value for all requests.
More in docs: http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)