Monday 14 December 2015

How to Convert Enumeration to Arraylist - Java Example

We can convert enumeration to arraylist in java with  the help list() method of Collections.

package javaproficeincy;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

public class EnumerationToList {
public static void main(String[] args) {
Vector<String> vt = new Vector<String>();
        vt.add("java");
        vt.add("php");
        vt.add("array");
        vt.add("string");
        vt.add("c");
        Enumeration<String> enm = vt.elements();
        List<String> ll = Collections.list(enm);
        System.out.println("List elements: "+ll);
}

}


Output:

List elements: [java, php, array, string, c]

Related Posts :


Monday 7 December 2015

How to Send message from one user to other ( chat example) In xmpp

We have knew how to add roster in xmpp server . Now we will send message from one user to other.
There is simple example for creating chat. There we will send a message using smack api and xmpp server. You can can visit how to install xmpp server.

package com.javaproficiency.demo;

import java.util.Collection;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;



public class SendMessageInChat {

 public static void main(String[] args) {

   AddRoster addRoster = new AddRoster();
 
XMPPConnection connection = addRoster.Connect();
try {
connection.login("yogesh@localhost","123");
System.out.println("Login");

Chat chat = connection.getChatManager().createChat("shivam@localhost", new MessageListener() {

@Override
            public void processMessage(Chat chat, Message message) {
                // Print out any messages we get back to standard out.
                System.out.println("Received message: " + message);
            }

        });
        try {
chat.sendMessage("How are you dear !!");
System.out.println(" Send Message succesfully");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

           connection.disconnect();

} catch (XMPPException e) {

e.printStackTrace();
}
}


private void loginUser(XMPPConnection connection) {
// TODO Auto-generated method stub

}


public XMPPConnection Connect() {
 
  ConnectionConfiguration config = new ConnectionConfiguration(
  "localhost", 5222);

  /*
  * ConnectionConfiguration config = new ConnectionConfiguration(
  * "192.163.2.200", 5222);
  */
  XMPPConnection connection = new XMPPConnection(config);
  try {
  connection.connect();
  } catch (XMPPException e) {
 
  e.printStackTrace();
  }
  return connection;
  }



}



After execution of this you can see message in xmpp client spark as

How to chat in xmpp server




How to remove Roster or Friend in xmpp server

In last post we have learn how to add roster in xmpp.  Now we will remove roster from roster list of any user. For  first you should  add roster in roster list of user. Now We get roster list of user and compare jabber id of roster and remove it using  removeEntry( RosterEntry ) method  . After remove roster you check roster using this article How to get roster of jabber id in xmpp server .

package com.javaproficiency.demo;

import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;



public class RemoveRoster {

  public static void main(String[] args) {

    AddRoster addRoster = new AddRoster();
 
XMPPConnection connection = addRoster.Connect();
try {
connection.login("yogesh@localhost","123");
System.out.println("Login");
Roster roster = connection.getRoster();
String removeJID = "shivam@localhost";
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
          // remove roster whith removeJID
if (removeJID.equals(entry.getUser())) {
roster.removeEntry(entry);
}
}

           connection.disconnect();

} catch (XMPPException e) {

e.printStackTrace();
}
}


public XMPPConnection Connect() {
  
   ConnectionConfiguration config = new ConnectionConfiguration(
   "localhost", 5222);

   /*
    * ConnectionConfiguration config = new ConnectionConfiguration(
    * "192.163.2.200", 5222);
    */
   XMPPConnection connection = new XMPPConnection(config);
   try {
   connection.connect();
   } catch (XMPPException e) {
  
   e.printStackTrace();
   }
   return connection;
   }



}



how to add roster in xmpp using smack api

In last article we have learn how to login on xmpp server using smack api . Now In this article we will learn how to add friends( roster ) in buddy using smack api.For add roster in xmpp first you should make two account. See It how to resister on xmpp server if you do not know how to register user on xmpp server. after that you can send roster request using below code . 


package com.javaproficiency.demo;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

public class AddRoster {

 public static void main(String[] args) {

   AddRoster addRoster = new AddRoster();
 
XMPPConnection connection = addRoster.Connect();
try {

                     // user yogesh login on xmpp server
connection.login("yogesh@localhost","123");
System.out.println("Login");

           Roster roster = connection.getRoster();
           // yogesh send roster request to shivam
           roster.createEntry("shivam@localhost","myking",null);

           System.out.println(" send roster request");
           connection.disconnect();

} catch (XMPPException e) {

e.printStackTrace();
}
}


public XMPPConnection Connect() {
 
  ConnectionConfiguration config = new ConnectionConfiguration(
  "localhost", 5222);

  /*
  * ConnectionConfiguration config = new ConnectionConfiguration(
  * "192.163.2.200", 5222);
  */
  XMPPConnection connection = new XMPPConnection(config);
  try {
  connection.connect();
  } catch (XMPPException e) {
 
  e.printStackTrace();
  }
  return connection;
  }


}



After execution  of this code you can see this output :

 Login
 
send roster request


And  


how to add roster in xmpp server








Saturday 5 December 2015

How to install Spark IM client in ubuntu

Spark Im client is xmpp client. You must read this article first  how to install openfire xmpp server in ubuntu. After that you need xmpp client for chating. Now We will learn how to Intall xmpp client in ubuntu.

Step 1: Download Xmpp Client Spark from this link http://www.igniterealtime.org/downloads/
 or you can download openfire from this website http://www.igniterealtime.org .

Step 2: Extract tar file.

Step 3: Go to Spark Folder and run this command

           ./Spark

Now you will see spark is running on you machine.

Step 4: Now you can login on xmpp server using spark


How to install xmpp client spark




You can create new account on xmpp server using spark












Related Posts:

Connecting to XMPP IM with Smack for Java applications

Login to XMPP IM with Smack for Java applications

Get Roster List From XMPP IM with Smack API in Java Application






How To Install Openfire XMPP Server On Ubuntu

Step 1:

Downlaod Openfire from this link http://www.igniterealtime.org/downloads/
 or you can download openfire from this website http://www.igniterealtime.org

step 2:   Exact tar file

Step 3:  go to bin folder and run this command

          ./openfire start

On your terminal you get such message

openfire/bin$  ./openfire start
testing JVM in /usr ...
Starting openfire


step 4:  Now go to browser and hit url

   localhost:9090

if you use local machine otherwise use ip address of machine. We can see such page and click to continue .

how to install openfire



Step 5:  In this step you will select domain and admin port. By default admin console port 9090 and secure admin port is 9091.Domain is ip address of machine. If you want to run openfire then you can use localhost as domain. Click continue for step step of openfire installation.


openfire instalation





Step 6: In this step of openfire installation you will select database settings. If you donot know about it more i suggest to you click continue .

openfire installation



Step 7 :  In this  step you will select database for openfire. For example if i use mysql database then i fill all fields as requirement . i select mysql database then in database url i fill up database name and mysql hostname and more parameter as my requirements .  There is usename mysql usename and password is mysql password.





Step 8: Click to continue:









Step 9:  In This Step you will step administrator account of openfire. Select password for openfire admin.




Step 10. Click Login to admin console of openfire.






Step 11. Use usename and password for openfire administration , which are you have selected during openfire installation .







Step 12: See Openfire Admin Account as







After that you need to learn this tutorial for openfire devlopment  Openfire Tutorial



Related Posts:

Connecting to XMPP IM with Smack for Java applications

Login to XMPP IM with Smack for Java applications

Get Roster List From XMPP IM with Smack API in Java Application






Thursday 3 December 2015

Operators and datatypes In Java


Operator is a symbol that is used to perform operations on operands. There are many types of operators in java such as unary operator, arithmetic operator, relational operator, shift operator, bitwise operator, ternary operator and assignment operator.





Primitive Data Types

1. Integer
Integer types varaible can hold whole numbers such as 747 and −196. The size of the values that can be stored depends on the integer type that we choose.

Type Size Range of values that can be stored
byte 1 byte −128 to 127
short 2 bytes −32768 to 32767
int 4 bytes −2,147,483,648 to 2,147,483,647
long 8 bytes 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807

The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can be stored in the byte data type is −(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127

2. Floating Point
Floating point data types are used to represent numbers with a fractional part. Single precision floating point numbers occupy 4 bytes and Double precision floating point numbers occupy 8 bytes. There are two subtypes:

Type Size Range of values that can be stored
float 4 bytes 3.4e−038 to 3.4e+038
double 8 bytes 1.7e−308 to 1.7e+038
3. Character
It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can hold only a single character because char stores unicode character sets. It has a minimum value of ‘u0000′ (or 0) and a maximum value of ‘uffff’ (or 65,535, inclusive).

4. Boolean
Boolean data types are used to store values with two states: true or false.


Related Post:






Wednesday 2 December 2015

How Find out duplicate number between 1 to N numbers - Java Program

We have numbers from 1 to n  and one number is duplicate. Now we will find out duplicate number in given list. For this we will use formula sum of 1....n numbers.Firstly we will calculate the sum of list and sum of 1.... n number. Now difference between sum of list and sum of 1... n is equal to duplicate number .

sum of 1... n number = n*(n+1)/2


package com.javaproficiency;

import java.util.ArrayList;
import java.util.List;

public class FindDuplicateNumber {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
list.add(i);
}
list.add(5);
FindDuplicateNumber duplicateNumber = new FindDuplicateNumber();
System.out.println(" duplicate number ="+ duplicateNumber.getDuplicateNumber(list));
}

public  int getDuplicateNumber( ArrayList<Integer> list){

int size = list.size()-1;
int totalSum = (size*(size+1))/2;
int duplicateNumber = getSumOfList(list)- totalSum ;
return duplicateNumber;
}

public int getSumOfList( ArrayList<Integer> list){
int sum =0;
for (Integer num : list) {
sum += num;
}
return sum;
}


}


Output :

 duplicate number =5




How to convert Byte array to String in Java

In our application sometime there is need of byte array. We can use byte array for encryption purpose . We can convert a string to byte array using string getBytes() method. In byte array string become in decryted format . We can make string from byte array using this syntax.

String str = new String(ByteArray);


package com.javaproficiency;

public class StringToBinary {
public static void main(String[] args) {
String IPCode = "java string is good";
//convert string to byte  array
byte [] bytes = IPCode.getBytes();
System.out.println(" string ="+ IPCode);
System.out.println(" byte array ="+ bytes);
//Convert byte array to string 
String str = new String( bytes );
System.out.println(" str ="+  str);
}

}

Output:

 string =java string is good

 byte array =[B@6c267f18

 str =java string is good

How to check the given number is binary number or not -Java Program

In mathematics and digital electronics, a binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). The base-2 system is a positional notation with a radix of 2. Below we have write a java program for check given number binary or not.

package com.javaproficiency;

public class IsBinary {

public static void main(String[] args) {

IsBinary isBinary = new IsBinary();

System.out.println(" num 101000 is binary = "+ isBinary.isBinary(101000) );
System.out.println(" num 101300 is binary = "+ isBinary.isBinary(101300) );
System.out.println(" num 101900 is binary = "+ isBinary.isBinary(101900) );
System.out.println(" num 10001 is binary = "+ isBinary.isBinary(10001) );


}


public boolean isBinary( int num ){

boolean flag = true;
while (num  > 0) {
int rem = num %10;
if (rem > 1) {
flag = false;
break;
}
num = num/10;
}
return flag;
}


}



Output:

 num 101000 is binary = true
 num 101300 is binary = false
 num 101900 is binary = false
 num 10001 is binary = true


Tuesday 1 December 2015

How to convert binary to decimal number - Java Program

In this example we will convert binary to decimal using  java. We will use this logic

11 ==>>  1*2^1+1*2^0   == > 3

110 ==> 1*2^2+1*2^1+0*2^0  ==> 6

package com.javaproficiency;

public class BinaryToDecimal {

public static void main(String[] args) {

System.out.println(" decimal number ="+ getDecimalFromBinary(11));

}


public static int getDecimalFromBinary(int num ){
int decimal = 0 ;
int p = 0;
 while ( num > 0) {
 decimal += num %10 * Math.pow(2, p );
 num = num /10;
 p++;
}

return decimal;
}

}


Output:

decimal number = 3