Can't access the get method from expression language in jsf - spring-boot

I can't access getCpuUsage() method from my xhtml code via
<h:outputText id="cpu_usage"
value="#{cpuUsageBean.cpuUsage} %" />
When i add #bean annotation to my getCpuUsage() method this method works when component initialized.But after that when i try to access via xhtml file seen on the page nothing happened at all. I hope you understand me well . Thanks in advance
my xhtml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body style="margin-left:50px">
<h2>PrimeFaces Polling Example</h2>
<h:form>
CPU usage:
<b> <h:outputText id="cpu_usage"
value="#{cpuUsageBean.cpuUsage} %" />
</b>
<p:poll interval="1" update="cpu_usage" />
</h:form>
</h:body>
</html>
MY MANAGED BEAN SO COMPONENT:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.InitBinder;
import lombok.extern.slf4j.Slf4j;
#Component
#Scope("VIEW")
//#ViewScoped
//#Named
#Slf4j
public class CpuUsageBean {
private AtomicInteger cpuUsage;
#PostConstruct
public void init() {
cpuUsage = new AtomicInteger(50);
ExecutorService es = Executors.newFixedThreadPool(1);
es.execute(() -> {
while (true) {
// simulating cpu usage
int i = ThreadLocalRandom.current().nextInt(-10, 11);
int usage = cpuUsage.get();
usage += i;
if (usage < 0) {
usage = 0;
} else if (usage > 100) {
usage = 100;
}
cpuUsage.set(usage);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
}
}
});
}
public int getCpuUsage() {
System.out.println("-----getCpuUsage : " + cpuUsage);
log.error("---------- getCpuUsage calisti");
return cpuUsage.get();
}
}
MY SPRİNGBOOT APP CLASS :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = "com.tutorial.PrimeFacesTutorial.controller,com.tutorial.PrimeFacesTutorial")
public class PrimeFacesTutorialApplication {
public static void main(String[] args) {
SpringApplication.run(PrimeFacesTutorialApplication.class, args);
}
}

Related

How to solve the error message: "Whitelabel Error Page" for Spring Boot

I'm new with spring boot and I'm trying to make a project with Spring MVC + Spring Boot2 + JSP + Spring Data + DB Oracle.
When I run the simple application, The first message error I was been:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Apr 17 10:20:05 CEST 2020
There was an unexpected error (type=Not Found, status=404).
No message available
I found a lot of documention about this error and I tested different solutions but nothing was fine for my problem. Below the tests I did:
1) I make sure that my main class was in the root package and I put the other packages int the sub level;
2) I used de #ComponentScan in the main class in this way #ComponentScan({"com.dashboard.demo.controller"});
3) in the application.properties I used this command server.servlet.context-path=/oee
This is my code:
Application.properties
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
server.servlet.context-path=/oee
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= jdbc:oracle:thin:#serverIP:Port:DB11G
spring.datasource.username= Server name
spring.datasource.password= password
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql= true
server.port = 8091
Main
package com.dashboard.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class OeeApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(OeeApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(OeeApplication.class, args);
}
}
OEEController
package com.dashboard.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.service.OEEService;
#Controller
public class OEEController {
#Autowired
private OEEService oeeService;
#RequestMapping(value = "/oee}", method = RequestMethod.GET)
public String listAll(Model model)
{
List<OEE> oee = oeeService.SelDevice();
model.addAttribute("OEE",oee);
return "oee";
}
}
OEEServiceImpl
package com.dashboard.demo.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.repository.OEERepository;
#Service
#Transactional
public class OEEServiceImpl implements OEEService{
#Autowired
private OEERepository oeeRepository;
#Override
public List<OEE> SelDevice()
{
return oeeRepository.findAll();
}
}
OEERepository
package com.dashboard.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.entities.OEEid;
#Repository
public interface OEERepository extends JpaRepository<OEE, OEEid>
{
}
I'm managing a composite key and I've create a class for the composite key and another to manage the entity. I'm catching the error int this package.
package com.dashboard.demo.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
#Data
#Embeddable
public class OEEid implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4512114330774744082L;
#DateTimeFormat(pattern = "dd-MM-yy HH:mm:ss")
#Column(name = "MSO_GIORNO_LAV")
private Date date;
#Column(name = "MSO_MACCHINA")
private String device;
public OEEid(Date date, String device) {
super();
this.date = date;
this.device = device;
}
}
package com.dashboard.demo.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.IdClass;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name = "MES_OEE")
#Data
public class OEE implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -7738922358421962399L;
#EmbeddedId
private OEEid oeeID;
#Basic(optional = false)
#Column(name = "MSO_QUANTITA")
private int amount;
#Basic(optional = false)
#Column(name = "MSO_OEE")
private float oee;
}
oee.jsp
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<header>
<h1>Spring MVC + JSP + JPA + Spring Boot 2</h1>
</header>
<div class="starter-template">
<h1>Users List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Date</th>
<th>Device</th>
<th>Amount</th>
<th>OEE</th>
</tr>
<c:forEach items="${OEE}" var="oee">
<tr>
<td>${oee.oeeID.date}</td>
<td>${oee.oeeID.device}</td>
<td>${oee.amount}</td>
<td>${oee.oee}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Can anyone give me any suggestions to solve this error message?
Thanks
This is my project directory
Can you please try by removing this server.servlet.context-path=/oee from properties file and try with localhost:8080/oeee

Spring Boot - Error during WebSocket handshake

When I tried using WebSocket in my spring boot application I got this error : "WebSocket connection to 'ws://localhost:8080/Moda/chatroomServerEndpoint' failed: Error during WebSocket handshake: Unexpected response code: 400" (Default.html-Line 11).. My aim : Send message by two different tabs (ex: in Google Chrome) Please help me! Thank you...
Default.html
<!<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Deneme</title>
<script type = "text/javascript">
var websocket = new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint");
websocket.onmessage = function processMessage(message) {
var jsonData = JSON.parse(message.data);
if(jsonData.message != null) messagesTextArea.value += jsonData.message + "\n";
}
function sendMessage(){
websocket.send(messageText.value);
messageText.value = "";
}
</script>
</head>
<body>
<textarea id="messagesTextArea" readonly = "readonly" rows="10" cols="45"></textarea><br/>
<input type = "text" id="messageText" size="50" /><input type="button" value="Send" onclick="sendMessage();" />
</body>
</html>
ModaApplication.java
package com.moda;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import com.moda.videochat.MyWebSocketConfigurator;
#Configuration
#EnableAutoConfiguration
#ServerEndpoint("/chatroomServerEndpoint")
public class ModaApplication {
public static void main(String[] args) {
SpringApplication.run(ModaApplication.class, args);
}
static Set<Session> chatroomUsers = Collections.synchronizedSet(new HashSet<Session>());
#OnOpen
public void handleOpen(Session userSession)
{
chatroomUsers.add(userSession);
}
#OnMessage
public void handleMessage(String message, Session userSession) throws IOException {
String username = (String) userSession.getUserProperties().get("username");
if(username == null)
{
userSession.getUserProperties().get("username");
userSession.getBasicRemote().sendText(buildJsonData("System","you are now connected as " + message));
}
else
{
Iterator<Session> iterator = chatroomUsers.iterator();
while(iterator.hasNext()) iterator.next().getBasicRemote().sendText(buildJsonData(username,message));
}
}
#OnClose
public void handleClose(Session userSession)
{
chatroomUsers.remove(userSession);
}
private String buildJsonData(String username, String message)
{
JsonObject jsonObject = Json.createObjectBuilder().add("message",username+": "+message).build();
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) {jsonWriter.write(jsonObject);}
return null;
}
}
Try
new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint/websocket");
instead of
`new WebSocket("ws://localhost:8080/Moda/chatroomServerEndpoint");`
Also make sure to set .setAllowedOrigins("*")

Spring Boot - unable to resolve JSP page

application.yml
spring:
mvc.view:
prefix: /
suffix: .jsp
SampleController.java
package springboot_demo;
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springboot_demo.service.StudentService;
#Controller
#SpringBootApplication
public class SampleController extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleController.class);
}
#Resource
private StudentService studentService;
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("data", studentService.list());
return "index";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
The 'data' is correctly fetched from database, but the JSP page seems not compiled. I visit http://localhost:8080 and the browser shows me like this:
<%#page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>Hello World!</h2>
<c:forEach items="${data }" var="i">
<h2>${i.id }${i.name }</h2>
</c:forEach>
</body>
</html>

Passing String from jsp to Controller in Spring

I created a project with Spring + JPA + Hibernate. I want to pass a string from jsp to controller(removeUtente method). If I click on the link I delete the row from the database .. Where am I doing wrong? Excuse me for my english..The controller receives the string from jsp and calls the method to remove it.
Thanks
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Lista utenti</h2>
<table border="1">
<c:forEach var="utente" items="${lista }">
<tr>
<td>
<c:out value="${utente.id}"/>
</td>
<td>
<c:out value="${utente.cognome}"/>
</td>
<td>
<c:out value="${utente.nome}"/>
</td>
<td>
<c:out value="${utente.eta}"/>
</td>
<td>
<c:url var="url" value="/remove">
<c:param name="id" value="${utente.id }"/>
</c:url>
click to delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
UtenteController.java
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestParam;
import persistence.UtenteDAO;
import bean.Utente;
#Controller
public class UtenteController {
#Autowired
UtenteDAO utenteDAO;
#RequestMapping(value="/add",method=RequestMethod.POST)
public String addUtente(#ModelAttribute Utente u){
utenteDAO.inserisciUtente(u);
return "index";
}//addUtente
#RequestMapping(value="/show",method=RequestMethod.GET)
public String getUtenti(ModelMap model){
List<Utente> lista=utenteDAO.listaUtenti();
model.addAttribute("lista", lista);
return "showlista";
}//getUtenti
#RequestMapping(value="/remove",method=RequestMethod.GET)
public String removeUtente(#RequestParam String id){
utenteDAO.rimuovi(id);
return "showlista";
}//removeUtente
}//UtenteController
Utente.java
package bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utente")
public class Utente {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#Column(name="cognome")
private String cognome;
#Column(name="nome")
private String nome;
#Column(name="eta")
private Integer eta;
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
public String getCognome(){return cognome;}//getCognome
public void setCognome(String cognome){this.cognome=cognome;}//setCognome
public String getNome(){return nome;}//getNome
public void setNome(String nome){this.nome=nome;}//setNome
public Integer getEta(){return eta;}//getEta
public void setEta(Integer eta){this.eta=eta;}//setEta
#Override
public String toString(){
return "id:"+id+" cogn:"+cognome+" nome:"+nome+" eta:"+eta;
}//toString
}//Utente
UtenteDAOImpl.java
package persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import bean.Utente;
#Transactional
public class UtenteDAOImpl implements UtenteDAO {
#PersistenceContext
EntityManager em;
public void inserisciUtente(Utente u){
em.persist(u);
}//inserisciUtente
#SuppressWarnings("unchecked")
public List<Utente> listaUtenti(){
Query q=em.createQuery("SELECT u FROM Utente u");
List<Utente> ris=q.getResultList();
return ris;
}//listaUtenti
public void rimuovi(String idUtente){
Query q=em.createQuery("DELETE FROM Utente AS u WHERE u.id =:id");
q.setParameter("id", idUtente);
q.executeUpdate();
}//rimuovi
}//inserisciUtente

Ajax loader is not getting called in a file upload custom component in JSF 2.0

In my current project I am trying to create a file upload custom component because we have a constraint that we can’t use any component library. Our requirement is to create single file upload, upon selecting and uploading a file it will get displayed in a data table below that component. User will be able to download the uploaded file and if required can delete the uploaded file also. There will be a ajax loader which needs to be fired upon uploading a file. Pictorially the UI looks like this.
________________________ __________ ____________
| | | Browse | | Upload |
|_______________________| |_________| |___________|
______________________________________________
| | |
| File1.pdf | * |
|_______________________________________|_____|
| | |
| File2.pdf | * |
|_______________________________________|_____|
To create this component I have taken help from Core JavaServer Pages(3e) to create custom component & BalusC’s blogs to trigger ajax call from a jsf page(jsf.ajax.addOnEvent). Here is the entire code of Renderer, xhtml, and managedbean. For the time being I have used a h:outputtext instead of h:datatable to update the page.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:corejsf="http://corejsf.com">
<h:head>
<title>A file upload test</title>
<h:outputScript name="jsf.js" library="javax.faces" target="head"/>
<script>
jsf.ajax.addOnEvent(function(data) {
var ajaxstatus = data.status;
var ajaxloader = document.getElementById("ajaxloader");
switch (ajaxstatus) {
case "begin": // This is called right before ajax request is been sent.
ajaxloader.style.display = 'block';
break;
case "complete":
ajaxloader.style.display = 'none';
break;
case "success": // NOOP.
break;
} });
</script>
</h:head>
<h:body>
<h:form>
<h:commandButton value="hello"></h:commandButton>
</h:form>
<h:form enctype="multipart/form-data">
Upload a photo of yourself:
<corejsf:upload uploadButton="upload"/>
<h:outputText id="updateText" value="#{user.value}"></h:outputText>
<h:commandButton action="#{user.submit}" value="Initiate"></h:commandButton>
</h:form>
<img id="ajaxloader" src="ajax-loader.gif" style="display: none;" />
</h:body>
</html>
The Renderer:
package com.corejsf;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
#FacesRenderer(componentFamily="javax.faces.Input",
rendererType="com.corejsf.Upload")
public class UploadRenderer extends Renderer {
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) return;
ResponseWriter writer = context.getResponseWriter();
String ajax = "jsf.ajax.request(this, event,{render:'j_idt11:updateText'}); return false";
String clientId = component.getClientId(context);
System.out.println("parentid>>>>>>"+component.getParent().getClientId(context));
System.out.println(clientId);
System.out.println("upload button >>>>>>"+(String)component.getAttributes().get("uploadButton"));
writer.startElement("input", component);
writer.writeAttribute("type", "file", "type");
writer.writeAttribute("name", clientId+":INPUT_FILE", "clientId");
writer.endElement("input");
writer.startElement("input", component);
writer.writeAttribute("type", "submit", null);
writer.writeAttribute("name", clientId + ":FILE_UPLOAD", null);
writer.writeAttribute("value", "Upload", "value");
writer.writeAttribute("onclick", ajax, null);
writer.endElement("input");
writer.flush();
}
public void decode(FacesContext context, UIComponent component) {
Map<String,String> requestMap = context.getExternalContext ().getRequestParameterMap();
String clientId = component.getClientId(context);
System.out.println("getId>>>>>>>"+component.getId());
if(requestMap.containsKey(clientId+":FILE_UPLOAD")){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("true");
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
//String clientIdFile = component.getClientId(context);
FileItem item = (FileItem) request.getAttribute(clientId+":INPUT_FILE");
System.out.println("filename>>>>"+item.getName()+">>>");
System.out.println("file blank>>>>"+item.getName().equals(""));
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
UserBean userBean = (UserBean) FacesContext.getCurrentInstance().getApplication()
.getELResolver().getValue(elContext, null, "user");
try {
userBean.setUploadedFile(item.getInputStream());
userBean.setValue(userBean.getUploadedFileList().size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
System.out.println("false");
}
}
Managed bean:
package com.corejsf;
import java.io.Serializable;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
//import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import java.io.InputStream;
import java.util.ArrayList;
#ManagedBean(name="user")
#ViewScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private ArrayList<InputStream> uploadedFileList = new ArrayList<InputStream>();
public ArrayList<InputStream> getUploadedFileList() {
return uploadedFileList;
}
public void setUploadedFileList(ArrayList<InputStream> uploadedFileList) {
this.uploadedFileList = uploadedFileList;
}
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getId() { return id; }
public void setId(String newValue) { id = newValue; }
public void setUploadedFile(InputStream inputStream){
uploadedFileList.add(inputStream);
}
}
UploadFilter:
package com.corejsf;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFilter implements Filter {
private int sizeThreshold = -1;
private String repositoryPath;
public void init(FilterConfig config) throws ServletException {
repositoryPath = config.getInitParameter(
"com.corejsf.UploadFilter.repositoryPath");
try {
String paramValue = config.getInitParameter(
"com.corejsf.UploadFilter.sizeThreshold");
if (paramValue != null)
sizeThreshold = Integer.parseInt(paramValue);
}
catch (NumberFormatException ex) {
ServletException servletEx = new ServletException();
servletEx.initCause(ex);
throw servletEx;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
boolean isMultipartContent
= ServletFileUpload.isMultipartContent(httpRequest);
if (!isMultipartContent) {
chain.doFilter(request, response);
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
if (sizeThreshold >= 0)
factory.setSizeThreshold(sizeThreshold);
if (repositoryPath != null)
factory.setRepository(new File(repositoryPath));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
#SuppressWarnings("unchecked") List<FileItem> items
= (List<FileItem>) upload.parseRequest(httpRequest);
final Map<String, String[]> map = new HashMap<String, String[]>();
for (FileItem item : items) {
String str = item.getString();
if (item.isFormField())
map.put(item.getFieldName(), new String[] { str });
else
httpRequest.setAttribute(item.getFieldName(), item);
}
chain.doFilter(new
HttpServletRequestWrapper(httpRequest) {
public Map<String, String[]> getParameterMap() {
return map;
}
// busywork follows ... should have been part of the wrapper
public String[] getParameterValues(String name) {
Map<String, String[]> map = getParameterMap();
return (String[]) map.get(name);
}
public String getParameter(String name) {
String[] params = getParameterValues(name);
if (params == null) return null;
return params[0];
}
public Enumeration<String> getParameterNames() {
Map<String, String[]> map = getParameterMap();
return Collections.enumeration(map.keySet());
}
}, response);
} catch (FileUploadException ex) {
ServletException servletEx = new ServletException();
servletEx.initCause(ex);
throw servletEx;
}
}
}
taglib.xml:
<facelet-taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
<namespace>http://corejsf.com</namespace>
<tag>
<tag-name>upload</tag-name>
<component>
<component-type>javax.faces.Input</component-type>
<renderer-type>com.corejsf.Upload</renderer-type>
</component>
</tag>
</facelet-taglib>
The issue that I am facing with this code is that the ajax is updating the h:outputtext but the ajax loader is not working. It is not getting displayed upon uploading a file. It should get displayed on begin status and disappear on complete status. Besides, firefox error console shows a “Reference error: jsf is not defined” message.
I have put a :
<h:outputScript name="jsf.js" library="javax.faces" target="head"/>
inside h:head tag . But it did not help. The webpage is not responding after adding this line in firefox but it is working on IE, though ajax loader is not working in any case.
Please help.
Thanks in advance.

Resources