Tuesday

JSTL format number

Add following taglib to your class:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<fmt:formatNumber value="${your double value}" maxFractionDigits="0"  groupingUsed="false" />
<!-- your value example :1500.0 then it will show 1500 ! -->
<!-- You can use it instead of <c:out /> which doesn’t have so much control for formatting -->

Why is SimpleDateFormat changing given date?

//The upper case Y is "week year". It has 364 or 371 days 
//The lower case y has usual 365 or 366.
//So they give different outputs:
//Locale.forLanguageTag("tr_TR") >> comes with Java 7

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class Test {

    public static void main(String[] args) {
       try {
           String dateString = new java.util.Date().toString();
           System.out.println(dateString);

           SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.forLanguageTag("tr_TR"));
           Date date = format.parse(dateString);
           System.out.println(date.toString());

           SimpleDateFormat format2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY", Locale.forLanguageTag("tr_TR"));
           Date date2 = format2.parse(dateString);
           System.out.println(date2.toString());

       } catch (ParseException e) {
           //log
       }
    }
    
}
Output:

Mon May 14 10:31:14 EEST 2018
Mon May 14 10:31:14 EEST 2018
Mon Jan 01 09:31:14 EET 2018

Friday

f:selectItems => adding tooltip

Put pass-through into to the namespace.
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"

You can use passthrough 'title' attribute:
<f:selectItems value="#{values}" pt:title="Your tooltip desc"/>

Execute two methods in action

You can use f:actionListener to execute 2 methods in action:
<a4j:commandbutton action="{method1()}" value="deneme" >                              
   <f:actionlistener binding="#{method2()}"/>
<a4j:commandbutton>

Sort list of strings by using Localization

import java.text.Collator;

List<String> yourValues = …;
Collections.sort(yourValues, Collator.getInstance(Locale.forLanguageTag("your locale ")));

See Collator interface.

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:

Thursday

SOAPUI : java.lang.Exception: Failed to load url

BUG:
When i try to import the WSDL in SoapUI-5.2.1, i got an error.
Detailed error log in C:\Program Files\SmartBear\SoapUI-5.2.1\bin\error.log is below:

java.lang.Exception: Failed to load url; https://10.xxx.xxx.xxx:xxxx/../../..?wsdl, 0 -
                at com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:171)
                at com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader.readCleanWsdlFrom(WsdlLoader.java:123)
                at com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader.loadXmlObject(WsdlLoader.java:101)
                at com.eviware.soapui.impl.wsdl.support.xsd.SchemaUtils.getDefinitionParts(SchemaUtils.java:488)
                at com.eviware.soapui.impl.wsdl.support.xsd.SchemaUtils.getDefinitionParts(SchemaUtils.java:477)
                at com.eviware.soapui.impl.support.definition.support.AbstractDefinitionCache.update(AbstractDefinitionCache.java:94)
                at com.eviware.soapui.impl.support.definition.support.AbstractDefinitionContext$Loader.construct(AbstractDefinitionContext.java:209)
                at com.eviware.soapui.support.swing.SwingWorkerDelegator.construct(SwingWorkerDelegator.java:46)
                at com.eviware.soapui.support.swing.SwingWorker$2.run(SwingWorker.java:131)
                at java.lang.Thread.run(Unknown Source)

Also when i open the url in the browser, i see the following certificate error which says that the connection uses TLS 1.2.

























FIX:
It means that the service has configured only for TLS1.2 and SSL has not allowed.
You should add the following parameter to the SOAPUI vmoptions file (C:\Program Files\SmartBear\SoapUI-5.2.1\bin\SoapUI-5.2.1.vmoptions) and restart SOAPUI.

-Dsoapui.https.protocols=TLSv1.2,SSLv3

Tuesday

Clearcase unable to contact albd_server on host 'remote server'

BUG:
I got following error when i attempt to open/start view.
  • clearcase unable to contact albd_server on host 
FIX:
Open Clearcase properties as following:
  • Windows Start >> Run  >> type  cc.cpl >> Service Startup tab
  • You will see "Status of the ALBD Service" as Stopped. Then click "Start Clearcase".