Monday, December 14, 2015

Applying css styles in JavaFx dynamically

We can apply the styles from a css file easily, which are fixed values defined in css, to any element in JavaFx directly by calling getStyleSheets() or getStyleClass().However, think of a scenario where the colours and styles are to be applied dynamically based on the unknown number of choices made available to the user. In this scenario, creating a separate style (or style class) per colour (or style) is practically not possible. However, here is an approach to apply dynamic styles.

With that being said, if you have any other method, I request you to share it and help others to learn more.

Source Code:


public class CssDemo extends Application {
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) {
		primaryStage.setTitle("Hello World!");
		final Button btn = new Button();
		btn.setText("Say 'Hello World'");
		btn.setOnAction(new EventHandler() {
			@Override
			public void handle(ActionEvent event) {
				try {
					String prefix = "background_";
					String suffix = ".css";

					// this temporary file remains after the jvm exits
					File tempFile = File.createTempFile(prefix, suffix);
					// to delete the files created in temp after the application closes
					// deletion happens only if the application exits properly
					tempFile.deleteOnExit();

					String cssContent = ".intro {   -fx-background-color: rgb("
							+ 67 + "," + 98 + "," + 288 + ")}";
					BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
					bw.write(cssContent);
					bw.close();

					String filename = tempFile.getPath();
					btn.getStylesheets().add("file:///" + filename);
					btn.getStyleClass().add("intro");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		StackPane root = new StackPane();
		root.getChildren().add(btn);
		primaryStage.setScene(new Scene(root, 300, 250));
		primaryStage.show();
	}
}

       
 

Including a screenshot of the source code just to make sure it is clear to understand.
 Happy Coding.


Sunday, October 4, 2015

Palindrome Java Code made short

I was asked by a friend to explain a palindrome program in java and I wanted to make it work for both integers and strings. In addition, wanted to make it short and understandable. Checking if a string is a palindrome or not is simple when compared to an integer palindrome. With a string, we can compare the first character with last character, second character with last but one character and so on. In java, we can convert an integer to string using Integer.toString().

In the below we have two methods, with the same name but different types of parameters passed. If an integer is passed parameter, it is converted to string and the same is passed to the method with string argument. Here it is checked if it is a palindrome by checking if it is like a mirror image, with mirror in the middle of the string. If yes, 1 is returned else, -1 is returned. The same value returned by string method is again returned by the integer method.

/**
 * Created by Naveen Kumar on 9/30/2015.
 */
public class PalindromeDemo {
 
public static void main(String args[]){
   PalindromeDemo pd =
new PalindromeDemo();
   
System.out.println((pd.palindromeCheck(343)==1)?"Palindrome":"Not Palindrome");
   
System.out.println((pd.palindromeCheck(3432)==1)?"Palindrome":"Not Palindrome");
   
System.out.println((pd.palindromeCheck("madam")==1)?"Palindrome":"Not Palindrome");
   
System.out.println((pd.palindromeCheck("abcd")==1)?"Palindrome":"Not Palindrome");
  
}

   
public int palindromeCheck(int n){
       
return (new PalindromeDemo()).palindromeCheck(Integer.toString(n));
   
}

   
public int palindromeCheck(String str){
       
for(int i=0;i<(str.length())/2;i++){
            
if(str.charAt(i)!=str.charAt(str.length()-i-1))
               
return -1;
       
}
       
return 1;
   
}
}


Any comments or updates are welcome :)

Happy Coding.

Saturday, February 22, 2014

UNIX Shell Scripting Leap Year

I found the following algorithm on Leap Years.

In your favorite editor (like gedit), type in the following code.

Code: (leap_year.sh)
----------------------
echo "Enter a year : "
read y

if [ $(( $y % 4 )) -eq 0 -a $(( $y % 100 )) -ne 0 -o $(( $y % 400 )) -eq 0 ]
then
echo "$y is a leap year"
else
echo "$y is not a leap year"
fi

Execution:
----------
1. Open Terminal
2. Navigate to the directory containing the above script
3. bash leap_year.sh
or you can also do  ./leap_year.sh provided you got execute permissions for the script.

Happy Coding.

JQuery, PHP, JSON

This post is mostly the same as the previous one which is about JQuery, PHP and JSON. But the difference is, in the previous post, only rendering is done not validation of answers. Now, I have included the validation part also. Once the user is done answering and clicks submit button, answers are checked with correct answers and final result is displayed as an alert. Same as previous post, the PHP file, which is supposed to get data from database and convert it into json format and echo the result, just echos a string which is a collection of questions in json format.

index.html
----------
<html>
<head>
<script src="jquery-1.10.2.js"></script>
<script src="jquery_functions4.js"></script>
</head>
<body>
<p> Its working fine </p>
<table align='center' border='1' id='results'> </table>
<div id='test'> </div>
</body>
</html>

get_qp.php
------------
<?php
echo ' {"question_paper":
 [
{
"qid": "1",
"question": "Who is the father of computer?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "a"
},
{
"qid": "2",
"question": "Who is the father of Java?",
"opt1": "Charless Babbage",
"opt2": "James Gauslin",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "b"
},
{
"qid": "3",
"question": "Who designed C Language?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Dennis Ritchie",
"opt4": "Robin Hood",
"answer": "c"
}
]
 }';

?>

jquery_functions4.js
--------------------
$(document).ready(function()
{
var answers = new Array();
var qids = new Array();
var user_response = new Array();
var i = 0;
var res = 0;
var div_data="";

$.getJSON("get_qp.php",function(data)
{
$.each(data.question_paper,function(i,qp)
{
div_data+="<tr>"
div_data+="<td>"+qp.qid+"</td>";
div_data+="<td colspan='4'>"+qp.question+"</td>";
div_data+="</tr>";
div_data+="<tr>";
div_data+="<td></td>";
div_data+="<td><input type='radio' id='"+qp.qid+"' name = "+qp.qid+" value='a'/>"+qp.opt1+"</td>";
div_data+="<td><input type='radio' id='"+qp.qid+"' name = "+qp.qid+" value='b'/>"+qp.opt2+"</td>";
div_data+="<td><input type='radio' id='"+qp.qid+"' name = "+qp.qid+" value='c'/>"+qp.opt3+"</td>";
div_data+="<td><input type='radio' id='"+qp.qid+"' name = "+qp.qid+" value='d'/>"+qp.opt4+"</td>";
div_data+="</tr>";

qids[i] = qp.qid;
answers[i++] = qp.answer;
});

div_data+="<tr><td colspan='5' align='center'><input type='submit' value='SUBMIT' id='submit_button'/></td></tr>";
$("#results").html(div_data);

$("#submit_button").click(function()
{
$("#results").hide();
res = 0;
for(var i=0;i<3;i++)
{
user_response[i] = $("input:radio[name="+qids[i]+"]:checked").val();
if(user_response[i] == answers[i])
res++;
}
alert("Your Score:"+res);
});
});
});

jquery-1.10.2.js can be downloaded online. It is JQuery API.
All the files are present in the same folder which is under c:\wamp\www\. For example, my project name is json_testing so I have saved these files under c:\wamp\www\json_testing\

Hope this helps. Happy Coding. 

Saturday, February 8, 2014

JQuery PHP & JSON

First, the JQuery function requests the PHP file for the data to be sent.
The server side code in PHP, requests the database for the data and gets the data.
Converts the received data into JSON format and sends it to the client side.
On the client side, JQuery (java script) receives the data in JSON format, extracts the required information, processes accordingly and displays in a table format.

Here in this example, the database connectivity is not included, rather, a JSON format is generated which is a question paper (objective type).

Client Side code: (index.html)
------------------
<html>
<head>
<script src="jquery/jquery-1.10.2.js"></script>
<script src="jquery_functions3.js"></script>
</head>
<body>
<p> Its working fine </p>
<table border='1' id="results"> </table>
</body>
</html>

Server Side code: (get_qp.php)
------------------
<?php
echo ' {"question_paper":
 [
{
"qid": "1",
"question": "Who is the father of computer?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "a"
},
{
"qid": "2",
"question": "Who is the father of Java?",
"opt1": "Charless Babbage",
"opt2": "James Gauslin",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "b"
},
{
"qid": "3",
"question": "Who designed C Language?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Dennis Ritchie",
"opt4": "Robin Hood",
"answer": "c"
}
]
 }
 ';

?>

JavaScript code (JQuery): (jquery_functions3.js)
--------------------------
$(document).ready(function()
{
   $.getJSON("get_qp.php",function(data)
   {
$.each(data.question_paper,function(i,qp)
{
var div_data = "<tr><td>"
+qp.qid+"</td><td colspan=4>"+qp.question+"</td></tr><tr><td></td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt1+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt2+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt3+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt4+"</td></tr>";

$("#results").append(div_data);
});
  });
});

Points to remember before proceeding with execution:
-----------------------------------------------------
1. I used WAMP for the above code.
2. JQuery API should be downloaded and included if you dont want to use an online API.
3. Make sure that you are running an updated version on Java.
4. All the above three files are to be present in the same folder. If you want to keep the js file separately, then make sure that you do required modification in the html file.

Happy Coding.

Output:


Tuesday, November 5, 2013

Distributed Computing, Connection Oriented Socket API

In my previous posts, I shared about connection less communication with socket API. This post is about connection oriented communication with socket API.
In the case of connection less communication, the packets are received at the receiver at random. Which means, if you consider packets received consecutively, the collection may contain packets in a random order and may be from many senders.
Connection oriented communication is also called Stream-mode communication where the packets are written to the stream by a sender and the receiver reads these packets from the stream.
In java, to implement Connection Oriented socket communication, two classes are used
1. ServerSocket (to establish and maintain the connection)
2. Socket (for data exchange)

Demo1:
The following program demonstrates a basic Connection Oriented communication between two processes, ConnectionAcceptor and ConnectionRequestor, running on two different hosts. ConnectionAcceptor process accepts a connection from ConnectionRequestor process and sends back a response provided in the command line arguments. ConnectionRequestor process sends a connection request to the ConnectionRequestor process, gets a response and prints the received response.

Code (ConnectionAcceptor):
import java.net.*;
import java.io.*;

/* 
*   ****** CONNECTION ORIENTED SOCKET PROGRAMMING *****
*   Author : @NaveenKumar
*   Program : Connection Acceptor (Server)
*   Date : 29/10/2013
*   File Name    : ConnectionAcceptor.java
*/

public class ConnectionAcceptor 
{
  public static void main(String args[])
  {
     if(args.length != 2)
     {
      System.out.println("Error in required no. of parameters");
     }// end of if
     else
     {
try{
int portNo = Integer.parseInt(args[0]);
String message = args[1];
ServerSocket connectionSocket = new 
                                 ServerSocket(portNo);
System.out.println("Waiting for connection");
Socket dataSocket = connectionSocket.accept();
System.out.println("Connection Accepted");
OutputStream outStream = 
                         dataSocket.getOutputStream();
PrintWriter socketOutput = new PrintWriter(new                            OutputStreamWriter(outStream));
socketOutput.println(message);
socketOutput.flush();
System.out.println("Message sent");
try{
    Thread.sleep(5000);
    System.out.println("Waiting time is over");
}catch(Exception e)
{
e.printStackTrace();
}
socketOutput.println(message);
socketOutput.flush();
dataSocket.close();
System.out.println("Data socket closed");
connectionSocket.close();
System.out.println("connection socket closed");
}catch(Exception ex){
ex.printStackTrace();
}//end of catch
   }//end of else
  }// end of main
}// end of class ConnectionAcceptor

Code (Connection Requestor):
import java.net.*;
import java.io.*;

/* 
*   ****** CONNECTION ORIENTED SOCKET PROGRAMMING *****
*   Author : @NaveenKumar
*   Program : Connection Requestor (client)
*   Date : 29/10/2013
*   File Name           : ConnectionRequestor.java
*/

public class ConnectionRequestor
{
  public static void main(String args[])
  {
    if(args.length != 2)
    {
System.out.println("Insufficient parameters");
    }// end of if
    else
    {
try{
InetAddress acceptorHost =InetAddress.getByName(args[0]);
int acceptorPort = Integer.parseInt(args[1]);
Socket mySocket = new Socket(acceptorHost, acceptorPort);
System.out.println("Connection request granted");
InputStream inStream = mySocket.getInputStream();
BufferedReader socketInput = new BufferedReader(new 
                           InputStreamReader(inStream));
System.out.println("waiting to read");
String message = socketInput.readLine();
System.out.println("Message received:\t"+message);
mySocket.close();
System.out.println("Data Socket closed");
       }catch(Exception ex){
ex.printStackTrace();
       }//end of catch
    }// end of else
  }// end of main
} // end of ConnectionRequestor

Executing Procedure:
1. Deploy the above programs in two different nodes which are connected on a network
2. Open terminal (command prompt) on both the nodes
3. navigate to the above java file locations
4. On terminal 1, javac ConnectionAcceptor.java (press enter),
                          java ConnectionAcceptor 3000  hai (press enter)
5. On the other terminal, javac ConnectionRequestor.java (press enter)
                                      java ConnectionRequestor 192.168.10.1 3000 (press enter)
192.168.10.1 is the IP address of the node that is running the ConnectionAcceptor process and 3000 is the port number on which it is listening.

'hai' is the response send back to the ConnectionRequestor process by ConnectorAcceptor process.

Demo 2:
Now, a modified version of the above ConnectionAcceptor is as follows. The modification provided is that, instead of accepting one single connection, it can accept multiple connections. The ConnectionAcceptor process is not terminated.

for better understanding, the new ConnectionAcceptor is renamed as Server.

Code (Server):
import java.net.*;
import java.io.*;

/* 
*   ****** CONNECTION ORIENTED SOCKET PROGRAMMING *****
*  Author : @NaveenKumar
*  Program : Server
*  Date : 29/10/2013
*  File Name           : Server.java
*/

public class Server 
{
  public static void main(String args[])
  {
    if(args.length != 2)
    {
      System.out.println("Error in required no. of parameters");
    }// end of if
    else
    {
     try{
int portNo = Integer.parseInt(args[0]);
String message = args[1];

ServerSocket connectionSocket = new ServerSocket(portNo);
System.out.println("Waiting for connection");
int i,j;
i = j = 1;
while(i==j)
{
  Socket dataSocket = connectionSocket.accept();
  System.out.println("Connection Accepted");
  OutputStream outStream = dataSocket.getOutputStream();
  PrintWriter socketOutput = new PrintWriter(new 
                    OutputStreamWriter(outStream));
  socketOutput.println(message);
  socketOutput.flush();
  System.out.println("Message sent");
  try{
Thread.sleep(5000);
System.out.println("Waiting time is over");
  }catch(Exception e)
  {
e.printStackTrace();
  }
  socketOutput.println(message);
  socketOutput.flush();

  dataSocket.close();
  System.out.println("Data socket closed");
}
connectionSocket.close();
System.out.println("connection socket closed");
    }catch(Exception ex){
ex.printStackTrace();
    }//end of catch
  }//end of else
 }// end of main
}// end of class Server

Code (Client):
import java.net.*;
import java.io.*;

/* 
*   ****** CONNECTION ORIENTED SOCKET PROGRAMMING *****
*  Author : @NaveenKumar
*  Program : Client
*  Date : 29/10/2013
*  File Name           : Client.java
*/

public class Client
{
  public static void main(String args[])
    {
       if(args.length != 2)
   {
     System.out.println("Insufficient parameters");
   }// end of if
   else
   {
     try{
      InetAddress acceptorHost = InetAddress.getByName(args[0]);
      int acceptorPort = Integer.parseInt(args[1]);
      Socket mySocket = new Socket(acceptorHost, acceptorPort);
      System.out.println("Connection request granted");
      InputStream inStream = mySocket.getInputStream();
      BufferedReader socketInput = new BufferedReader(new 
                                  InputStreamReader(inStream));
      System.out.println("waiting to read");
     String message = socketInput.readLine();
     System.out.println("Message received:\t"+message);
     mySocket.close();
   System.out.println("Data Socket closed");
    }catch(Exception ex){
      ex.printStackTrace();
    }//end of catch
   }// end of else
  }// end of main
} // end of Client

Execution:
One Server process running on a host on a network, multiple Client processes running on multiple hosts on the network.
1. Deploy the above programs in different hosts which are connected on a network
2. Open terminal (command prompt) on both the nodes
3. navigate to the above java file locations
4. On terminal 1, javac Server.java (press enter),
                          java Server 3000  hai (press enter)
5. On the other terminals, javac Client.java (press enter)
                                      java Client 192.168.10.1 3000 (press enter)
192.168.10.1 and 3000 are the IP address and port number of the Server Process.

Try executing multiple clients simultaneously and observe the happenings.
If you dont have multiple hosts available, then for demonstration purpose, you can do execution on localhost itself as demonstrated in the class.


Wednesday, October 30, 2013

Distributed Computing, Socket API Prime Number identification from a list of numbers

In the previous example, we looked into a connection less java Socket API Program. Now, assume that there are 4 nodes in the distributed system and 100 numbers given as input are to be processed (for example, checking if a given number is a prime or not). Now we need a master node to accept this input and proceed with assigning of the work and again displaying the final output. For simplicity, I am giving input as the first 100 natural numbers.
The Setup is assumed to consist of one 5 nodes. One master and others as slaves.
Code: Master.java
import java.net.*;
import java.io.*;
/*
*   ************* SOCKET PROGRAMMING (Master) **************
*Author    : @NaveenKumar
*Program   :To print prime numbers in [1,100]
*Date      : 29/10/2013
*File Name : Master.java
*/
public class Master
{
     public static void main(String args[])
     {
           int num;
           try{
                InetAddress[] receiverHost = {
                             InetAddress.getByName("127.0.0.1"),
                             InetAddress.getByName("127.0.0.1"),
                             InetAddress.getByName("127.0.0.1"),
                             InetAddress.getByName("127.0.0.1")};
                int[] receiverPort = {3000,3010,3020,3030};
                String message;
             //instantiate a datagram socket for sending the data
                DatagramSocket s = new DatagramSocket();
                DatagramSocket s1 = new DatagramSocket(3500);
                byte[] buffer;
                for(int i=1;i<=100;i++)
                {
                     message = Integer.toString(i);
                     buffer = message.getBytes();
                     DatagramPacket p = new             
                     DatagramPacket(buffer,buffer.length,
                            receiverHost[i%4],receiverPort[i%4]);
                     s.send(p);
                }
                s.close();
                byte[] buffer1;
                String msg1;
                for(int i = 0;i<100 i="" o:p="">
                {
                     buffer1 = new byte[10];
                     DatagramPacket p1 = new DatagramPacket
                                                    (buffer1,10);
                     s1.receive(p1);
                     msg1 = new String(buffer1);
                     //num = Integer.parseInt(msg1);
                     if(msg1.charAt(0)!='-')
                           System.out.println("Received: "+msg1);
                }
                s1.close();
           }catch(Exception ex) 
           {
                ex.printStackTrace();
           }//end of catch
     }//end of main
}//end of class

In the above program for Master node,  a list of nodes in the network are provided with the port numbers of respective node on which they are listening. Once the processing of data is done on the other nodes, then the results are then processed on the Master node and displayed. If the number -1 is received from any slave, it is ignored but if a positive integer is received, then it is printed.

Code: Slave.java
import java.net.*;
import java.io.*;

/*
*   ******************** SOCKET PROGRAMMING (SLAVE) **************
*    Author          : @NaveenKumar
*    Date      : 29/10/2013
*    File Name       : Receiver.java
*/

public class Slave
{
     public static void main(String args[])
     {
           System.out.println("Starting Receiver");
           if(args.length!=1)
           {
                System.out.println("Invalid no. of args");
           }
           else{
           int receive_port = Integer.parseInt(args[0]);
           try
           {
                DatagramSocket s = new 
                                   DatagramSocket(receive_port);
                DatagramSocket soc = new DatagramSocket();
                System.out.println("Socket created");
                byte[] buffer = new byte[10];  
                System.out.println("buffer created");
                DatagramPacket p = new DatagramPacket(buffer,10);
                System.out.println("packet created");
                int i,j;
                i=10;
                j=10;
                String msg;
                Slave sl = new Slave();
                while(i==j)
                {
                     s.receive(p);
                     msg = new String(buffer);
                     // process the message
                     sl.process(msg,soc);
                }
                s.close();
           }catch(Exception ex) // end of try and start of catch
           {
                ex.printStackTrace();
           }// end of catch
      }//end of else
     }// end of main
    
     public Slave()
     {
          
     }
     public void process(String msg, DatagramSocket s1)
     {
           String msg1="";
           String msg2 = "";
           String message = msg;
           int res = -1;
           byte[] buffer;
           for(int k=0;k
           {
                if((int)message.charAt(k)<58 amp="" nbsp="" span="">
                                  (int)message.charAt(k)>47) 
                        msg2 += message.charAt(k);
                else 
                        break;
           }
           int num = Integer.parseInt(msg2);
           int temp = 0;
           for(int i=1;i
           {
                if(num%i == 0)
                           temp++;
                if(temp==2)
                     break;
           }
           if(temp==1)
                res = num;
           else
                res = -1;
           try{
                InetAddress receiverHost = 
                             InetAddress.getByName("127.0.0.1");
                int receiverPort = 3500;
                msg1 = Integer.toString(res);
                System.out.println("Msg: "+msg1);
                buffer = msg1.getBytes();
                DatagramPacket p1 = new DatagramPacket(buffer,
                       buffer.length,receiverHost,receiverPort);
                s1.send(p1);
           }catch(Exception ex)
           {
                ex.printStackTrace();
           }// end of catch
     }//end of process method
}// end of class Receiver


In the above code for Slave process, slave process waits for receiving a message from Master process. Once a number is received, it calls process() method with the received message as a parameter to this method. Here in this method, the received data is converted into integer and then checked if it is a prime number of not. If it is a prime number, the number itself is sent back to the Master. If it is not a prime number, then -1 is sent back.