Search Results

Search found 18 results on 1 pages for 'eventsource'.

Page 1/1 | 1 

  • Event Source Live streaming in Ruby on rails onError method

    - by kishorebjv
    I'm trying to implement basic rails4 code with eventsource API & Action controller live, Everything is fine but I'm not able to reach event listner . Controller code: class HomeController < ApplicationController include ActionController::Live def tester response.headers["Content-Type"] = "text/event-stream" 3.times do |n| response.stream.write "message: hellow world! \n\n" sleep 2 end end Js code: var evSource = new EventSource("/home/tester"); evSource.onopen = function (e) { console.log("OPEN state \n"+e.data); }; evSource.addEventListener('message',function(e){ console.log("EventListener .. code.."); },false); evSource.onerror = function (e) { console.log("Error State \n\n"+e.data); }; & When i reloading the page, My console output was "OPEN state" & then "Error State" as output.. event-listener code was not displaying . 1.When I'm curling the page, "message: Hellow world!" was displaying. 2.I changed in development.rb config.cache_classes = true config.eager_load = true 3. My browsers are chrome & firefox are latest versions, so no issues with them, Where I'm missing? suggestions please!

    Read the article

  • Server-Sent Events using GlassFish (TOTD #179)

    - by arungupta
    Bhakti blogged about Server-Sent Events on GlassFish and I've been planning to try it out for past some days. Finally, I took some time out today to learn about it and build a simplistic example showcasing the touch points. Server-Sent Events is developed as part of HTML5 specification and provides push notifications from a server to a browser client in the form of DOM events. It is defined as a cross-browser JavaScript API called EventSource. The client creates an EventSource by requesting a particular URL and registers an onmessage event listener to receive the event notifications. This can be done as shown var url = 'http://' + document.location.host + '/glassfish-sse/simple';eventSource = new EventSource(url);eventSource.onmessage = function (event) { var theParagraph = document.createElement('p'); theParagraph.innerHTML = event.data.toString(); document.body.appendChild(theParagraph);} This code subscribes to a URL, receives the data in the event listener, adds it to a HTML paragraph element, and displays it in the document. This is where you'll parse JSON and other processing to display if some other data format is received from the URL. The URL to which the EventSource is subscribed to is updated on the server side and there are multipe ways to do that. GlassFish 4.0 provide support for Server-Sent Events and it can be achieved registering a handler as shown below: @ServerSentEvent("/simple")public class MySimpleHandler extends ServerSentEventHandler { public void sendMessage(String data) { try { connection.sendMessage(data); } catch (IOException ex) { . . . } }} And then events can be sent to this handler using a singleton session bean as shown: @Startup@Statelesspublic class SimpleEvent { @Inject @ServerSentEventContext("/simple") ServerSentEventHandlerContext<MySimpleHandler> simpleHandlers; @Schedule(hour="*", minute="*", second="*/10") public void sendDate() { for(MySimpleHandler handler : simpleHandlers.getHandlers()) { handler.sendMessage(new Date().toString()); } }} This stateless session bean injects ServerSentEventHandlers listening on "/simple" path. Note, there may be multiple handlers listening on this path. The sendDate method triggers every 10 seconds and send the current timestamp to all the handlers. The client side browser simply displays the string. The HTTP request headers look like: Accept: text/event-streamAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Cache-Control: no-cacheConnection: keep-aliveCookie: JSESSIONID=97ff28773ea6a085e11131acf47bHost: localhost:8080Referer: http://localhost:8080/glassfish-sse/faces/index2.xhtmlUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5 And the response headers as: Content-Type: text/event-streamDate: Thu, 14 Jun 2012 21:16:10 GMTServer: GlassFish Server Open Source Edition 4.0Transfer-Encoding: chunkedX-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Apple Inc./1.6) Notice, the MIME type of the messages from server to the client is text/event-stream and that is defined by the specification. The code in Bhakti's blog can be further simplified by using the recently-introduced Twitter API for Java as shown below: @Schedule(hour="*", minute="*", second="*/10") public void sendTweets() { for(MyTwitterHandler handler : twitterHandler.getHandlers()) { String result = twitter.search("glassfish", String.class); handler.sendMessage(result); }} The complete source explained in this blog can be downloaded here and tried on GlassFish 4.0 build 34. The latest promoted build can be downloaded from here and the complete source code for the API and implementation is here. I tried this sample on Chrome Version 19.0.1084.54 on Mac OS X 10.7.3.

    Read the article

  • Enterprise Instrumentation: The 'sessionName' parameter of value 'TraceSession' is not valid

    - by Michael Freidgeim
    We are still using Enterprise Instrumentation(that was created during .Net 1.1 time)In new Server 2008 environment and IIS 7 we have the following errors:The 'sessionName' parameter of value 'TraceSession' is not valid. A trace session of this name does not exist in the TraceSessions configuration file for Windows Trace Session Manager service. Ensure that a session of this name exists in the TraceSessions configuration file and that the Windows Trace Session Manager service is started.   at Microsoft.EnterpriseInstrumentation.EventSinks.TraceEventSink..ctor(IDictionary parameters, EventSource eventSource)   --- End of inner exception stack trace ---   at System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo method, Object[] args, SignatureStruct& signature, RuntimeType declaringType)   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)   at Microsoft.EnterpriseInstrumentation.EventSinks.EventSink.CreateNewEventSinks(DataRow[] eventSinkRows, EventSource eventSource)I’ve seen the same errors on development Win7 machines when using IIS. It seems not a problem on Cassini.I've checked ,that Windows Trace Session Manager Service has started and The file C:\Program Files (x86)\Microsoft Enterprise Instrumentation\Bin\Trace Service\TraceSessions.config has corresponding entry<?xml version="1.0" encoding="utf-8" ?><configuration >                <defaultParameters minBuffers="4" maxFileSize="10" maxBuffers="25" bufferSize="20" logFileMode="sequential" flushTimer="3" />                <sessionList>                                 <session name="TraceSession" enabled="false" fileName="C:\Program Files (x86)\Microsoft Enterprise Instrumentation\Bin\Trace Service\Logs\TraceLog.log" />                </sessionList></configuration>The errors still continue, but I was able to disable  the parameter in  eventSink configuration   <eventSink name=" traceSink" description=" Outputs events to the Windows Event Trace." type ="Microsoft.EnterpriseInstrumentation.EventSinks.TraceEventSink ">                <!-- MNF disabled parameter to  avoid error "The 'sessionName' parameter of value 'TraceSession' is not valid"                      < parameter name ="sessionName " value ="TraceSession " />                    -->    </ eventSink>Related old post http://bytes.com/topic/net/answers/104761-enterprise-instrumentation-windows-trace-session-managerOne day I wish to replace all EnterpriseInstrumentation calls with NLog.

    Read the article

  • MVC: returning multiple results on stream connection to implement HTML5 SSE

    - by eddo
    I am trying to set up a lightweight HTML5 Server-Sent Event implementation on my MVC 4 Web, without using one of the libraries available to implement sockets and similars. The lightweight approach I am trying is: Client side: EventSource (or jquery.eventsource for IE) Server side: long polling with AsynchController (sorry for dropping here the raw test code but just to give an idea) public class HTML5testAsyncController : AsyncController { private static int curIdx = 0; private static BlockingCollection<string> _data = new BlockingCollection<string>(); static HTML5testAsyncController() { addItems(10); } //adds some test messages static void addItems(int howMany) { _data.Add("started"); for (int i = 0; i < howMany; i++) { _data.Add("HTML5 item" + (curIdx++).ToString()); } _data.Add("ended"); } // here comes the async action, 'Simple' public void SimpleAsync() { AsyncManager.OutstandingOperations.Increment(); Task.Factory.StartNew(() => { var result = string.Empty; var sb = new StringBuilder(); string serializedObject = null; //wait up to 40 secs that a message arrives if (_data.TryTake(out result, TimeSpan.FromMilliseconds(40000))) { JavaScriptSerializer ser = new JavaScriptSerializer(); serializedObject = ser.Serialize(new { item = result, message = "MSG content" }); sb.AppendFormat("data: {0}\n\n", serializedObject); } AsyncManager.Parameters["serializedObject"] = serializedObject; AsyncManager.OutstandingOperations.Decrement(); }); } // callback which returns the results on the stream public ActionResult SimpleCompleted(string serializedObject) { ServerSentEventResult sar = new ServerSentEventResult(); sar.Content = () => { return serializedObject; }; return sar; } //pushes the data on the stream in a format conforming HTML5 SSE public class ServerSentEventResult : ActionResult { public ServerSentEventResult() { } public delegate string GetContent(); public GetContent Content { get; set; } public int Version { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.Content != null) { HttpResponseBase response = context.HttpContext.Response; // this is the content type required by chrome 6 for server sent events response.ContentType = "text/event-stream"; response.BufferOutput = false; // this is important because chrome fails with a "failed to load resource" error if the server attempts to put the char set after the content type response.Charset = null; string[] newStrings = context.HttpContext.Request.Headers.GetValues("Last-Event-ID"); if (newStrings == null || newStrings[0] != this.Version.ToString()) { string value = this.Content(); response.Write(string.Format("data:{0}\n\n", value)); //response.Write(string.Format("id:{0}\n", this.Version)); } else { response.Write(""); } } } } } The problem is on the server side as there is still a big gap between the expected result and what's actually going on. Expected result: EventSource opens a stream connection to the server, the server keeps it open for a safe time (say, 2 minutes) so that I am protected from thread leaking from dead clients, as new message events are received by the server (and enqueued to a thread safe collection such as BlockingCollection) they are pushed in the open stream to the client: message 1 received at T+0ms, pushed to the client at T+x message 2 received at T+200ms, pushed to the client at T+x+200ms Actual behaviour: EventSource opens a stream connection to the server, the server keeps it open until a message event arrives (thanks to long polling) once a message is received, MVC pushes the message and closes the connection. EventSource has to reopen the connection and this happens after a couple of seconds. message 1 received at T+0ms, pushed to the client at T+x message 2 received at T+200ms, pushed to the client at T+x+3200ms This is not OK as it defeats the purpose of using SSE as the clients start again reconnecting as in normal polling and message delivery gets delayed. Now, the question: is there a native way to keep the connection open after sending the first message and sending further messages on the same connection?

    Read the article

  • javascript variable evaluation in function

    - by lamerzpua
    I trying to use simile widget for own need but I'm stuck on such problem. I have loop for (i=0;i<15;i++){ Timeline.loadXML(function_that_return_url(), function(xml, url) { eventSource[i].loadXML(xml, url); }); } This code is for Timeline.loadXML: Timeline.loadXML = function(url, f) { var fError = function(statusText, status, xmlhttp) { alert("Failed to load data xml from " + url + "\n" + statusText); }; var fDone = function(xmlhttp) { var xml = xmlhttp.responseXML; if (!xml.documentElement && xmlhttp.responseStream) { xml.load(xmlhttp.responseStream); } f(xml, url); }; SimileAjax.XmlHttp.get(url, fError, fDone);}; When I open the page - my function function(xml, url) { eventSource[i].loadXML(xml, url); }); is passed to loadXML method which use it inside as f(xml, url); Problem is that i variable is not parsed as number and I receive message that eventSource[...] is not declared. How I can evaluate i values before it will be posted as argument for the method LoadXML ?

    Read the article

  • How do JVM's implicit memory barriers behave when chaining constructors

    - by Joonas Pulakka
    Referring to my earlier question on incompletely constructed objects, I have a second question. As Jon Skeet pointed out, there's an implicit memory barrier in the end of a constructor that makes sure that final fields are visible to all threads. But what if a constructor calls another constructor; is there such a memory barrier in the end of each of them, or only in one being called from outside? That is, when the "wrong" solution is: public class ThisEscape { public ThisEscape(EventSource source) { source.registerListener( new EventListener() { public void onEvent(Event e) { doSomething(e); } }); } } And the correct one would be a factory method version: public class SafeListener { private final EventListener listener; private SafeListener() { listener = new EventListener() { public void onEvent(Event e) { doSomething(e); } } } public static SafeListener newInstance(EventSource source) { SafeListener safe = new SafeListener(); source.registerListener(safe.listener); return safe; } } Would the following work too, or not? public class MyListener { private final EventListener Listener; private MyListener() { listener = new EventListener() { public void onEvent(Event e) { doSomething(e); } } } public MyListener(EventSource source) { this(); source.register(listener); } }

    Read the article

  • JS function returning another function

    - by Michael
    I want to understand about variables, that has been used in returning function. This is example code Prototype = {} Prototype.F = { bind: function() { var args = arguments, __method = args.shift(), object = args.shift(); return function() { return __method.apply(object, args.concat(arguments)); } } } function ObjectA() { ... this.addListener = Prototype.F.bind(this.eventSource.addListener, this.eventSource); ... } var a = ObjectA(); a.addListener(this); // assuming 'this' here will point to some window object As I understand the returning function in F() is not evaluated until it's called in the last line. It's ok to accept. So addListener will hold a function body containing 'apply'. But what I don't understand, when addListener is called, what kind of parameters it is going to have? particularly _method and args will always be uninitialized?

    Read the article

  • Send post data while opening SSE connection

    - by Prosto Trader
    I'm trying to establish SSE connection and do some long-taking actions on server-side, informing user about how it goes through SSE events. Actually, I don't understand how would I send some data along with new connection. I have to combine regular ajax with new EventSource or there is a way to transfer post data inside that event? Here is what I have so far, and I need to send pretty big JSON with the request. Is it possible or the only way to send data is GET? var source = new EventSource('/terminal/ajax-put-packet-trade-order/');

    Read the article

  • Responding to the page unload in a managed bean

    - by frank.nimphius
    Though ADF Faces provides an uncommitted data warning functionality, developers may have the requirement to respond to the page unload event within custom application code, programmed in a managed bean. The af:clientListener tag that is used in ADF Faces to listen for JavaScript and ADF Faces client component events does not provide the option to listen for the unload event. So this often recommended way of implementing JavaScript in ADF Faces does not work for this use case. To send an event from JavaScript to the server, ADF Faces provides the af:serverListener tag that you use to queue a CustomEvent that invokes method in a managed bean. While this is part of the solution, during testing, it turns out, the browser native JavaScript unload event itself is not very helpful to send an event to the server using the af:serverListener tag. The reason for this is that when the unload event fires, the page already has been unloaded and the ADF Faces AdfPage object needed to queue the custom event already returns null. So the solution to the unload page event handling is the unbeforeunload event, which I am not sure if all browsers support them. I tested IE and FF and obviously they do though. To register the beforeunload event, you use an advanced JavaScript programming technique that dynamically adds listeners to page events. <af:document id="d1" onunload="performUnloadEvent"                      clientComponent="true"> <af:resource type="javascript">   window.addEventListener('beforeunload',                            function (){performUnloadEvent()},false)      function performUnloadEvent(){   //note that af:document must have clientComponent="true" set   //for JavaScript to access the component object   var eventSource = AdfPage.PAGE.findComponentByAbsoluteId('d1');   //var x and y are dummy variables obviously needed to keep the page   //alive for as long it takes to send the custom event to the server   var x = AdfCustomEvent.queue(eventSource,                                "handleOnUnload",                                {args:'noargs'},false);   //replace args:'noargs' with key:value pairs if your event needs to   //pass arguments and values to the server side managed bean.   var y = 0; } </af:resource> <af:serverListener type="handleOnUnload"                    method="#{UnloadHandler.onUnloadHandler}"/> // rest of the page goes here … </af:document> The managed bean method called by the custom event has the following signature:  public void onUnloadHandler(ClientEvent clientEvent) {  } I don't really have a good explanation for why the JavaSCript variables "x" and "y" are needed, but this is how I got it working. To me it ones again shows how fragile custom JavaScript development is and why you should stay away from using it whenever possible. Note: If the unload event is produced through navigation in JavaServer Faces, then there is no need to use JavaScript for this. If you know that navigation is performed from one page to the next, then the action you want to perform can be handled in JSF directly in the context of the lifecycle.

    Read the article

  • Read attributes of MSBuild custom tasks via events in the Logger

    - by gt
    I am trying to write a MSBuild logger module which logs information when receiving TaskStarted events about the Task and its parameters. The build is run with the command: MSBuild.exe /logger:MyLogger.dll build.xml Within the build.xml is a sequence of tasks, most of which have been custom written to compile a (C++ or C#) solution, and are accessed with the following custom Task: <DoCompile Desc="Building MyProject 1" Param1="$(Param1Value)" /> <DoCompile Desc="Building MyProject 2" Param1="$(Param1Value)" /> <!-- etc --> The custom build task DoCompile is defined as: public class DoCompile : Microsoft.Build.Utilities.Task { [Required] public string Description { set { _description = value; } } // ... more code here ... } Whilst the build is running, as each task starts, the logger module receives IEventSource.TaskStarted events, subscribed to as follows: public class MyLogger : Microsoft.Build.Utilities.Logger { public override void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { eventSource.TaskStarted += taskStarted; } private void taskStarted(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e) { // write e.TaskName, attributes and e.Timestamp to log file } } The problem I have is that in the taskStarted() method above, I want to be able to access the attributes of the task for which the event was fired. I only have access to the logger code and cannot change either the build.xml or the custom build tasks. Can anyone suggest a way I can do this?

    Read the article

  • MessageQueue.BeginReceive() null ref error - c#

    - by ltech
    Have a windows service that listens to a msmq. In the OnStart method is have this protected override void OnStart(string[] args) { try { _queue = new MessageQueue(_qPath);//this part works as i had logging before and afer this call //Add MSMQ Event _queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);//this part works as i had logging before and afer this call _queue.BeginReceive();//This is where it is failing - get a null reference exception ; } catch(Exception ex) { EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed + ex.InnerException.ToString() + _lineFeed + ex.Message.ToString()); } } where private MessageQueue _queue = null;

    Read the article

  • Use a "x-dom-event-stream" stream in javascript ?

    - by rnaud
    Hello, HTML5 draft contains an API called EventSource to stream data (notifications) trough javascript using only one server call. Looking it up, I found an exemple on Opera Labs of the javascript part : document.getElementsByTagName("event-source")[0] .addEventListener("server-time", eventHandler, false); function eventHandler(event) { // Alert time sent by the server alert(event.data); } and the server side part : <?php header("Content-Type: application/x-dom-event-stream"); while(true) { echo "Event: server-time\n"; $time = time(); echo "data: $time\n"; echo "\n"; flush(); sleep(3); } ?> But as of today, it seems only Opera has implemented the API, neither Chrome nor Safari have a working version (Am I wrong here ?) So my question is, is there any other way in javascript, maybe more complex, to use this one stream to get data ?

    Read the article

  • What is an "incompletely constructed object"?

    - by Joonas Pulakka
    Goetz's Java Concurrency in Practice, page 41, mentions how this reference can escape during construction. A "don't do this" example: public class ThisEscape { public ThisEscape(EventSource source) { source.registerListener( new EventListener() { public void onEvent(Event e) { doSomething(e); } }); } } Here this is "escaping" via the fact that doSomething(e) refers to the enclosing ThisEscape instance. The book states: Publishing an object from within its constructor can publish an incompletely constructed object. This is true even if the publication is the last statement in the constructor. If the this reference escapes during construction, the object is considered not properly constructed. I don't quite get this. If the publication is the last statement in the constructor, hasn't all the constructing work been done before that? How come is this not valid by then? Apparently there's some voodoo going on after that, but what?

    Read the article

  • Solved::MessageQueue.BeginReceive() null ref error - c#

    - by ltech
    Have a windows service that listens to a msmq. In the OnStart method is have this protected override void OnStart(string[] args) { try { _queue = new MessageQueue(_qPath);//this part works as i had logging before and afer this call //Add MSMQ Event _queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);//this part works as i had logging before and afer this call _queue.BeginReceive();//This is where it is failing - get a null reference exception } catch(Exception ex) { EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed + ex.InnerException.ToString() + _lineFeed + ex.Message.ToString()); } } where private MessageQueue _queue = null; This works on my machine but when deployed to a windows 2003 server and running as Network service account, it fails Exception recvd: Service cannot be started. System.NullReferenceException: Object reference not set to an instance of an object. at MYService.Service.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state) Solved: Turned out that the Q that i set up, I had to explicitly add Network Service account to it under security tab

    Read the article

  • How can i use ClearCanvas in remote database?

    - by programmerist
    How can i get data from REMOTE database using OnStart method? protected override int OnStart(StudyLoaderArgs studyLoaderArgs) { ApplicationEntity ae = studyLoaderArgs.Server as ApplicationEntity; _ae = ae; EventResult result = EventResult.Success; AuditedInstances loadedInstances = new AuditedInstances(); try { XmlDocument doc = RetrieveHeaderXml(studyLoaderArgs); StudyXml studyXml = new StudyXml(); studyXml.SetMemento(doc); _instances = GetInstances(studyXml).GetEnumerator(); loadedInstances.AddInstance(studyXml.PatientId, studyXml.PatientsName, studyXml.StudyInstanceUid); return studyXml.NumberOfStudyRelatedInstances; } finally { AuditHelper.LogOpenStudies(new string[] { ae.AETitle }, loadedInstances, EventSource.CurrentUser, result); } } i need to use OnStart in main project. How cn i use or call OnStart method

    Read the article

  • .NET: How to pass value when subscribing to event and obtain it when the event is triggered (Dynamic

    - by Entrase
    The task is to create event handlers in runtime. I need the one method to be called with different parameter value for different events. The events and their number are only known in runtime. So I'm trying to generate dynamic methods, each of which will be assigned to some event, but in general they all just pass some value to an instance method and call it. It would be great if something similar could be done the easier way. I mean passing some value at subscribing stage and then obtaining it when the event is triggered. This is what I'm trying to do now: public class EventSource { public event EventHandler eventOne; public event EventHandler eventTwO; public event EventHandler eventThree; } public class EventListener { SubscribeForEvents() { BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance; // Suppose we've already got EventInfo // and target source somewhere // so we can do eventInfo.AddEventHandler(target, delegate) // Now we need a delegate. int value = 42; Type tDelegate = eventInfo.EventHandlerType; // http://msdn.microsoft.com/en-us/library/ms228976(VS.95).aspx Type returnType = GetDelegateReturnType(tDelegate); DynamicMethod listener = new DynamicMethod("", null, GetDelegateParameterTypes(tDelegate), this.GetType()); ///////// Type[] callParameters = { typeof(int) }; MethodInfo method = this.GetType().GetMethod("ToCallFromDelegate", flags); ILGenerator generator = listener.GetILGenerator(); // No success in this mess. What's wrong? generator.Emit(OpCodes.Ldc_I4, value); generator.Emit(OpCodes.Call, method); generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ret); ///////////// Delegate delegate = listener.CreateDelegate(tDelegate); eventInfo.AddEventHandler(target, delegate); // When triggered, there is InvalidProgramException } void ToCallFromDelegate(int value) { doSomething(); } }

    Read the article

  • data is not inserting in my db table [closed]

    - by Sarojit Chakraborty
    Please see my below(SubjectDetailsDao.java) code of addZoneToDb method. My debugger is nicely running upto ** session.getTransaction().commit();** code. but after that debugger stops,I do not know why it stops after that line? .And because of this i am unable to insert my data into my database table. I don't know what to do.Why it is not inserting my data into my database table? Plz help me for this. H Now i am getting this Error: Struts Problem Report Struts has detected an unhandled exception: Messages: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; File: org/hibernate/validator/event/ValidateEventListener.java Line number: 172 Stacktraces java.lang.reflect.InvocationTargetException sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) java.lang.Thread.run(Thread.java:722) java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172) org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:156) org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:49) org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) v.esoft.dao.SubjectdetailsDAO.SubjectdetailsDAO.addZoneToDb(SubjectdetailsDAO.java:185) v.esoft.actions.LoginAction.datatobeinsert(LoginAction.java:53) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) ............................... ............................... SubjectDetailsDao.java(I have problem in addZoneToDb) package v.esoft.dao.SubjectdetailsDAO; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import com.opensymphony.xwork2.ActionSupport; import v.esoft.connection.HibernateUtil; import v.esoft.pojos.Subjectdetails; public class SubjectdetailsDAO extends ActionSupport { private static Session session = null; private static SessionFactory sessionFactory = null; static Transaction transaction = null; private String currentDate; SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); private java.util.Date currentdate; public SubjectdetailsDAO() { sessionFactory = HibernateUtil.getSessionFactory(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); currentdate = new java.util.Date(); currentDate = formatter.format(currentdate); } public List getAllCustomTempleteRoutinesForGrid() { List list = new ArrayList(); try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).addOrder(Order.desc("subjectId")).list(); } catch (Exception e) { System.out.println("Exepetion in getAllCustomTempleteRoutines" + e); } finally { try { // HibernateUtil.shutdown(); } catch (Exception e) { System.out.println("Exception In getExerciseListByLoginId Resource closing :" + e); } } return list; } //**showing list on grid private static List<Subjectdetails> custLst=new ArrayList<Subjectdetails>(); static int total=50; static { SubjectdetailsDAO cts = new SubjectdetailsDAO(); Iterator iterator1 = cts.getAllCustomTempleteRoutinesForGrid().iterator(); while (iterator1.hasNext()) { Subjectdetails get = (Subjectdetails) iterator1.next(); custLst.add(get); } } /****************************************update Routines List by WorkId************************************/ public int updatesub(Subjectdetails s) { int updated = 0; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Query query = session.createQuery("UPDATE Subjectdetails set subjectName = :routineName1 WHERE subjectId=:workoutId1"); query.setString("routineName1", s.getSubjectName()); query.setInteger("workoutId1", s.getSubjectId()); updated = query.executeUpdate(); if (updated != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return updated; } /****************************************update Routines List by WorkId************************************/ public int addSubjectt(Subjectdetails s) { int inserted = 0; Subjectdetails ss=new Subjectdetails(); try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); ss. setSubjectName(s.getSubjectName()); session.save(ss); System.out.println("Successfully data insert in database"); inserted++; if (inserted != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return inserted; } /******************************************Get all Routines List by LoginID************************************/ public List getSubjects() { List list = null; try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).list(); } catch (Exception e) { System.out.println("Exception in getRoutineList() :" + e); } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In getUserList Resource closing :" + e); } } return list; } //---\ public int addZoneToDb(String countryName, Integer loginId) { int inserted = 0; try { System.out.println("---------1--------"); Session session = HibernateUtil.getSessionFactory().openSession(); System.out.println("---------2------session--"+session); session.beginTransaction(); Subjectdetails country = new Subjectdetails(countryName, loginId, currentdate, loginId, currentdate); System.out.println("---------2------country--"+country); session.save(country); System.out.println("-------after save--"); inserted++; session.getTransaction().commit(); System.out.println("-------after commits--"); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { } } } finally { try { } catch (Exception e) { } } return inserted; } //-- public int nextId() { return total++; } public List<Subjectdetails> buildList() { return custLst; } public static int count() { return custLst.size(); } public static List<Subjectdetails> find(int o,int q) { return custLst.subList(o, q); } public void save(Subjectdetails c) { custLst.add(c); } public static Subjectdetails findById(Integer id) { try { for(Subjectdetails c:custLst) { if(c.getSubjectId()==id) { return c; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void update(Subjectdetails c) { for(Subjectdetails x:custLst) { if(x.getSubjectId()==c.getSubjectId()) { x.setSubjectName(c.getSubjectName()); } } } public void delete(Subjectdetails c) { custLst.remove(c); } public static List<Subjectdetails> findNotById(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()!=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findLesserAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()<=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findGreaterAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()>=id) { temp.add(c); } } return temp; } } Subjectdetails.hbm.xml <hibernate-mapping> <class name="vb.sofware.pojos.Subjectdetails" table="subjectdetails" catalog="vbsoftware"> <id name="subjectId" type="int"> <column name="subject_id" /> <generator class="increment"/> </id> <property name="subjectName" type="string"> <column name="subject_name" length="150" /> </property> <property name="createrId" type="java.lang.Integer"> <column name="creater_id" /> </property> <property name="createdDate" type="timestamp"> <column name="created_date" length="19" /> </property> <property name="updateId" type="java.lang.Integer"> <column name="update_id" /> </property> <property name="updatedDate" type="timestamp"> <column name="updated_date" length="19" /> </property> </class> </hibernate-mapping> My POJO - Subjectdetails.java package v.esoft.pojos; // Generated Oct 6, 2012 1:58:21 PM by Hibernate Tools 3.4.0.CR1 import java.util.Date; /** * Subjectdetails generated by hbm2java */ public class Subjectdetails implements java.io.Serializable { private int subjectId; private String subjectName; private Integer createrId; private Date createdDate; private Integer updateId; private Date updatedDate; public Subjectdetails( String subjectName) { //this.subjectId = subjectId; this.subjectName = subjectName; } public Subjectdetails() { } public Subjectdetails(int subjectId) { this.subjectId = subjectId; } public Subjectdetails(int subjectId, String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectId = subjectId; this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public Subjectdetails( String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public int getSubjectId() { return this.subjectId; } public void setSubjectId(int subjectId) { this.subjectId = subjectId; } public String getSubjectName() { return this.subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Integer getCreaterId() { return this.createrId; } public void setCreaterId(Integer createrId) { this.createrId = createrId; } public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Integer getUpdateId() { return this.updateId; } public void setUpdateId(Integer updateId) { this.updateId = updateId; } public Date getUpdatedDate() { return this.updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } } And my Sql query is CREATE TABLE IF NOT EXISTS `subjectdetails` ( `subject_id` int(3) NOT NULL, `subject_name` varchar(150) DEFAULT NULL, `creater_id` int(5) DEFAULT NULL, `created_date` datetime DEFAULT NULL, `update_id` int(5) DEFAULT NULL, `updated_date` datetime DEFAULT NULL, PRIMARY KEY (`subject_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    Read the article

  • WebSocket and Java EE 7 - Getting Ready for JSR 356 (TOTD #181)

    - by arungupta
    WebSocket is developed as part of HTML 5 specification and provides a bi-directional, full-duplex communication channel over a single TCP socket. It provides dramatic improvement over the traditional approaches of Polling, Long-Polling, and Streaming for two-way communication. There is no latency from establishing new TCP connections for each HTTP message. There is a WebSocket API and the WebSocket Protocol. The Protocol defines "handshake" and "framing". The handshake defines how a normal HTTP connection can be upgraded to a WebSocket connection. The framing defines wire format of the message. The design philosophy is to keep the framing minimum to avoid the overhead. Both text and binary data can be sent using the API. WebSocket may look like a competing technology to Server-Sent Events (SSE), but they are not. Here are the key differences: WebSocket can send and receive data from a client. A typical example of WebSocket is a two-player game or a chat application. Server-Sent Events can only push data data to the client. A typical example of SSE is stock ticker or news feed. With SSE, XMLHttpRequest can be used to send data to the server. For server-only updates, WebSockets has an extra overhead and programming can be unecessarily complex. SSE provides a simple and easy-to-use model that is much better suited. SSEs are sent over traditional HTTP and so no modification is required on the server-side. WebSocket require servers that understand the protocol. SSE have several features that are missing from WebSocket such as automatic reconnection, event IDs, and the ability to send arbitrary events. The client automatically tries to reconnect if the connection is closed. The default wait before trying to reconnect is 3 seconds and can be configured by including "retry: XXXX\n" header where XXXX is the milliseconds to wait before trying to reconnect. Event stream can include a unique event identifier. This allows the server to determine which events need to be fired to each client in case the connection is dropped in between. The data can span multiple lines and can be of any text format as long as EventSource message handler can process it. WebSockets provide true real-time updates, SSE can be configured to provide close to real-time by setting appropriate timeouts. OK, so all excited about WebSocket ? Want to convert your POJOs into WebSockets endpoint ? websocket-sdk and GlassFish 4.0 is here to help! The complete source code shown in this project can be downloaded here. On the server-side, the WebSocket SDK converts a POJO into a WebSocket endpoint using simple annotations. Here is how a WebSocket endpoint will look like: @WebSocket(path="/echo")public class EchoBean { @WebSocketMessage public String echo(String message) { return message + " (from your server)"; }} In this code "@WebSocket" is a class-level annotation that declares a POJO to accept WebSocket messages. The path at which the messages are accepted is specified in this annotation. "@WebSocketMessage" indicates the Java method that is invoked when the endpoint receives a message. This method implementation echoes the received message concatenated with an additional string. The client-side HTML page looks like <div style="text-align: center;"> <form action=""> <input onclick="send_echo()" value="Press me" type="button"> <input id="textID" name="message" value="Hello WebSocket!" type="text"><br> </form></div><div id="output"></div> WebSocket allows a full-duplex communication. So the client, a browser in this case, can send a message to a server, a WebSocket endpoint in this case. And the server can send a message to the client at the same time. This is unlike HTTP which follows a "request" followed by a "response". In this code, the "send_echo" method in the JavaScript is invoked on the button click. There is also a <div> placeholder to display the response from the WebSocket endpoint. The JavaScript looks like: <script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8080/websockets/echo"; var websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; function init() { output = document.getElementById("output"); } function send_echo() { websocket.send(textID.value); writeToScreen("SENT: " + textID.value); } function onOpen(evt) { writeToScreen("CONNECTED"); } function onMessage(evt) { writeToScreen("RECEIVED: " + evt.data); } function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false);</script> In this code The URI to connect to on the server side is of the format ws://<HOST>:<PORT>/websockets/<PATH> "ws" is a new URI scheme introduced by the WebSocket protocol. <PATH> is the path on the endpoint where the WebSocket messages are accepted. In our case, it is ws://localhost:8080/websockets/echo WEBSOCKET_SDK-1 will ensure that context root is included in the URI as well. WebSocket is created as a global object so that the connection is created only once. This object establishes a connection with the given host, port and the path at which the endpoint is listening. The WebSocket API defines several callbacks that can be registered on specific events. The "onopen", "onmessage", and "onerror" callbacks are registered in this case. The callbacks print a message on the browser indicating which one is called and additionally also prints the data sent/received. On the button click, the WebSocket object is used to transmit text data to the endpoint. Binary data can be sent as one blob or using buffering. The HTTP request headers sent for the WebSocket call are: GET ws://localhost:8080/websockets/echo HTTP/1.1Origin: http://localhost:8080Connection: UpgradeSec-WebSocket-Extensions: x-webkit-deflate-frameHost: localhost:8080Sec-WebSocket-Key: mDbnYkAUi0b5Rnal9/cMvQ==Upgrade: websocketSec-WebSocket-Version: 13 And the response headers received are Connection:UpgradeSec-WebSocket-Accept:q4nmgFl/lEtU2ocyKZ64dtQvx10=Upgrade:websocket(Challenge Response):00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 The headers are shown in Chrome as shown below: The complete source code shown in this project can be downloaded here. The builds from websocket-sdk are integrated in GlassFish 4.0 builds. Would you like to live on the bleeding edge ? Then follow the instructions below to check out the workspace and install the latest SDK: Check out the source code svn checkout https://svn.java.net/svn/websocket-sdk~source-code-repository Build and install the trunk in your local repository as: mvn install Copy "./bundles/websocket-osgi/target/websocket-osgi-0.3-SNAPSHOT.jar" to "glassfish3/glassfish/modules/websocket-osgi.jar" in your GlassFish 4 latest promoted build. Notice, you need to overwrite the JAR file. Anybody interested in building a cool application using WebSocket and get it running on GlassFish ? :-) This work will also feed into JSR 356 - Java API for WebSocket. On a lighter side, there seems to be less agreement on the name. Here are some of the options that are prevalent: WebSocket (W3C API, the URL is www.w3.org/TR/websockets though) Web Socket (HTML5 Demos - html5demos.com/web-socket) Websocket (Jenkins Plugin - wiki.jenkins-ci.org/display/JENKINS/Websocket%2BPlugin) WebSockets (Used by Mozilla - developer.mozilla.org/en/WebSockets, but use WebSocket as well) Web sockets (HTML5 Working Group - www.whatwg.org/specs/web-apps/current-work/multipage/network.html) Web Sockets (Chrome Blog - blog.chromium.org/2009/12/web-sockets-now-available-in-google.html) I prefer "WebSocket" as that seems to be most common usage and used by the W3C API as well. What do you use ?

    Read the article

1