Dec 31, 2015

Java 7 Features

Following are some of the cool features introduced on Java 7.

1. Strings in switch Statement

Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,
String state = "NEW";

switch (day) {
   case "NEW": System.out.println("Order is in NEW state"); break;
   case "CANCELED": System.out.println("Order is Cancelled"); break;
   case "REPLACE": System.out.println("Order is replaced successfully"); break;
   case "FILLED": System.out.println("Order is filled"); break;
   default: System.out.println("Invalid");
}

equals() and hashcode() method from java.lang.String is used in comparison, which is case-sensitive. Benefit of using String in switch is that, Java compiler can generate more efficient code than using nested if-then-else statement.


2. Type Inference for Generic Instance Creation (Diamond Operator)

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

For example, consider the following variable declaration:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
Map<String, List<String>> myMap = new HashMap<>();

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the
Map<String, List<String>> type:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning


3. Multiple Exception Handling

In JDK 7, a single catch block can handle more than one exception types.
For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:

try {
   ......

} catch(ClassNotFoundException ex) {
   ex.printStackTrace();
} catch(SQLException ex) {
   ex.printStackTrace();
}

In JDK 7, you could use one single catch block, with exception types separated by '|'.

try {
   ......

} catch(ClassNotFoundException|SQLException ex) {
   ex.printStackTrace();
}

By the way, just remember that Alternatives in a multi-catch statement cannot be related by sub classing. For example a multi-catch statement like below will throw compile time error :

try {
   ......

} catch (FileNotFoundException | IOException ex) {
   ex.printStackTrace();
}

Alternatives in a multi-catch statement cannot be related by sub classing, it will throw error at compile time :
java.io.FileNotFoundException is a subclass of alternative java.io.IOException
        at Test.main(Test.java:18)



4. Binary Literals, underscore in literals

In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. This is especially valuable for people who uses large numbers in source files, may be useful in finance and computing domains. For example,

int billion = 1_000_000_000;  // 10^9
long creditCardNumber =  1234_4567_8901_2345L; //16 digit number
long ssn = 777_99_8888L;
double pi = 3.1415_9265;
float  pif = 3.14_15_92_65f;


5. Binary Literals with prefix "0b"

In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').
int mask = 0b01010000101;
or even better
int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;

6. The try-with-resources Statement

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).


7. Java NIO 2.0

Java SE 7 introduced java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system. It also introduced the Path class which allow you to represent any path in operating system. New File system API complements older one and provides several useful method checking, deleting, copying, and moving files.
Following additional features have been introduced in NIO package.
  • Now you can check if a file is hidden in Java. 
  • You can also create symbolic and hard links from Java code.  
  • JDK 7 new file API is also capable of searching for files using wild cards. 
  • You also get support to watch a directory for changes.

Anyhow it would be recommended to check Java doc of new file package to learn more about this interesting useful feature.


Dec 28, 2015

Java: Finally block

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

When finally will not execute?

    - If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.

    - If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    - If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

From the sample code below we can notice that finally block is not executed while JVM exits in catch block.


    public static void main(String[] args)
    {
        try
        {
            System.out.println("IN TRY BLOCK");
            throwsMethod();
        }
        catch (Exception e)
        {
            System.out.println("IN CATCH BLOCK");
            System.exit(0);
        }
        finally
        {
            System.out.println("IN FINALLY BLOCK");
        }
    }
    
    static void throwsMethod() throws Exception
    {
        throw new Exception("Exception thrown manually");
    }

Code output:

IN TRY BLOCK
IN CATCH BLOCK 

Here you can notice, code inside finally block is not executed.


Dec 27, 2015

java.lang.Error

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it. 

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

 

Error Summary

S.N.Error & Description
1 AbstractMethodError This is Thrown when an application tries to call an abstract method.
2AssertionError This is Thrown to indicate that an assertion has failed.
3 ClassCircularityError This is Thrown when a circularity has been detected while initializing a class.
4 ClassFormatError This is Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.
5 Error This is an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
6 ExceptionInInitializerError These are the Signals that an unexpected exception has occurred in a static initializer.
7 IllegalAccessError This is Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to
8 IncompatibleClassChangeError This is Thrown when an incompatible class change has occurred to some class definition.
9 InstantiationError This is Thrown when an application tries to use the Java new construct to instantiate an abstract class or an interface.
10 InternalError This is Thrown to indicate some unexpected internal error has occurred in the Java Virtual Machine.
11 LinkageError The Subclasses of LinkageError indicate that a class has some dependency on another class.
12 NoClassDefFoundError This is Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and no definition of the class could be found.
13 NoSuchFieldError This is Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.
14 NoSuchMethodError This is Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
15 OutOfMemoryError This is Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
16 StackOverflowError This is Thrown when a stack overflow occurs because an application recurses too deeply.
17 ThreadDeath This is an instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called.
18 UnknownError This is Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.
19 UnsatisfiedLinkError This is Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native.
20 UnsupportedClassVersionError This is Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.
21 VerifyError This is Thrown when the "verifier" detects that a class file, though well formed, contains some sort of internal inconsistency or security problem.
22 VirtualMachineError This is Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.

Jul 22, 2015

Change timezone in Unix/Linux

Check your current timezone.


Log in as root. Open the terminal and check which timezone your machine is currently using by executing the date command. The terminal will display the date in the following format:
Mon Aug 12 12:15:08 PST 2013.
PST in this case refers to the current timezone (Pacific Standard Time).

Select your timezone region.


Change to the directory /usr/share/zoneinfo. A list of time zone regions will be displayed.

The /usr/share/zoneinfo directory may vary depending on your Linux distribution.

Backup your old timezone settings.


If you wish, backup the previous timezone configuration by renaming it to a backup name. Use the following command
mv /etc/localtime /etc/localtime-old    

Link your machine’s clock to a city in your timezone.


Use the following command, replacing the region and city with your appropriate entries:
ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime

If your city is not listed in the timezone list, pick one from your same timezone.

Verify that your timezone has been set.


Run the date command again and check that the timezone corresponds to the one you just changed to.

Set your clock to stay synced with internet time servers.


Most modern distributions have NTP already installed. If you do not, you will need to install the NTP server package. Use the following commands to install it, depending on your Linux distribution:

Ubuntu/Debian: sudo aptitude install ntp
CentOS: sudo yum install ntp
sudo /sbin/chkconfig ntpd on
Fedora/RedHat: sudo yum install ntp
sudo chkconfig ntpd on
Enter the ntpdate command: ntpdate && hwclock –w

There are a variety of public time servers available to connect to. You can find listings online.


Jul 21, 2015

Use 'grep' to Find File Names With a Matching String

By default, grep displays the lines in one or more files that match your search string (or regular expression). Here is how you recursively search through a directory of files and list the name(s) of the files that contain a matching string instead of the matched line.
grep -l Switch

The -l switch indicates that you want to display the names of files that contain a string that matches your query. Here is an example of its use with an entire directory of xml files (using the *.xml wildcard):
grep -l 'SEARCH_TERM' /path_to_your_directory/*.xml

This command causes grep to search for lines that match the query SEARCH_TERM in every .xml file in the given directory & will print the names of the files that contain a match to the standard output stream.
abc.xml
another_abc.xml

Replace SEARCH_TERM with your query and *.xml with any filetype or the name pattern of a set of files that you would like to search. The query can be a string or regular expression.

You can find grep documentation here

Jul 6, 2015

nodetool: Failed to connect to '127.0.0.1:7199' - ConnectException: 'Connection refused'. (Cassandra)


Error While Using Cassandra’s 'nodetool'

This error may occur when using the 'nodetool' command, such as in the following example:

$ nodetool status

For both CentOS 6 and CentOS 7 search the following configuration file:

cassandra-env.sh


This will be inside your <cassandra_home>/conf/ directory
Open this file in edit mode (Make sure you have permission to edit this file. Here I am a root user, so I have permission to edit it)

$ vim <cassandra_home>/conf/cassandra-env.sh


Tips: If you couldn't find this file, use 'locate' command to get the file location.
$ locate cassandra-env.sh


Once you open the file in edit mode, search for:

JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=

Which will probably result in:

# add this if you’re having trouble connecting:
# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>"


Uncomment the second line, and add the hostname of your server (replace <public name> with the IP/hostname), or the IP address which you’re connecting to/from.

Then exit and save the file.

Final Note:
Make Sure to restart Cassandra once the changes are done.

Jan 23, 2015

Unix Shell scripting conditional expressions


In this post, lets discuss the use of conditionals in bash scripts.

What are conditionals?


At times you need to specify different courses of action to be taken in a shell script, depending on the success or failure of a command. The if construction allows you to specify such conditions.

The most compact syntax of the if command is:

if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

The TEST-COMMAND often involves numerical or string comparison tests, but it can also be any command that returns a status of zero when it succeeds and some other status when it fails.

Syntax:


if [ expression 1 ];
then
  Statement(s) to be executed if expression 1 is true
elif [ expression 2 ];
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ];
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

Example:



#!/bin/sh
a=1
b=2

if [ $a == $b ];
then
   echo "a is equal to b"
elif [ $a -gt $b ];
then
   echo "a is greater than b"
elif [ $a -lt $b ];
then
   echo "a is less than b"
else
   echo "None of the conditions matched"
fi

Now let us see the different ways to use expressions with numeric and strings.

       ( EXPRESSION )
              EXPRESSION is true

       ! EXPRESSION
              EXPRESSION is false

       EXPRESSION1 -a EXPRESSION2
              both EXPRESSION1 and EXPRESSION2 are true

       EXPRESSION1 -o EXPRESSION2
              either EXPRESSION1 or EXPRESSION2 is true

       -n STRING
              the length of STRING is nonzero

       STRING equivalent to -n STRING

       -z STRING
              the length of STRING is zero

       STRING1 = STRING2
              the strings are equal

       STRING1 != STRING2
              the strings are not equal

       INTEGER1 -eq INTEGER2
              INTEGER1 is equal to INTEGER2

       INTEGER1 -ge INTEGER2
              INTEGER1 is greater than or equal to INTEGER2

       INTEGER1 -gt INTEGER2
              INTEGER1 is greater than INTEGER2

       INTEGER1 -le INTEGER2
              INTEGER1 is less than or equal to INTEGER2

       INTEGER1 -lt INTEGER2
              INTEGER1 is less than INTEGER2

       INTEGER1 -ne INTEGER2
              INTEGER1 is not equal to INTEGER2


Expressions for file operations can be found in this link: File Operations


All these details could be obtained from 'man test' command on linux/unix terminal.

What are VIEWS in Oracle/PLSQL?



Oracle/PLSQL: VIEWS


Let's learn to create, update, and drop Oracle VIEWS with syntax and examples.

What is a VIEW in Oracle?


An Oracle VIEW, in essence, is a virtual table that does not physically exist. Rather, it is created by a query joining one or more tables.

Create VIEW
Syntax
The syntax for the Oracle CREATE VIEW Statement is:

CREATE VIEW view_name AS 
SELECT columns FROM tables WHERE conditions;

view_name is the name of the Oracle VIEW that you wish to create.

Example
Here is an example of how to use the Oracle CREATE VIEW:

CREATE VIEW sup_orders AS 
SELECT suppliers.supplier_id, orders.quantity, orders.price 
FROM suppliers INNER JOIN orders 
ON suppliers.supplier_id = orders.supplier_id WHERE suppliers.supplier_name = 'Microsoft';

This Oracle CREATE VIEW example would create a virtual table based on the result set of the SELECT statement. You can now query the Oracle VIEW as follows:

SELECT * FROM sup_orders;

Update VIEW

You can modify the definition of an Oracle VIEW without dropping it by using the Oracle CREATE OR REPLACE VIEW Statement.

Syntax
The syntax for the Oracle CREATE OR REPLACE VIEW Statement is:

CREATE OR REPLACE VIEW view_name AS 
SELECT columns FROM table WHERE conditions;

Example
Here is an example of how you would use the Oracle CREATE OR REPLACE VIEW Statement:

CREATE or REPLACE VIEW sup_orders AS 
SELECT suppliers.supplier_id,
orders.quantity, orders.price
FROM suppliers INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'Apple';

This Oracle CREATE OR REPLACE VIEW example would update the definition of the Oracle VIEW called sup_orders without dropping it. If the Oracle VIEW did not yet exist, the VIEW would merely be created for the first time.

Drop VIEW

Once an Oracle VIEW has been created, you can drop it with the Oracle DROP VIEW Statement.

Syntax
The syntax for the Oracle DROP VIEW Statement is:

DROP VIEW view_name;

view_name is the name of the view that you wish to drop.

Example

Here is an example of how to use the Oracle DROP VIEW Statement:

DROP VIEW sup_orders;

This Oracle DROP VIEW example would drop/delete the Oracle VIEW called sup_orders.

Frequently Asked Questions

Question: Can you update the data in an Oracle VIEW?

Answer: A VIEW in Oracle is created by joining one or more tables. When you update record(s) in a VIEW, it updates the records in the underlying tables that make up the View.
So, yes, you can update the data in an Oracle VIEW providing you have the proper privileges to the underlying Oracle tables.


Question:
Does the Oracle View exist if the table is dropped from the database?

Answer: Yes, in Oracle, the VIEW continues to exist even after one of the tables (that the Oracle VIEW is based on) is dropped from the database. However, if you try to query the Oracle VIEW after the table has been dropped, you will receive a message indicating that the Oracle VIEW has errors.
If you recreate the table (the table that you had dropped), the Oracle VIEW will again be fine.

Jan 14, 2015

Eclipse + Maven + Tomcat 7 : java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet




Sometimes when we setup a new web application project in Eclipse with Maven and using Tomcat 7 server, we might face following exception trace in server startup.



java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:126)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1043)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4957)
    at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5284)
    at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5279)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)



This exception usually occur due to missing "Maven Dependency" in Deployment Assembly.

Following the below steps will help resolving the issue:

- Open your eclipse-> right click on your maven project & choose "Properties"

- Click on "Deployment Assembly"

- Click "Add"

- Click on "Java Build Path Entries"

- Select "Maven Dependencies"

- Click Finish.

Rebuild and deploy it again.




Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete



Problem usually arises when we use Eclipse Kepler and Tomcat 7.

Add Tomcat 7 to eclipse and when you start the tomcat or when you try to add a project to tomcat, you will get following error 


Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 
Server at localhost-config. The configuration may be corrupt or incomplete


Follow the below steps to resolve the issue:


- Delete tomcat from eclipse-> servers tab.

- Copy all the contents inside your "TOMCAT_7_HOME/conf" directory.

- Paste the above copied content into "WORKSPACE_DIR/Servers/Tomcat v7.0 Server at localhost-config" directory.

- Open Eclipse and add the tomcat server to Servers tab.

- Add the project and start the server.


Jan 12, 2015

Shell Scripting: File Operations



In Shell scripting, we can perform lots of file based operations such as checking if file exists, checking if it's a directory, checking if it's a writable file and so on. 

For Example, following is a shell script that checks if the file "config_file.txt" exists.
 
#!/bin/bash
FILE="config_file.txt" if [ -f $FILE ]; then echo "File $FILE exists" else echo "File $FILE does not exists" fi

Following are the list of options available for file operations.

-a file
True if file exists.

-b file
True if file exists and is a block special file.

-c file
True if file exists and is a character special file.

-d file
True if file exists and is a directory.

-e file
True if file exists.

-f file
True if file exists and is a regular file.

-g file
True if file exists and is set-group-id.

-h file
True if file exists and is a symbolic link.

-k file
True if file exists and its ‘‘sticky’’ bit is set.

-p file
True if file exists and is a named pipe (FIFO).

-r file
True if file exists and is readable.

-s file
True if file exists and has a size greater than zero.

-t fd 
True if file descriptor fd is open and refers to a terminal.

-u file
True if file exists and its set-user-id bit is set.

-w file
True if file exists and is writable.

-x file
True if file exists and is executable.

-O file
True if file exists and is owned by the effective user id.

-G file
True if file exists and is owned by the effective group id.

-L file
True if file exists and is a symbolic link.

-S file
True if file exists and is a socket.

-N file
True if file exists and has been modified since it was last read.

file1 -nt file2
True if file1 is newer (according to modification date) than file2, or if file1 exists and
file2 does not.

file1 -ot file2
True if file1 is older than file2, or if file2 exists and file1 does not.

file1 -ef file2
True if file1 and file2 refer to the same device and inode numbers.

How to Remote Desktop (RDP) Linux Machine from windows 7


Overview
Our requirement is to enable remote desktop function in centos Linux machine which will allow us to access Linux box from windows machine using mstsc.exe (Remote Desktop).

For that we will use XRDP which is wonderful remote desktop protocol application. It is free open source software for Linux.

Installation:
We need some additional work to install XRDP on centos as centos repositories do not contain the XRDP package. You need to download and add EPEL (Extra Packages Enterprise Linux).

Let’s verify our correct OS architecture first.
Using below command we can verify OS architecture.

Step 1:
[/root]# uname -r
2.6.32-431.el6.x86_64

If the output shows x86_64 at end then mean, you have a 64-bit install or if it shows i386 then it is a 32-bit install.

Our output is showing (2.6.32-431.el6.x86_64) it’s mean we have 64-bit operating system.
After determining your architecture, install the correct EPEL repository with below command.

Step 3:
For RedHat or Centos 6.x 32-bit
[/root]# wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
[/root]# rpm -ivh epel-release-6-8.noarch.rpm

For Redhat Enterprise Linux or Centos 5.x 64-bit
[/root]# wget http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
[/root]# sudo rpm -Uvh epel-release-5*.rpm

For RedHat Enterprise Linux or Centos 6.x 64-bit
[/root]# wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
[/root]# sudo rpm -Uvh epel-release-6*.rpm

For Redhat Enterprise Linux or Centos 7.x 64-bit
[/root]# wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-1.noarch.rpm
[/root]# sudo rpm -Uvh epel-release-7*.rpm

Step 4:
Lets verify EPEL repository is installed correctly
[/root]# yum repolist -v | grep epel
We can see EPEL repository is installed correctly.

While doing this step, if any following error occurs,

"Loaded plugins: fastestmirror, refresh-packagekit, security Loading
mirror speeds from cached hostfile
Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again"

Solve this issue editing both /etc/yum.repos.d/epel.repo and /etc/yum.repos.d/epel-testing.repo files, commenting all entries starting with mirrorlist=... and uncomenting all the entries starting with baseurl=...

If it didn’t solve the issue, then run yum update on the os.

Step 5:
Now we need to install XRDP package including some dependencies.
[/root]# yum install xrdp tigervnc-server

Step 6:
After instllation we need to configure display.

Edit display file located at /etc/sysconfig/vncservers
[/root]# vim /etc/sysconfig/vncservers

Find at last these lines
# VNCSERVERS="2:myusername"
# VNCSERVERARGS[2]="-geometry 800x600 -nolisten tcp -localhost"

Uncomment and change them into.
VNCSERVERS="2:root"
VNCSERVERARGS[2]="-geometry 800x600"

I am using root user as my remote desktop user.
Now save this file and exit.

Step 7:
Start VNC and XRDP services.
[/root]# service vncserver start
[/root]# service xrdp start

If any following error occurs on vncserver start,

"You will require a password to access your desktops.
getpassword error: Inappropriate ioctl for device"

Run the command "vncserver /.vnc/passwd" and then enter the password (i.e. Setup new password)


Step 8:
Make them available on next startup.
[/root]# chkconfig xrdp on
[/root]# chkconfig vncserver on

That’s it all the packages are installed, now you should be able to access your linux box from any RDP Client.

Stop iptables from centos machine.
[/root]# sudo /etc/init.d/iptables stop 


Then goto your windows machine where you need to connect the above configured Linux machine. Click on "Start" and type "mstsc.exe".

In the open dialog, enter the Linux PC's ip address & Enter. Give Linux machine's user name ('root' in our case) and password.

Now you are connected to Linux via Remote Desktop.