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

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.

Related

Spring Boot - readMessageInternal of AbstractHttpMessageConverter implementation not getting invoked

Trying to write very simple http message converter to add encryption around request & respose.
Implemented rest controller and messageConverter. writeInternal does get invoked during response. However readInternal does not get invoked when request is sent to the rest end point.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
The below code is for encryption and decryption of request and response body For overall Project to modify response body and request parameters. Please check this code is works for me
For Request Encryption refer readInternal
below is the front-end or postman request sending, you have to add encrypted request in Json formate
Ex.{data : "+++++++++++++YOUR_ENCRYPTED_STRING++++++++++"}
For Response Descryption refer writeInternal
sending back to your front-end or postman request response with encrypted string
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
// Convert request to input stream for sending to the controller
private InputStream decrypt(InputStream inputStream) throws IOException {
//this is API request params
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException" + e.getMessage());
} catch (IOException e) {
logger.error("IOException" + e.getMessage());
} finally {
inputStream.close();
}
try {
JSONObject requestJsonObject = new JSONObject(writer.toString().replace("\n", ""));
// Add your decryption method the object data will get your encrypted string data and return with string of your JSON object
String decryptRequestString = EncryptionUtils.decryptText(requestJsonObject.getString("data"));
if (decryptRequestString != null) {
return new ByteArrayInputStream(decryptRequestString.getBytes(StandardCharsets.UTF_8));
} else {
return inputStream;
}
} catch (JSONException err) {
logger.error("Error" + err.toString());
} catch (NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException
| InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException e) {
logger.info("NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException | " +
"InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException:: " + e.getMessage());
}
return inputStream;
}
private byte[] encrypt(Object obj) throws JsonProcessingException {
// do your encryption here
try {
String stringFromObject = objectMapper.writeValueAsString(obj);
// Add your encryption method
String encrypt = EncryptionUtils.encryptText(stringFromObject);
return objectMapper.writeValueAsBytes(encrypt);
} catch (Exception e) {
logger.info("Error While Encrypt data :: " + e.getMessage());
return objectMapper.writeValueAsBytes(obj);
}
}
}
Reference code Spring Boot - Encrypt JSON data
Hope this code is working for you
It is invoking if the request has body and "supports" method return ture

Spring security Session Timeout handling for Ajax calls redirect to login not working

There are a lot of questions like this one similar to my question but not working. I am following this blog to redirect ajax request to login page when session timeout but in my case it is not working. here is the code
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.security.web.util.ThrowableCauseExtractor;
import org.springframework.web.filter.GenericFilterBean;
public class AjaxTimeoutRedirectFilter extends GenericFilterBean{
private static final Logger logger = LoggerFactory.getLogger(AjaxTimeoutRedirectFilter.class);
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private int customSessionExpiredErrorCode = 901;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
try
{
chain.doFilter(request, response);
logger.debug("Chain processed normally");
}
catch (IOException ex)
{
throw ex;
}
catch (Exception ex)
{
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
RuntimeException ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (ase == null)
{
ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
}
if (ase != null)
{
if (ase instanceof AuthenticationException)
{
throw ase;
}
else if (ase instanceof AccessDeniedException)
{
if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication()))
{
HttpServletRequest httpReq = (HttpServletRequest) request;
logger.info("User session expired or not logged in yet");
String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxHeader))
{
logger.info("Ajax call detected, send {} error code", this.customSessionExpiredErrorCode);
((HttpServletResponse)response).sendRedirect("/home/login");
return;
}else
{
((HttpServletResponse)response).sendRedirect("/home/login");
logger.info("Redirect to login page");
return;
}
}
else
{
this.redirectStrategy.sendRedirect((HttpServletRequest) request, (HttpServletResponse) response,"/home/login");
return;
}
}
}
}
}
private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer
{
/**
* #see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
protected void initExtractorMap()
{
super.initExtractorMap();
registerExtractor(ServletException.class, new ThrowableCauseExtractor()
{
public Throwable extractCause(Throwable throwable)
{
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
return ((ServletException) throwable).getRootCause();
}
});
}
}
public void setCustomSessionExpiredErrorCode(int customSessionExpiredErrorCode)
{
this.customSessionExpiredErrorCode = customSessionExpiredErrorCode;
}
}
I have added this <security:custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/> and the ajaxTimeoutRedirectFilter bean in the xml configuration file but not working. When i debug it goes to redirect code but the redirect is not redirecting to login.
As ajax call response status after redirect will be 200 instead of 302. There is no option left to identify redirection from status.
Instead of changing status code by implementing your own filter (order before ExceptionTranslationFilter), breaking filter chain by re-throwing exception.
Simple way is
1. Add this hidden div in login page.
<div style="display:none">LOGIN_PAGE_IDENTIFIER</div>
And in your each JSP page.(or, If you have any config.js which you include in every jsp page, add below code there)
<script type="text/javascript">
$(document).ajaxComplete(function (event, xhr, settings) {
if(xhr.responseText.indexOf("LOGIN_PAGE_IDENTIFIER") != -1)
window.location.reload();
});
</script>
PS:
About your concern regarding your AjaxTimeoutRedirectFilter
If you are receiving 901 status in ajax response then
$(document).ajaxComplete(function (event, xhr, settings) {
if(xhr.status == 901)
window.location.reload();
});
adding this to your every JSP page should solve your problem.

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

Java MessageDriven Beans Issue

i need help with this kind of issue:
Exception attempting to inject Unresolved Message-Destination-Ref web.News/queue#java.lang.String#null into class web.News: Lookup failed for 'java:comp/env/web.News/queue' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
This is my Entity Class
package ejb;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author Maciej1
*/
#Entity
public class NewsItem implements Serializable {
private String heading;
private String body;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof NewsItem)) {
return false;
}
NewsItem other = (NewsItem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejb.NewsItem[ id=" + id + " ]";
}
/**
* #return the heading
*/
public String getHeading() {
return heading;
}
/**
* #param heading the heading to set
*/
public void setHeading(String heading) {
this.heading = heading;
}
/**
* #return the body
*/
public String getBody() {
return body;
}
/**
* #param body the body to set
*/
public void setBody(String body) {
this.body = body;
}
}
here is my Message-Driven Beans class:
package ejb;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Maciej1
*/
#MessageDriven(mappedName = "jms/NewsQueue", activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class NewsMDB implements MessageListener {
#PersistenceContext(unitName = "MDBLabPU")
private EntityManager em;
public NewsMDB() {
}
#Override
public void onMessage(Message message) {
ObjectMessage msg = null;
try {
if (message instanceof ObjectMessage) {
msg = (ObjectMessage) message;
NewsItem e = (NewsItem) msg.getObject();
saveObject(e);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public void saveObject(Object object) {
em.persist(object);
}
}
In the end my class to communication with JavaServer Faces:
package web;
import ejb.NewsItem;
import ejb.NewsItemFacadeLocal;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
/**
*
* #author Maciej1
*/
#Named
#RequestScoped
public class News {
#EJB
private NewsItemFacadeLocal newsItemFacade;
#Resource(lookup="java:comp/DefaultJMSConnectionFactory")
private ConnectionFactory connectionFactory;
#Resource(lookup="jms/NewsQueue")
private javax.jms.Queue queue;
private String headingText = "headingText";
private String bodyText = "bodyText";
void sendNewsItem(String heading, String body)
{
try {
Connection connection = connectionFactory.createConnection();
Session session;
session = connection.createSession(true, 0);
MessageProducer messageProducer = session.createProducer(queue);
ObjectMessage message = session.createObjectMessage();
NewsItem e = new NewsItem();
e.setHeading(heading);
e.setBody(body);
message.setObject(e);
messageProducer.send(message);
messageProducer.close();
connection.close();
} catch (JMSException
ex) {
ex.printStackTrace();
}
}
public List<NewsItem> getNewsItems()
{
return newsItemFacade.findAll();
}
public String submitNews(){
sendNewsItem(getHeadingText(), getBodyText());
return null;
}
Can you help me with this issue?
I discover that problem can be probable in Faces file:
<?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://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:outputText></h:outputText>
<h:inputText value="#{news.headingText}" id="headingInputText"></h:inputText>
<h:outputText></h:outputText>
<h:inputText value="#{news.bodyText}" id="bodyInputText"></h:inputText>
<h:commandButton value="Submit" id="submitButton"></h:commandButton>
</h:form>
</h:body>
</html>
I had to change from this declaration:
#Resource(lookup="jms/NewsQueue")
private javax.jms.Queue queue;
to this:
#Resource(lookup="java:app/jms/NewsQueue")
private javax.jms.Queue queue;
It's generate from NetBeans 8.1 probably differently. Now this code work perfectly

Jfree bar chart servlet code with oracle database

I am new to jfree chart I have the following code it runs without any error, however the browser shows me an empty page .. do not know where is the problem.
I am trying to create a bar chart using jfree chart in servlet and the data will be retrieved from oracle data base.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities;
public class BarChar extends HttpServlet {
#Override
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("JDBC driver loaded");
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
OutputStream out = response.getOutputStream();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","FATIMAH", "FATIMAH");
DefaultCategoryDataset bar = new DefaultCategoryDataset();
Statement stmt = conn.createStatement();
ResultSet r = stmt.executeQuery("select category,marks from chart_data");
while (r.next())
{
String category = r.getString("CATEGORY");
int marks = r.getInt("MARKS");
bar.addValue(marks,"Mark",category);
}
JFreeChart BarChartObject=ChartFactory.createBarChart("Subject Vs Marks Bar Chart","Subject","Marks",bar,PlotOrientation.VERTICAL,true,true,false);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, BarChartObject, 400, 300);
}
catch (Exception e) {
System.err.println(e.toString());
}
finally {
out.close();
}
}
}

Resources