Spring Boot - Error during WebSocket handshake - spring-boot

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("*")

Related

send data from spring boot to client with stomp websocket

I want to send data from Boot(Server) to client!
I am using stomp websocket!
WebSocketClient doesn't work with error that the HTTP response from the server [200] did not permit the HTTP upgrade to WebSocket!
It's my Java Stomp WebSocket client code!
In this code, I tried to config handShakeHeader.... but it doesn't work!
package refill.station.websocket;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class WebSocketTest {
#Test
public void WebSocketTest() {
WebSocketClient webSocketClient = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
stompClient.setTaskScheduler(new ConcurrentTaskScheduler());
String url = "ws://localhost:8080/ws/websocket";
StompSessionHandler sessionHandler = new StompSessionHandlerAdapter() {};
List<String> protocols = new ArrayList<>();
protocols.add("v10.stomp");
protocols.add("v11.stomp");
WebSocketHttpHeaders handSahkeHeaders = new WebSocketHttpHeaders();
handSahkeHeaders.setUpgrade("websocket");
handSahkeHeaders.setConnection("Upgrade");
handSahkeHeaders.setSecWebSocketVersion("13");
handSahkeHeaders.setSecWebSocketKey("4hb9p5/JjeKLed5aXlBqnw==");
handSahkeHeaders.setSecWebSocketProtocol(protocols);
StompHeaders stompHeaders = new StompHeaders();
StompSession stompSession = null;
try {
stompSession = stompClient.connect(URI.create(url), handSahkeHeaders, stompHeaders, sessionHandler).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
stompSession.send("/app/control/complete", "msg");
// StompSession stompSession = stompClient.connect(url, sessionHandler).get();
}
}
I checked my WebSocket server with javascript and it works correctly!
This is my WebSocket server configuration!
package refill.station.config.websocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.RequestUpgradeStrategy;
import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
RequestUpgradeStrategy upgradeStrategy = new TomcatRequestUpgradeStrategy();
registry.addEndpoint("/ws")
.withSockJS();
registry.addEndpoint("/ws")
.setHandshakeHandler(new DefaultHandshakeHandler(upgradeStrategy))
.setAllowedOrigins("*");
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/control");
}
}
last, it's my controller for websocket!
package refill.station.controller.websocket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RequiredArgsConstructor
#RestController
#Slf4j
public class RefillerCommunicateController {
#MessageMapping("/control/complete")
#SendTo("/control/operate")
public String test(#Payload String data) {
log.info("RefillerCommunicateController-test method");
return "test";
}
}

${channels} is empty in JSP page served by Spring MVC

I am new to Java using STS 4 Eclipse, Java 8.
I am trying to use JSTL tags to output some values through my jsp file, however, I am not getting any output from my forEach loop in list.jsp. I am getting an output from the < p > tag directly before the loop.
Sorry for the large amount of code just didn't want to miss anything.
list.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Channels</title>
</head>
<body>
<p>Channels</p>
<c:forEach items="${channels}" var="channel">
<p>${channel.name}'s topic is ${channel.topic}</p>
<p> Link to the channel</p>
</c:forEach>
</body>
</html>
ChannelController.java
package co2103.hw1.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import co2103.hw1.Hw1Application;
import co2103.hw1.domain.Channel;
#Controller
public class ChannelController {
public List<Channel> channels;
#GetMapping("/channels")
public String channelsList(Model model) {
model.addAttribute("channels", Hw1Application.channels);
return "channels/list";
}
#RequestMapping("/newChannel")
public String newchannel(Model model) {
model.addAttribute("channel", new Channel());
return "channels/form";
}
#PostMapping("/addChannel")
public String updateChannel(#ModelAttribute Channel channel, BindingResult result) {
if (result.hasErrors()) {
return "channels/form";
}
int id = 0;
channel.setId(id);
String name = null;
channel.setName(name);
String topic = null;
channel.setTopic(topic);
Hw1Application.channels.add(channel);
return "redirect:/";
}
}
Hw1Application
package co2103.hw1;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import co2103.hw1.domain.Channel;
import co2103.hw1.domain.Show;
#SpringBootApplication
public class Hw1Application {
public static void main(String[] args) {
SpringApplication.run(Hw1Application.class, args);
}
public static List<Channel> channels = new ArrayList<>();
public static List<Show> shows = new ArrayList<>();
public void run(String... args) {
Channel channel = new Channel();
channel.setId(0);
channel.setName("Channel 1");
channel.setTopic("Nothing");
Show show = new Show();
show.setTitle("Show 1");
show.setProducer("Me");
show.setCategory("News");
show.setEpisodes(300);
Show show2 = new Show();
show.setTitle("Show 2");
show.setProducer("Me2");
show.setCategory("News2");
show.setEpisodes(300);
shows.add(show);
shows.add(show2);
channel.setShows(shows);
}
}
Channel.java
package co2103.hw1.domain;
import java.util.List;
public class Channel {
private int id;
private String name;
private String topic;
private List<Show> shows;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
}
in the class Hw1Application ==> the method public void run(String... args) :
you need to add in the end
channels.add(channel)
Because in ChannelController.java you called channels ( that is empty in w1Application and not setted) in you #GettingMapping
So the answer that worked for me was to implements CommandLineRunner in my Hw1Application class
Hw1Application.java
#SpringBootApplication
public class Hw1Application implements CommandLineRunner {
....
}

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

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);
}
}

Invalid property 'idUtilisateur' of bean class

I'm getting following error while running my Spring MVC web application:
Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
How can I fix it?
Utilisateur.java
package com.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idutilisateur")
private Long idUtilisateur;
#Column(name="emailutilisateur")
private String emailUtilisateur;
#Column(name="motpasseutilisateur")
private String motPasseUtilisateur;
#Column(name="nomutilisateur")
private String nomUtilisateur;
#Column(name="dateinscriptionutilisateur")
private Timestamp dateInscriptionUtilisateur;
public Long getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(Long idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getEmailUtilisateur() {
return emailUtilisateur;
}
public void setEmailUtilisateur(String emailUtilisateur) {
this.emailUtilisateur = emailUtilisateur;
}
public String getMotPasseUtilisateur() {
return motPasseUtilisateur;
}
public void setMotPasseUtilisateur(String motPasseUtilisateur) {
this.motPasseUtilisateur = motPasseUtilisateur;
}
public String getNomUtilisateur() {
return nomUtilisateur;
}
public void setNomUtilisateur(String nomUtilisateur) {
this.nomUtilisateur = nomUtilisateur;
}
public Timestamp getDateInscriptionUtilisateur() {
return dateInscriptionUtilisateur;
}
public void setDateInscriptionUtilisateur(Timestamp dateInscriptionUtilisateur) {
this.dateInscriptionUtilisateur = dateInscriptionUtilisateur;
}
#Override
public String toString() {
return "Utilisateur [idUtilisateur=" + idUtilisateur + ", emailUtilisateur=" + emailUtilisateur
+ ", motPasseUtilisateur=" + motPasseUtilisateur + ", nomUtilisateur=" + nomUtilisateur
+ ", dateInscriptionUtilisateur=" + dateInscriptionUtilisateur + "]";
}
}
UtilisateurController
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import com.model.Utilisateur;
import com.service.UtilisateurService;
#Controller
public class UtilisateurController {
#SuppressWarnings("unused")
private final static Logger logger = Logger.getLogger("UtilisateurController");
public UtilisateurController(){
System.out.println("spring_da_user_management_web_app");
}
#Autowired
private UtilisateurService service;
#RequestMapping(value="/newUtilisateur", method=RequestMethod.GET)
public ModelAndView newUtilisateur(ModelAndView model){
Utilisateur utilisateur = new Utilisateur();
model.addObject("utilisateur", utilisateur);
model.setViewName("utilisateurForm");
return model;
}
#RequestMapping(value = "/saveUtilisateur", method = RequestMethod.POST)
public ModelAndView saveUtilisateur(#ModelAttribute Utilisateur utilisateur) {
if (utilisateur.getIdUtilisateur() == 0) {
service.addUtilisateur(utilisateur);
} else {
service.updateUtilisateur(utilisateur);
}
return new ModelAndView("redirect:/");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView listeUtilisateur(ModelAndView model) throws IOException{
List<Utilisateur> listeUtilisateur = service.getAllUtilisateur();
model.addObject("listeUtilisateur", listeUtilisateur);
model.setViewName("listeutilisateur");
return model;
}
#RequestMapping(value = "/editUtilisateur", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
Long idUtilisateur = Long.parseLong(request.getParameter("idUtilisateur"));
Utilisateur utilisateur = service.getUtilisateurById(idUtilisateur);
ModelAndView model = new ModelAndView("utilisateurForm");
model.addObject("utilisateur", utilisateur);
return model;
}
#RequestMapping(value="/deleteUtilisateur", method=RequestMethod.GET)
public ModelAndView deleteUtilisateur(HttpServletRequest request){
service.deleteUtilisateur(Long.parseLong(request.getParameter("idUtilisateur")));
return new ModelAndView("redirect:/");
}
}
UtilisateurDao
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.Utilisateur;
#Repository
public class UtilisateurDaoImpl implements UtilisateurDao {
#Autowired
private SessionFactory sessionFactory;
public void addUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().saveOrUpdate(utilisateur);
}
#SuppressWarnings("unchecked")
public List<Utilisateur> getAllUtilisateur() {
List<Utilisateur> listeUtilisateur = sessionFactory.getCurrentSession().createQuery("from Utilisateur").list();
return listeUtilisateur;
}
public Utilisateur getUtilisateurById(Long idUtilisateur) {
return (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
}
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().update(utilisateur);
return utilisateur;
}
public void deleteUtilisateur(Long idUtilisateur) {
Utilisateur utilisateur = (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
if(utilisateur != null){
this.sessionFactory.getCurrentSession().delete(utilisateur);
}
}
}
utilisateurForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit / Save Utilisateur</title>
</head>
<body>
<div align="center">
<h1> Edit / Save Utilisateur</h1>
<form:form action="saveUtilisateur" method="post" modelAttribute="utilisateur">
<table>
<form:hidden path="idUtilisateur"/>
<tr>
<td>Adresse email</td>
<td><form:input path="emailUtilisateur"/></td>
</tr>
<tr>
<td>Mot de passe</td>
<td><form:password path="motPasseUtilisateur"/></td>
</tr>
<tr>
<td>Nom d'utilisateur</td>
<td><form:input path="nomUtilisateur"/></td>
</tr>
<tr>
<td>Date d'inscription</td>
<td><form:input path="dateInscriptionUtilisateur"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

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