I need to execute some tasks in the server and show status with JSF (primefaces).
Below I'm describing my last try:
default.xhtml
<p:commandButton
value="execute"
action="#{controller.init()}" /> <!-- initialize and validate data and call task1() -->
<p:fieldset id="messages" legend="Status:">
<ul>
<li>
<h:panelGrid columns="2" id="msg1" styleClass="#{controller.status1}">
<p:outputLabel value="#{controller.msg1}" />
<span class="#{controller.classToIconClass(controller.status1)}"></span>
</h:panelGrid>
</li>
<li>
<h:panelGrid columns="2" id="msg2" styleClass="#{controller.status2}">
<p:outputLabel value="#{controller.msg2}" />
<span class="#{controller.classToIconClass(controller.status2)}"></span>
</h:panelGrid>
</li>
...
<p:remoteCommand name="task1" action="#{controller.task1()}" update="messages" />
<p:remoteCommand name="task2" action="#{controller.task2()}" update="messages" />
Each step is like this: (Controller.java)
#SessionScoped
...
public void task1() {
if(stopExecution) return;
long returnCode = -1;
String errorMessage = "An error occurred in the task1 execution.";
try {
returnCode = execute(comandString);
} catch (Exception e) {
Logger.getLogger(getClass()).error(errorMessage, e);
returnCode = -1;
stopExecution = true;
}
if(returnCode != 0 && returnCode != 4) {
msg1 = errorMessage;
status1 = "error";
stopExecution = true;
return;
} else {
msg1 = "Task1 is finished.";
status1 = "successful";
}
msg2 = "Running task2...";
status2 = "running";
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("task2();"); // Calls next step
}
// Everything is like task1() and always call next task at the end:
public void task2() {...}
public void task3() {...}
public void task4() {...}
public void finish() {...}
This way everything runs fine, but the users sometimes refresh the page and the execution chain brokes.
Is there a way to do what a I want to do and surviving a page refresh?
PS:
I also tried to execute task by task with RequestContext.getCurrentInstance().update("form:messages"); between them, but the page only updates at the end of the last task.
EDIT:
As Michele and Xtreme Biker said, I do it in a separate thread:
Controller.java
#SessionScoped
...
RequestContext requestContext;
Callable<Long> task1 = new Callable<Long>() {
#Override
public Long call() throws Exception {
long returnCode = -1;
String errorMessage = "An error occurred in the task1 execution.";
returnCode = execute(comandString);
if(returnCode != 0 && returnCode != 4) {
msg1 = errorMessage;
status1 = "error";
return returnCode;
} else {
msg1 = "Task1 is finished.";
status1 = "successful";
msg2 = "Running task2...";
status2 = "running";
}
requestContext.update("form:messages");
return returnCode;
}
};
public void init() {
requestContext = RequestContext.getCurrentInstance();
List<Future<Long>> tasks = new ArrayList<Future<Long>>();
ExecutorService executor = Executors.newSingleThreadExecutor();
tasks.add(executor.submit(this.task1));
tasks.add(executor.submit(this.task2));
tasks.add(executor.submit(this.task3));
tasks.add(executor.submit(this.task4));
tasks.add(executor.submit(this.finish));
executor.shutdown();
}
All tasks run even if I do a page refresh, good.
But the view doesn't update.
I think that requestContext.update("form:messages"); is in the wrong place.
But if a get RequestContext.getCurrentInstance() from inside the Callable.call, I get a NullPointerException, because I'm not in the JSF life cycle.
What's wrong?
Thanks in advice.
Related
i am uploading multiple images through p:fileUpload and showing uploaded images in datagrid but after upload the blank panel is created inside datagrid
<p:panelGrid columns="1" layout="grid" style="width: 1000px">
<p:outputLabel value="Upload Images"></p:outputLabel>
<p:fileUpload mode="advanced" multiple="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" dragDropSupport="true"
update="messages,updimgsfields,carouselcomp" sizeLimit="100000"
fileUploadListener="#{drawingattachmnt.handleFileUpload}"></p:fileUpload>
<!-- <p:graphicImage id="gimPhoto" value="#{fileuploadSection.image}" /> -->
</p:panelGrid>
<p:fieldset id="updimgsfields" legend="Uploaded Images">
<p:dataGrid id="updimgsdatagrid" var="upldimg"
value="#{drawingattachmnt.uploadedimages}" columns="4">
<p:panel id="drawingattachmntpnl" header="#{upldimg.displayId}"
style="text-align:center">
<h:panelGrid columns="1" cellpadding="5"
style="width: 100%; height: 200px;">
<p:graphicImage value="#{upldimg.imgcontent}" cache="false"
stream="true">
<f:param id="imgId" name="photo_id" value="#{upldimg.id}" />
</p:graphicImage>
</h:panelGrid>
</p:panel>
<p:draggable for="drawingattachmntpnl" revert="true"
handle=".ui-panel-titlebar" stack=".ui-panel" />
</p:dataGrid>
</p:fieldset>
// file upload function inside bean
public void handleFileUpload(final FileUploadEvent event) throws IOException {
if (event.getFile().getContents() != null) {
final ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
BufferedImage uploadedImage = null;
byte[] imageBytes = null;
try {
final String imageType = event.getFile().getContentType() != null
|| event.getFile().getContentType().split("/") != null ? event.getFile().getContentType()
.split("/")[1] : "jpeg";
uploadedImage = ImageIO.read(event.getFile().getInputstream());
ImageIO.write(uploadedImage, imageType, byteArrOutputStream);
imageBytes = byteArrOutputStream.toByteArray();
updimg.setImgcontent(new DefaultStreamedContent(new ByteArrayInputStream(imageBytes), imageType));
updimg.setId(UUID.randomUUID().toString().substring(0, 8));
updimg.setDisplayId("FIG: ");
uploadedimages.add(updimg);
} catch (final IOException io) {
} finally {
try {
byteArrOutputStream.close();
// imageInputStream.close();
} catch (final IOException e1) {
e1.printStackTrace();
}
uploadedImage.flush();
}
final FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Successful", "File uploaded Successfully "));
}
// List POJO
import org.primefaces.model.StreamedContent;
public class UploadImage {
public String displayId;
public String id;
public StreamedContent imgcontent;
public UploadImage() {
}
public UploadImage(final String id, final String displayId, final StreamedContent imgcontent) {
this.id = id;
this.displayId = displayId;
this.imgcontent = imgcontent;
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UploadImage other = (UploadImage) obj;
if (this.id == null ? other.id != null : !this.id.equals(other.id)) {
return false;
}
return true;
}
public String getDisplayId() {
return displayId;
}
public String getId() {
return id;
}
public StreamedContent getImgcontent() {
return imgcontent;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public void setDisplayId(final String displayId) {
this.displayId = displayId;
}
public void setId(final String id) {
this.id = id;
}
public void setImgcontent(final StreamedContent imgcontent) {
this.imgcontent = imgcontent;
}
}
I need to show images in datagrid dynamically, but i am getting blank image panel inside datagrid. what should be done ?
I am using primefaces For displaying a datagrid of datatables as follow -
Facelets page:
<h:form name="form">
<p:dataGrid value="#{routeEditingBean.routes}" var="route"
columns="1">
<p:column>
<h:outputText value="#{route.routeId}" />
</p:column>
<p:dataTable value="#{route.routeDetailses}" var="rd"
rowKey="rd.id.employeeId"
selection="#{routeEditingBean.selectedRouteDetails}">
<p:column>
<h:outputText value="#{rd.id.employeeId}" />
</p:column>
<p:column selectionMode="multiple">
</p:column>
</p:dataTable>
<p:commandLink process="#all"
actionListener="#{routeEditingBean.display()}">
<p:graphicImage library="images" name="add-car.jpg"></p:graphicImage>
</p:commandLink>
</p:dataGrid>
</h:form>
Backing-bean:
#ManagedBean
#ViewScoped
public class RouteEditingBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
List<RouteMaster> routes;
List<RouteDetails> selectedRouteDetails;
RouteMaster delrb;
public RouteEditingBean() {
// TODO Auto-generated constructor stub
routes = new ArrayList<RouteMaster>();
Session session = HibernateUtil.getSessionFactory().openSession();
org.hibernate.Transaction transaction = null;
try {
HttpSession httpsession = (HttpSession) FacesContext
.getCurrentInstance().getExternalContext()
.getSession(false);
LoginBean lb = (LoginBean) httpsession.getAttribute("loginBean");
transaction = session.beginTransaction();
Criteria c = session.createCriteria(RouteMaster.class);
List routeMasterList = c.list();
for (Iterator iterator = routeMasterList.iterator(); iterator
.hasNext();) {
RouteMaster routeMaster = (RouteMaster) iterator.next();
System.out.println(routeMaster.getRouteId());
c = session.createCriteria(RouteDetails.class);
c.add(Restrictions.eq("id.routeId", routeMaster.getRouteId()));
Set<RouteDetails> routeDetailses = new HashSet<RouteDetails>();
for (Iterator iterator1 = c.list().iterator(); iterator1
.hasNext();) {
RouteDetails rd = (RouteDetails) iterator1.next();
routeDetailses.add(rd);
}
routeMaster.setRouteDetailses(routeDetailses);
routes.add(routeMaster);
}
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<RouteMaster> getRoutes() {
return routes;
}
public void setRoutes(List<RouteMaster> routes) {
this.routes = routes;
}
public RouteMaster getDelrb() {
return delrb;
}
public void setDelrb(RouteMaster delrb) {
this.delrb = delrb;
}
public List<RouteDetails> getSelectedRouteDetails() {
return selectedRouteDetails;
}
public void setSelectedRouteDetails(List<RouteDetails> selectedRouteDetails) {
this.selectedRouteDetails = selectedRouteDetails;
}
public void deleteEmployee(RouteMaster rm, RouteDetails rd) {
System.out.println(rm.getRouteId());
System.out.println(rd.getId().getEmployeeId());
}
public void display() {
System.out.println("Inside display");
if (selectedRouteDetails == null) {
System.out.println("No selection");
} else {
for (Iterator iterator = selectedRouteDetails.iterator(); iterator
.hasNext();) {
RouteDetails rd1 = (RouteDetails) iterator.next();
System.out.println(rd1.getId().getEmployeeId());
}
}
}
}
When form is Submitted then selected values are returning null. I want to get selected values for all dataTable in dataGrid. Please help.
can you try it this way
List<RouteDetails> selectedRouteDetails = new ArrayList<RouteDetails>();
or
public RouteEditingBean() {
selectedRouteDetails = new ArrayList<RouteDetails>();
.....
}
I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}
I am trying to create a search method using jsf but I am having problem with my code could anyone tell me what I am doing wrong.the method should allow the user to enter and query and pass the results to a table,I have 2 class.
When I test the code to see if it works I get this error
javax.el.MethodNotFoundException: /index.xhtml #19,84 action="#{search.searchresult}": Method not found: Controller.Search#f09285.searchresult()
Java code
#ManagedBean
public class Search {
private String q;
private List <Testpaper>test;
public List<Testpaper> getTest() {
return test;
}
public void setTest(List<Testpaper> test) {
this.test = test;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public void getSearchresult()throws SQLException{
test = new TestDAO().Searches(q);
}
}
public class TestDAO {
#Resource(name="jdbc/GradeSprout2")
DataSource ds;
public List<Testpaper> Searches(String q)throws SQLException {
List<Testpaper> test = new ArrayList<Testpaper>();
if(ds==null)
throw new SQLException("Can't get data source");
//get database connection
Connection con = ds.getConnection();
if(con==null)
throw new SQLException("Can't get database connection");
PreparedStatement ps
= con.prepareStatement(
"select * from test where testname like ?;");
try{
ps.setString(1, "%" + q + "%");
ResultSet result = null;
result = ps.executeQuery();
while (result.next()) {
Testpaper testpaper = new Testpaper();
testpaper.setTestname(result.getString("testname"));
test.add(testpaper);
}}catch(Exception e1){
}
finally{
try{
con.close();
}
catch(Exception e2){
}
}
return test;
}
public TestDAO(){
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/GradeSprout2");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
JSF code
<h:form>
<h:inputText size="95" value="#{search.q}"/>
<br></br>
<br></br>
<h:commandButton value="Find Test" action="#{search.searchresult}">
</h:commandButton>
</h:form>
<h:dataTable value="#{search.test}" var="test" rendered="#{not empty search.test}">
<h:column>#{test.testname}</h:column>
</h:dataTable>
<h:outputText value="No matches found!"
rendered="#{not empty search.q and empty search.test}" />
The error message is very specific: you do not have a searchresult method in your search managed bean. In order to make this work, you should change the method getSearchresult name for searchresult.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSF HTTP Session Login
Avoid back button on JSF+Primefaces application
Primefaces Login Application
I have developed web application by using Prime Faces.Now I want to improve the login system in here up to now I have done followings..
1. index.xhtml
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="Username:" />
<p:inputText value="#{loginBean.username}"
id="username" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<h:inputSecret value="#{loginBean.password}"
id="password" required="true" label="password" />
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" update=":growl" action="#{loginBean.doLogin}" actionListener="#{loginBean.login}" oncomplete="handleLoginRequest(xhr, status, args)" style="height: 30px; font-size: 12px" />
<p:commandButton type="reset" value="Clear" style="height: 30px; font-size: 12px"/>
</f:facet>
</h:panelGrid>
</h:form>
2.LoginBean.java
public class LoginBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<user> getUser() {
List<user> tableList = new ArrayList<user>();
String query = "SELECT * FROM users";
try {
Connection conn = new Connector().getConn();
Statement select = conn.createStatement();
ResultSet result = select.executeQuery(query);
while (result.next()) {
user c = new user();
c.setID(result.getInt("ID"));
c.setName(result.getString("name"));
c.setPassword(result.getString("password"));
tableList.add(c);
}
select.close();
// result.close();
conn.close();
} catch (SQLException e) {
System.err.println("Mysql Statement Error: " + query);
e.printStackTrace();
}
//System.out.println(tableList);
return tableList;
}
public void login(ActionEvent actionEvent) {
List<user> tableList3=getUser();
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg = null;
boolean loggedIn = false;
for(int i=0;i<tableList3.size();i++){
String user_name = tableList3.get(i).getName();
String pass_word = tableList3.get(i).getPassword();
if(username != null && username.equals(user_name) && password != null && password.equals(pass_word)) {
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
//return "table?faces-redirect=true";
} else {
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
//return "new?faces-redirect=true";
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
}
}
public String doLogin(){
List<user> tableList2=getUser();
String msg = null;
for(int i=0;i<tableList2.size();i++){
String user_name = tableList2.get(i).getName();
String pass_word = tableList2.get(i).getPassword();
if(username != null && username.equals("admin") && password != null && password.equals("admin")){
msg = "table?faces-redirect=true";
}
else if(user_name.contains(username)&& pass_word.contains(password)&& !user_name.contains("admin")) {
msg = "table1?faces-redirect=true";
}
}
return msg;
}
public String logout() {
return "index?faces-redirect=true";
}
}
In here the users can load the pages with out logged in to the system.I want to prevent this by using session.But I have not clear idea how to do this.So please help me to do this by step by step.
Thank you.