Tuesday

JavaScript Cookies example

If you want to run your ajax or other code blocks once a day(or any other), you can use cookies.

In the below, we created cookie that would expire at midnight (timezone issues could be).
If cookie isn't there or has expired we run ajax else we do nothing.

Also you can see the cookie details from developer tools >> application >> cookies >> your adress (for chrome 61)

$(document).ready(function() {
       var myCookie = getCookie("MY_cookieName");  

       if(myCookie == "")  {   //cookie is not created or has expired
             $.ajax({
                //Do your job
             });
           var createdTime = new Date().toString();
           setCookieExpireAtMidnight("MY_cookieName", createdTime);
       }
});

function getCookie(cname) {
       var name = cname + "=";
       var ca = document.cookie.split(';');
       for(var i = 0; i < ca.length; i++) {
             var c = ca[i];
             while (c.charAt(0) == ' ') {
                    c = c.substring(1);
             }
             if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
             }
       }
       return "";
}

function setCookieExpireAtMidnight(cname, value) {
       var midnight = new Date();
       midnight.setHours(23,59,59,0);
       var expires = "expires=" + midnight.toString();
       document.cookie = cname + "=" + value + ";" + expires + "; path=/";
}

Thursday

javax.websocket example

I will show an example of Web Socket. I'll use a Javascript WebSocket API  to reconnect periodically to the server.

Server Side:
1. WebSocketDecoder.java
import java.io.IOException;
import java.io.Reader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

public class WebSocketDecoder implements Decoder.TextStream<JsonObject> {

        @Override
        public void init(EndpointConfig config) {}

        @Override
        public void destroy() {}

       @Override
       public JsonObject decode(Reader reader) throws DecodeException, IOException {
         try (JsonReader jReader = Json.createReader(reader)) {
               return jReader.readObject();
        }
       }

}

2. WebSocketEncoder.java

import java.io.IOException;
import java.io.Writer;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class WebSocketEncoder implements Encoder.TextStream<JsonObject> {

    @Override
    public void init(EndpointConfig config) {}

    @Override
    public void encode(JsonObject jsonLoad, Writer writer) throws EncodeException, IOException {
        try (JsonWriter jsonWriter = Json.createWriter(writer)) {
            jsonWriter.writeObject(jsonLoad);
        }
    }

    @Override
    public void destroy() {}
}

3. WebSocket.java
import java.io.IOException;
import java.util.HashMap;

import javax.faces.bean.ApplicationScoped;
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ApplicationScoped
@ServerEndpoint(value = "/ltmc/{username}", encoders = {WebSocketEncoder.class}, decoders = {WebSocketDecoder.class})
public class WebSocket {

    private static HashMap<String, Session> users = new HashMap<>();

    @OnOpen
    public void onOpen(Session session,  @PathParam("username") String username) {
       users.put(username, session);
    }

    @OnClose
    public void onClose(Session client) {
       users.remove(client);
    }

    //If the client send a message, you can procces it in this method.
    @OnMessage
    public void onMessage(JsonObject request, Session client) {
       //We're sending client message, to the client again.
       client.getBasicRemote().sendObject(request);
    }

    @OnError
    public void onError(Session client, Throwable t) {
       //log the error detail
    }

    //You can call this method from other classes.
    //It will send a json object message to the client. The message will be caught from 'onmessage' method on client in notification.socket.js
    public void sendNotification(String username) throws IOException, EncodeException {
       Session client = users.get(username);

       if(client != null && client.isOpen()) {
           JsonObject event = Json.createObjectBuilder()
                    .add("user","Less Talk More Code")
                    .build();
           client.getBasicRemote().sendObject(event);
           
       } else {
             //log that user can't find
       }
    }
}

Client Side:
1. reconnect.web.socket.js >> you can download from   https://github.com/joewalnes/reconnecting-websocket

2. notification.socket.js
var webSocket;

function initNotificationSocket(){
       var wsUri = url;
       websocket = new ReconnectingWebSocket(wsUri, null, {debug: true, reconnectInterval: 3000});
       websocket.onmessage = function(event) {
             onMessage(event);
       };
       //We're sending message to the server. 
       //This message will be caught in the onmessage method - WebSocket.java
       websocket.send(JSON.stringify({"user":"hello"}));
}

function onMessage(event) {
       var msg = JSON.parse(event.data);
       alert(msg.user );
}

initNotificationSocket();

3. add following codes to your .jsp file.
<script type="text/javascript">
     var url = "ws://" + "server side address:port" + "/ltmc/" + "your dynamic username";
</script>
       
<script type="text/javascript" src="js/reconnect.web.socket.js"></script>
<script type="text/javascript" src="js/notification.socket.js"></script>

Monday

Web push notification example - with notify.js plugin

I will show an example of web push notification by using notify.js (https://notifyjs.com/) plugin and styling it.

- jquery-1.11.2.js >>You can download from:  https://code.jquery.com/jquery-1.11.2.js

- bootstrap.min.css >> For button styling we'll use, but you don't have to add this. You can download it from: https://getbootstrap.com/docs/3.3/getting-started/

- notify.js  >>go to 'https://notifyjs.com/' >> 'Download notify.js' section

- notify.min.js >>go to 'https://notifyjs.com/' >> 'Download notify.min.js' section

- notify.custom.js will be written by us, we'll add our styling and function.
$.notify
.addStyle("info", {
   html:
     "<div class='clearfix'>"
        +"<div class='pull-left notifyjs-icon' style='float:left'></div>"
          +"<div class='notifyjs-title pull-left' data-notify-html='title'/>"
             + "<button id='yesInfo' class='btn btn-success btn-sm notifyjs-btn' data-notify-text='button'>OKE</button>"
     +"</div>",
});


$(document).on('click', '#yes', function () {
    $(this).trigger('notify-hide');
});

function notify(msg) {
       $.notify({
           title: msg
       }, {
           style: 'info'
       });
}

- test.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Give your title</title>
</head>

<body>
       <link rel="stylesheet" href="js/bootstrap.min.css">
       <script type="text/javascript" src="js/jquery-1.11.2.js"></script>
       <script type="text/javascript" src="js/notify.js"></script>
       <script type="text/javascript" src="js/notify.custom.js"></script>
       <script>
             notify('<h4>Hello</h4>You can see our notification. Click to <b>OKE</b> button to close notification.');
       </script>
</body>
</html>

-notify.style.css
.notifyjs-icon{width:140px;height:150px; background:url(../../your img path) no-repeat 50% #3A423A}
.notifyjs-title h4{font-weight:normal;color:#3A423A}
.notifyjs-title b{color:#3A423A}
.notifyjs-title{width:290px;color:#333;padding: 0 5px 4px 10px}
.notifyjs-info-base{width:450px;display:inline-block;padding:10px;position:relative;background-color:#F0F8FF;autoHide:false;clickToHide:false}

.notifyjs-btn{position:absolute! important;bottom:20px;right:20px;}

Output: