I am trying to send an image by drag and drop in send message area but its failing to do so. I dont know how to send an image in this code. Can someone please help me out?
ChatEndpoint.java
This is serverendpoint of websocket.I have four methods.onOpen,onClose,onMessage and onError.I am not doing anything in onOpen method.This method gets called when websocket establishes the connection.When the websocket tries to send message to the client,onMessage method gets called.Here the message sent from the jsp page(client) sends it in json string format to the server.The object mapper converts it to java object.I have also made an enum for MessageType having two options LOGIN and MESSAGE.I am checking inf the java object matches with the login message type then it stores the name of chat user from properties of user obtained from session object.It also then sends the session object to join method where the session is added to the list of session object.It also send the message the user has joined the chat room.If messagetype is a message then it sends it to send message method of room class where the message is sent back to the client using sendText.
#ServerEndpoint(value = "/chat")
public class ChatEndpoint {
private Logger log = Logger.getLogger(ChatEndpoint.class.getSimpleName());
private Room room = Room.getRoom();
#OnOpen
public void onOpen(final Session session, EndpointConfig config) {}
#OnMessage
public void onMessage(final Session session, final String messageJson) {
ObjectMapper mapper = new ObjectMapper();
ChatMessage chatMessage = null;
try {
chatMessage = mapper.readValue(messageJson, ChatMessage.class);
} catch (IOException e) {
String message = "Badly formatted message";
try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, message));
} catch (IOException ex) { log.severe(ex.getMessage()); }
} ;
Map<String, Object> properties = session.getUserProperties();
if (chatMessage.getMessageType() == MessageType.LOGIN) {
String name = chatMessage.getMessage();
properties.put("name", name);
room.join(session);
room.sendMessage(name + " - Joined the chat room");
}
else {
String name = (String)properties.get("name");
room.sendMessage(name + " - " + chatMessage.getMessage());
}
}
#OnClose
public void OnClose(Session session, CloseReason reason) {
room.leave(session);
room.sendMessage((String)session.getUserProperties().get("name") + " - Left the room");
}
#OnError
public void onError(Session session, Throwable ex) { log.info("Error: " + ex.getMessage()); }
}
Room.java
public class Room {
private static Room instance = null;
private List<Session> sessions = new ArrayList<Session>();
public synchronized void join(Session session) { sessions.add(session); }
public synchronized void leave(Session session) { sessions.remove(session); }
public synchronized void sendMessage(String message) {
for (Session session: sessions) {
if (session.isOpen()) {
try { session.getBasicRemote().sendText(message); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
public synchronized static Room getRoom() {
if (instance == null) { instance = new Room(); }
return instance;
}
}
index.jsp
Here i am sending the wsUri which is stored in context param as ws://localhost:8080/single-room-chat/chat
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<% String WsUrl = getServletContext().getInitParameter("WsUrl"); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name='viewport' content='minimum-scale=1.0, initial-scale=1.0,
width=device-width, maximum-scale=1.0, user-scalable=no'/>
<title>single-room-chat</title>
<link rel="stylesheet" type="text/css" href="content/styles/site.css">
<script type="text/javascript" src="scripts/chatroom.js"></script>
<script type="text/javascript">
var wsUri = '<%=WsUrl%>';
var proxy = CreateProxy(wsUri);
document.addEventListener("DOMContentLoaded", function(event) {
console.log(document.getElementById('loginPanel'));
proxy.initiate({
loginPanel: document.getElementById('loginPanel'),
msgPanel: document.getElementById('msgPanel'),
txtMsg: document.getElementById('txtMsg'),
txtLogin: document.getElementById('txtLogin'),
msgContainer: document.getElementById('msgContainer')
});
});
</script>
</head>
<body>
<div id="container">
<div id="loginPanel">
<div id="infoLabel">Type a name to join the room</div>
<div style="padding: 10px;">
<input id="txtLogin" type="text" class="loginInput"
onkeyup="proxy.login_keyup(event)" />
<button type="button" class="loginInput" onclick="proxy.login()">Login</button>
</div>
</div>
<div id="msgPanel" style="display: none">
<div id="msgContainer" style="overflow: auto;"></div>
<div id="msgController">
<textarea id="txtMsg"
title="Enter to send message"
onkeyup="proxy.sendMessage_keyup(event)"
style="height: 20px; width: 100%"></textarea>
<button style="height: 30px; width: 100px" type="button"
onclick="proxy.logout()">Logout</button>
</div>
</div>
</div>
</body>
</html>
chatroom.js
var CreateProxy = function(wsUri) {
var websocket = null;
var audio = null;
var elements = null;
var playSound = function() {
if (audio == null) {
audio = new Audio('content/sounds/beep.wav');
}
audio.play();
};
var showMsgPanel = function() {
elements.loginPanel.style.display = "none";
elements.msgPanel.style.display = "block";
elements.txtMsg.focus();
};
var hideMsgPanel = function() {
elements.loginPanel.style.display = "block";
elements.msgPanel.style.display = "none";
elements.txtLogin.focus();
};
var displayMessage = function(msg) {
if (elements.msgContainer.childNodes.length == 100) {
elements.msgContainer.removeChild(elements.msgContainer.childNodes[0]);
}
var div = document.createElement('div');
div.className = 'msgrow';
var textnode = document.createTextNode(msg);
div.appendChild(textnode);
elements.msgContainer.appendChild(div);
elements.msgContainer.scrollTop = elements.msgContainer.scrollHeight;
};
var clearMessage = function() {
elements.msgContainer.innerHTML = '';
};
return {
login: function() {
elements.txtLogin.focus();
var name = elements.txtLogin.value.trim();
if (name == '') { return; }
elements.txtLogin.value = '';
// Initiate the socket and set up the events
if (websocket == null) {
websocket = new WebSocket(wsUri);
websocket.onopen = function() {
var message = { messageType: 'LOGIN', message: name };
websocket.send(JSON.stringify(message));
};
websocket.onmessage = function(e) {
displayMessage(e.data);
showMsgPanel();
playSound();
};
websocket.onerror = function(e) {};
websocket.onclose = function(e) {
websocket = null;
clearMessage();
hideMsgPanel();
};
}
},
sendMessage: function() {
elements.txtMsg.focus();
if (websocket != null && websocket.readyState == 1) {
var input = elements.txtMsg.value.trim();
if (input == '') { return; }
elements.txtMsg.value = '';
var message = { messageType: 'MESSAGE', message: input };
// Send a message through the web-socket
websocket.send(JSON.stringify(message));
}
},
login_keyup: function(e) { if (e.keyCode == 13) { this.login(); } },
sendMessage_keyup: function(e) { if (e.keyCode == 13) { this.sendMessage(); } },
logout: function() {
if (websocket != null && websocket.readyState == 1) { websocket.close();}
},
initiate: function(e) {
elements = e;
elements.txtLogin.focus();
}
}
};
Related
I'm writing a simple application in which a javascript web socket client has to send image to a webscoket implemented by tomcat and Java language.
when I send a string message every thing is going well but #Onmessage event don't be fired if I send an image data. I've spent 2 days but haven't the solution yet.
Java WebSocket Code:
#ServerEndpoint("/sendfile")
public class BinaryWebSocketServer {
private
static final Set<Session> sessions =
Collections.synchronizedSet(new HashSet<Session>());
#OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("onOpen_File::" + session.getId());
}
#OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("onClose_File::" + session.getId());
}
#OnMessage
public void onMessage(byte[] data, Session session) {
System.out.println("onByteArrayMessage::From=" + session.getId() + " with len:" + data.length );
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2;
try {
bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("image created");
}
#OnError
public void onError(Throwable t) {
System.out.println("onError::" + t.getMessage());
}
}
Javascript Client:
<body>
<h2>File Upload</h2> Select file
<input type="file" id="filename" />
<br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
<br />
<textarea id="echoText" rows="5" cols="30"></textarea>
<script>
var webSocket = new WebSocket("ws://192.168.1.55:8081/Hello-Capture/sendfile");
webSocket.binaryType = 'arraybuffer';
webSocket.onopen = function(message){ wsOpen(message);};
//webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
}
function wsError(message){
echoText.value += "Error ..." + message.code +" \n";
}
function sendFile() {
var file = document.getElementById('filename').files[0];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.loadend = function(e) {
};
reader.onload = function(e) {
var rawData = e.target.result;
var byteArray = new Uint8Array(rawData);
var fileByteArray = [];
webSocket.send(byteArray.buffer);
echoText.value =("the File has been transferred.\n");
};
reader.readAsArrayBuffer(file);
}
</script>
</body>
Finally I find the solution so I comment it maybe some one else gets stuck into.
I've forgotten to pass a boolean parameter to onMessage function.
the correct form is :
#OnMessage
public void onMessage(byte[] data,boolean last, Session session) {
.
.
.
}
I create application similar to https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
But I use Spring Security and this is the reason of error (if I remove Spring Security all work correctly):
{"timestamp":"2018-08-20T09:26:44.223+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/uploadFile"}
What I have to change for avoid this problem?
FileController:
#RestController
public class FileController {
private final FileStorageService fileStorageService;
#Autowired
public FileController(FileStorageService fileStorageService) {
this.fileStorageService = fileStorageService;
}
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String filename = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(filename)
.toUriString();
return new UploadFileResponse(
filename,
fileDownloadUri,
file.getContentType(),
file.getSize()
);
}
//...
}
upload-files.html with vanila js script that send post query:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Spring Boot File Upload / Download Rest API Example</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="upload-container">
<div class="upload-header">
<h2>File Upload</h2>
</div>
<div class="upload-content">
<div class="single-upload">
<h3>Upload Single File</h3>
<form id="singleUploadForm" name="singleUploadForm">
<input id="singleFileUploadInput" type="file" name="file" class="file-input" required />
<button type="submit" class="primary submit-btn">Submit</button>
</form>
<div class="upload-response">
<div id="singleFileUploadError"></div>
<div id="singleFileUploadSuccess"></div>
</div>
</div>
</div>
</div>
</body>
<script>
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
</script>
</html>
UPDATE
WebSecurityConfig:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private final CustomUserDetailsService userDetailsService;
#Autowired
public WebSecurityConfig(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
#Override
public boolean matches(CharSequence charSequence, String encoded) {
return !encoded.equals(USER_NOT_FOUND_PASSWORD)
&& BCrypt.checkpw(charSequence.toString(), encoded);
}
};
}
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
.hasRole("USER").and()
// Possibly more configuration ...
.formLogin() // enable form based log in
// set permitAll for all URLs associated with Form Login
.permitAll();
}
You should add access persmission to url's otherwise spring security won't allow to access.
I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
{
try
{
string Baseurl = sys_ser.getApiURL();
EmployeeModel EmpInfo = new EmployeeModel();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
//var EmpObj = empobjList[0];
if (empobjList != null)
{
return empobjList;
}
}
}
}
catch(Exception ex)
{
//<Srcript> alert('WebService is not available' + ex.message)</>
}
return null;
}
If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);
View:
#model string
<!--Your HTML-->
#if (!string.IsNullOrEmpty(Model)
{
<script type="text/javascript">
alert(Model);
</script>
}
I am running the following script on the client-side and the script is failing to update, when there is change in the database. I debugged the script using DevTools and discovered my Jquery scripts are responding back as "304 not modified". Does this issue, indicate why the client-side content is failing to update.
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery-1.6.4.min.js"></script>
<script src="../Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
alert("Notifications have been sent.");
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
</script>
<h1>New Notifications</h1>
<div>
<br />
<b>New <span id="spanNewMessages"></span> = role.</b><br />
<b>New <span id="spanNewCircles"></span> = descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT top 1 [role],[description] FROM [dbo].[User] order by uploadDate desc";
connection.Open();
SqlDependency.Start(GetConnectionString());
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
[HubMethodName("onStatusChanged")]
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
Please advice. Thank you.
In Microsoft Visual Studio Express I have started a new project using the "Windows Phone HTML5 App" template. If I run the emulator, everything works fine. Next I added the following JavaScript to the index.html page:
<script type="text/javascript">
window.onload = function(){
alert(window.location.href); // --> x-wmapp0:/Html/index.html
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
alert('ON READY STATE CHANGE');
if(xmlhttp.readyState==4){
alert(xmlhttp.responseText);
}
}
//xmlhttp.open("GET","text.txt",true); // I have tried all of these
//xmlhttp.open("GET","Html/text.txt",true);
//xmlhttp.open("GET","/Html/text.txt",true);
xmlhttp.open("GET","x-wmapp0:/Html/text.txt",true);
xmlhttp.send();
}
</script>
Now when I run the app in the emulator I get the first alert with the window location, but do not get any alerts from the readyState or onreadystatechange. The text.txt file is on the same level as the index.html. I have run this code in IE10 and it works just fine. Any ideas on what I am doing wrong?
Update: I have deployed this on an actual Windows 8 phone and got the same result
Cheers
Here is what Microsoft told me from MSDN
XMLHttpRequest only works for retrieving network resources. i.e. You cannot use it to access content from your applications local storage, i.e. XAP or IsolatedStorage.
Here is an example of script + code which I have used in the past to work around this limitation:
HTML Page with JavaScript:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script type="text/javascript">
function LoadFile(SourceURL) {
try {
var httpfreq = new XMLHttpRequest();
httpfreq.onreadystatechange = function () {
filecontent.innerText = "httpfreq.onreadystatechange fired, readyState = " + httpfreq.readyState.toString();
if (httpfreq.readyState = 4) {
filecontent.innerText = "Status = " + httpfreq.status.toString();
if (httpfreq.status = 200) {
window.external.notify("Received content" + httpfreq.responseText);
filecontent.innerHTML = httpfreq.responseText;
}
else {
window.external.notify("Error loading page: " + SourceURL);
filecontent.innerText = "Error loading page " + SourceURL;
}
}
};
httpfreq.open("GET", SourceURL);
httpfreq.send(null);
}
catch (e) {
if (e.number = 0x80070005) {
LoadLocalFile(SourceURL, "GetResourceCallback");
}
else {
alert(e.name + " " + e.number.toString());
}
}
}
function LoadLocalFile(SourceURL, callbackfn) {
window.external.notify("GetResource?file=" + SourceURL + ";callback=" + callbackfn);
}
function GetResourceCallback(StringContent) {
filecontent.innerText = StringContent;
}
</script>
</head>
<body>
<p>
test page: notes.html
</p>
<p><input type="button" onclick="LoadFile('text.txt')" value="Load Local" /> </p>
<p><input type="button" onclick="LoadFile('http://www.somedomain.com/text.txt')" value="Load remote" /> </p>
<p>---------------------------</p>
<div id="filecontent"></div>
<p>---------------------------</p>
</body>
</html>
And the required App Host code (c#)
private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Script Notify : {0}",e.Value);
if (e.Value.Contains("GetResource?file="))
{
Dispatcher.BeginInvoke(() =>
{
String szArgs = e.Value;
string szResource = null;
string szCallbackFn = null;
char[] separators = new char[2] {'?',';'};
string[] parms = szArgs.Split(separators);
for (int i = 1; i < parms.Length; i++ )
{
if (parms[i].Contains("file="))
{
szResource = parms[i].Substring(5);
}
else if (parms[i].Contains("callback="))
{
szCallbackFn = parms[i].Substring(9);
}
}
if (!String.IsNullOrWhiteSpace(szResource) && !String.IsNullOrWhiteSpace(szCallbackFn))
{
// read local resource.
string szFileContent= "Resource not found!";
try
{
if (String.IsNullOrEmpty(webBrowser1.Base))
{
// if Base is not set then assume XAP file content.
szFileContent = ReadXAPResource(szResource);
}
else
{
// else assume IsolatedStorage
szFileContent = ReadISOFile(webBrowser1.Base, szResource);
}
}
catch (Exception)
{}
webBrowser1.InvokeScript(szCallbackFn, szFileContent);
}
});
}
}
private string ReadXAPResource(string szFile)
{
string szContent = "File Not Found";
try
{
// in my project HTML files are in the HelpContent folder...
StringBuilder szPath = new StringBuilder("HelpContent");
if (!szFile.StartsWith("/"))
szPath.Append("/");
szPath.Append(szFile);
StreamResourceInfo sri = Application.GetResourceStream(new Uri(szPath.ToString(), UriKind.Relative));
if (null != sri)
{
StreamReader strm = new StreamReader(sri.Stream);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}
private string ReadISOFile(string szBase, string szFile)
{
string szContent = "File Not Found";
try
{
string fullPath = szBase + szFile;
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfsInput = isf.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (null != isfsInput)
{
StreamReader strm = new StreamReader(isfsInput);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}