Tuesday, 26 August 2014

Linux Commands



File Commands




1.
ls
Directory listing
2.
ls -al
Formatted listing with hidden files
3.
ls -lt
Sorting the Formatted listing by time modification
4.
cd dir
Change directory to dir
5.
cd
Change to home directory
6.
pwd
Show current working directory
7.
mkdir dir
Creating a directory dir
8.
cat >file
Places the standard input into the file
9.
more file
Output the contents of the file
10.
head file
Output the first 10 lines of the file
11.
tail file
Output the last 10 lines of the file
12.
tail -f file
Output the contents of file as it grows,starting with


the last 10 lines
13.
touch file
Create or update file
14.
rm file
Deleting the file
15.
rm -r dir
Deleting the directory
16.
rm -f file
Force to remove the file
17.
rm -rf dir
Force to remove the directory dir
18.
cp file1 file2
Copy the contents of file1 to file2
19.
cp -r dir1 dir2
Copy dir1 to dir2;create dir2 if not present
20.
mv file1 file2
Rename or move file1 to file2,if file2 is an existing


directory
21.
ln -s file link
Create symbolic link link to file
Process management

1.
ps
To display the currently working processes
2.
top
Display all running process




3.
kill pid
Kill the process with given pid
4.
killall proc
Kill all the process named proc
5.
pkill pattern
Will kill all processes matching the pattern
6.
bg
List stopped or background jobs,resume a stopped


job in the background
7.
fg
Brings the most recent job to foreground
8.
fg n
Brings job n to the foreground




Searching

1.
grep pattern file
Search for pattern in file
2.
grep -r pattern dir
Search recursively for pattern in dir
3.
command | grep 
Search pattern in the output of a command

pa

4.
locate file
Find all instances of file
5.
find . -name filename
Searches in the current directory (represented by


a period) and below it, for files and directories with


names starting with filename
6.
pgrep pattern
Searches for all the named processes , that


matches with the pattern and, by default, returns


their ID




System Info

1.
date
Show the current date and time
2.
cal
Show this month's calender
3.
uptime
Show current uptime
4.
w
Display who is on line
5.
whoami
Who you are logged in as




6.
finger user
Display information about user
7.
uname -a
Show kernel information
8.
cat /proc/cpuinfo
Cpu information
9.
cat proc/meminfo
Memory information
10.
man command
Show the manual for command
11.
df
Show the disk usage
12.
du
Show directory space usage
13.
free
Show memory and swap usage
14.
whereis app
Show possible locations of app
15.
which app
Show which applications will be run by default




Compression

1.
tar cf file.tar file
Create tar named file.tar containing file
2.
tar xf file.tar
Extract the files from file.tar
3.
tar czf file.tar.gz files
Create a tar with Gzip compression
4.
tar xzf file.tar.gz
Extract a tar using Gzip
5.
tar cjf file.tar.bz2
Create tar with Bzip2 compression
6.
tar xjf file.tar.bz2
Extract a tar using Bzip2
7.
gzip file
Compresses file and renames it to file.gz
8.
gzip -d file.gz
Decompresses file.gz back to file




Network

1.
ping host
Ping host and output results
2.
whois domain
Get whois information for domains
3.
dig domain
Get DNS information for domain
4.
dig -x host
Reverse lookup host
5.
wget file
Download file
6.
wget -c file
Continue a stopped download







Shortcuts

1.
ctrl+c
Halts the current command
2.
ctrl+z
Stops the current command, resume with fg in the


foreground or bg in the background
3.
ctrl+d
Logout the current session, similar to exit
4.
ctrl+w
Erases one word in the current line
5.
ctrl+u
Erases the whole line
6.
ctrl+r
Type to bring up a recent command
7.
!!
Repeats the last command
8.
exit
Logout the current session






Saturday, 23 August 2014

A sample Hello World example in node.js


// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server
.listen(8000);
// Put a friendly message on the terminal
console
.log("Server running at http://127.0.0.1:8000/");

Friday, 22 August 2014

Domain Controller Settings for Windows Authentication .

What is Active Directory?

Active Directory (AD) is a directory service that Microsoft developed for Windows domain networks and is included in most Windows Server operating systems as a set of processes and services.
An AD domain controller authenticates and authorizes all users and computers in a Windows domain type network—assigning and enforcing security policies for all computers and installing or updating software. For example, when a user logs into a computer that is part of a Windows domain, Active Directory checks the submitted password and determines whether the user is a system administrator or normal user.
Active directory/Domain settings for a computer
Pre-requisites –
  1.      You are using a window 7 professional Edition (As per my knowledge it does not support Windows 7  Home Basic Edition)
  2.    You have a user account on active directory.
  3.       You must be connected to the domain network.

A domain is a collection of computers on a network with common rules and procedures that are administered as a unit. Each domain has a unique name. Typically, domains are used for workplace networks. To connect your computer to a domain, you'll need to know the name of the domain and have a valid user account on the domain.

1.       Open System by clicking the Start button, right-clicking Computer, and then clicking Properties.
2.       Under Computer name, domain, and workgroup settings, click Change settings.  If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
3.       Click the Computer Name tab, and then click Change. Alternatively, click Network ID to use the Join a Domain or Workgroup wizard to automate the process of connecting to a domain and creating a domain user account on your computer.
4.       Under Member of, click Domain a screen appears as



Type the name of the domain that you want to join- and then click OK.
You will be asked to type your user name and password for the domain.
Once you are successfully joined to the domain, you will be prompted to restart your computer. You must restart your computer before the changes take effect.

DNS Settings needed - 
  1. Click Start and then Control Panel
  2. Click View network status and tasks
  3. Click Change adapter settings on the left portion of the Window.
  4. Double-click the icon for the Internet connection you're using. Often this will be labeled "Local Area Connection" or the name of your ISP. If you have multiple connections, make sure not to click the one with the red X.
  5. Click the Properties button.
  6. Click and highlight Internet Protocol Version 4 (TCP/IPv4) and click Properties.
  7. If not already selected, select Use the following DNS server addresses
  8. Enter the new DNS addresses and then click Ok and close out of all other windows.




Thursday, 21 August 2014

How to change wallpaper in ubuntu command-line ?

       
for filename in /home/mahavir/Documents/walle/wallpapers/*.* do echo "file://$filename" background="file://$filename" echo $background gsettings set org.gnome.desktop.background picture-uri $background sleep 21 done if (exit=0) then ./ubuntuish.sh fi

Wednesday, 20 August 2014

How to find disk space utilization using Java?

 import java.io.File;  
 import java.nio.file.FileSystem;  
 import java.nio.file.FileSystems;  
 import java.nio.file.Path;  
 import java.util.Iterator;  
 public class DiskSpace {  
  public static void main(String[] args) {  
            FileSystem fs = FileSystems.getDefault();  
            Iterable drives = fs.getRootDirectories();  
            Iterator path = drives.iterator();  
            while(path.hasNext()){  
                  Path p = path.next();    
                  String drive = p.toString();  
                  System.out.println(drive);  
                  File f = new File(drive);  
                  float freeSpace = f.getFreeSpace();  
                  float totalSpace = f.getTotalSpace();  
                  if(totalSpace>0){  
                          float percentFree = (freeSpace/totalSpace)*100;  
                          System.out.println(drive + "---- " +freeSpace + "------ " + totalSpace + "---------- " + percentFree);  
                  }  
            }  
      }  
 }  

Monday, 18 August 2014

A sample shell script to deploy your application in tomcat7 ubuntu.

A sample shell script to deploy your application in tomcat7 ubuntu.

#/bin/sh
echo -e  "Enter your name - \c "
read name
echo -e  "Enter your password - \c "
read password

################ Used to stop the tomcat #################################
function stop_tomcat(){
      sudo service tomcat7 stop
       return ;
}

################ Used to start the tomcat #################################
function start_tomcat(){
      sudo service tomcat7 start
      status = `echo $?`
      if [ $status -ge 0 ]
      then
    echo "Error starting tomcat "
    exit
       fi


      return ;
}
######################end ################################################


######################### copy the war to webapps ########################
function copy_war(){
       echo "Copying war ------------------"
       sudo cp ~/patch/.war /var/lib/tomcat7/webapps
       ls -ltr /var/lib/tomcat7/webapps/
       start_tomcat
       echo " ---------------- patch complete --------------------"
}

############################end###########################################


######################### copy the war to webapps ########################
function code_base_patch(){
       echo "Code base patching"
       unrar  x ~/patch/.rar /var/lib/tomcat7/webapps//
       cd /var/lib/tomcat7/webapps//
       ant
       start_tomcat
       echo " ---------------- patch complete --------------------"
}

############################end###########################################




if  [ $name = "dev" ]
then
     if [ $password = "dev" ]
     then
if [ -f "patch_log.log" ]
then
    echo "Patch started on `date` by - " $name >> patch_log.log
else
    touch patch_log.log
fi
stop_tomcat
echo -e "Enter mode of deployment - \c"
         read mode
if [ $mode = "war" ]
           then
              copy_war
  else
     code_base_patch
             
         fi
      fi
else
     echo "Invalid username/password please try again "
fi

Tuesday, 12 August 2014

Find if a url is http or https


How to find if a url is http or https in a J2EE application ?

 This can be done using request.getScheme() 

This method is defined in ServletRequest interface from javax.servlet package inherited by HttpServletRequest. 
public java.lang.String getScheme(): Returns the name of the scheme used to make this request, for example, http, https, or ftp .

eg - 
  import javax.servlet.*;
 import javax.servlet.http.*;
 import java.io.*;  
 public class SchemeInfo extends HttpServlet { 
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
 { 
          res.setContentType("text/html"); PrintWriter out = res.getWriter();
         String str = req.getScheme(); 
         out.println("req.getScheme() : " + str); 
         out.close(); 
}

Thursday, 7 August 2014

PERL

What is PERL ?

PERL stands for Practical Extraction and Report Language .It is  used for mission critical projects in public and private sectors . 

Following are the features of  PERL - 
  • Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
  • Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.
  • Perl works with HTML, XML, and other mark-up languages.
  • Perl supports Unicode.
  • Perl is Y2K compliant.
  • Perl supports both procedural and object-oriented programming.
  • Perl interfaces with external C/C++ libraries through XS or SWIG.
  • Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN).
  • The Perl interpreter can be embedded into other systems.

Monday, 28 July 2014

Why hashmap key must be immutable?

HashMap is a data-structure where data is organized as key and values pairs. i.e. for every value there must be a  key to be produced to be stored into the hashmap.

Keys are normally generated using hashcode() method.

Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable.

I have already posted how to make objects immutable in one of my previous posts. 

Java Static Import

 Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.

The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface: An interface that only defines constants then writing a class implementing that interface, which is considered an inappropriate use of interfaces.

The mechanism can be used to reference individual members of a class:

import static java.lang.Math.PI;
import static java.lang.Math.pow;

or all the static members of a class -

import static java.lang.Math.*; 

For example, the class:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        System.out.println("Considering a circle with a diameter of 5 cm, it has:");
        System.out.println("A circumference of " + (Math.PI * 5) + " cm");
        System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + " sq. cm");
    }
}
Can instead be written as:

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + " cm");
        out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
    }
}


 

Sunday, 27 July 2014

What is JSESSIONID in J2EE Web application - JSP Servlet?

What is JSESSIONID in J2EE Web application - JSP Servlet? 

JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting. If Web server is using cookie for session management it creates and sends JSESSIONID cookie to the client and than client sends it back to server in subsequent http requests.

When JSESSIONID created in Web application?


  • In Java J2EE application container is responsible for Session management and by default uses Cookie.
  • If user request is served by Servlet than session is created by calling request.getSession(true) method. it accepts a boolean parameter which instruct to create session if its not already existed. if you call    request.getSession(false) then it will either return null if no session is associated with this user or return the associated HttpSession object.
  • If HttpRequest is for JSP page than Container automatically creates a new Session with JSESSIONID if this feature is not disabled explicitly by using page directive %@ page session="false" %>.
  • Once Session is created Container sends JSESSIONID cookie into response to the client. In case of HTML access, no user session is created. If  client has disabled cookie than Container uses URL rewriting for managing session on which jsessionid is appended into URL as shown below:           
  •  Ex. - https://localhost:8443/supermart/login.htm;jsessionid=1A530637289A03B07199A44E8D531427
  • When HTTP session is invalidated(), mostly when user logged off, old JSESSIONID destroyed and a new JSESSIONID is created when user further login.

ConcurrentAcessModification Exception Java

 

ConcurrentAcessModification Exception Java


This exception does not normally have anything to do with synchronization - it is normally thrown if a Collection is modified while an Iterator is iterating through it. AddAll methods may use an iterator - and its worth noting that the posh foreach loop iterates over instances of Iterator too.

Example - 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Test{
   
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1,"1");
        map.put(2,"2");
        map.put(3,"3");
        map.put(4,"4");
        map.put(5,"5");
        map.put(6,"6");
        Set keyset = map.keySet();
        Iterator iterator = keyset.iterator();
        while(iterator.hasNext()){
          System.out.println(map.get((Integer)iterator.next()));

          // Here you will get java.lang.ConcurrentAccessModification Exception.
            map.put(6,"6");
            map.put(7,"7");
          
        }
    }

}

 

Why we cant make class as private and protected

Why we cant make class as private and protected?

Private - 
What are other benefits you will get , if class declare as private ?
         Can we able to create object for private class from other class ? : No
         We cannot access the any of member (fields, methods ) of private class , then what is use of it ?



Protected-
If declared the class as protected - only via inheritance can access the fields and member , any other class who is not belong to protected class ( i.e . class is not inherited ) : it cont access any of fields and methods . 


Monday, 21 July 2014

Immutable objects - Java

Immutable Class - 

An immutable class is one whose state can not be changed once created


Rules/Guidelines to make a class immutable in java 


  •  Donot provide / remove all the setter methods of the member variables in the class
  •  Make the class as final . If we donot make it final child class can have setter implementation. 
  •  Make all the fields final and private 

import java.util.Date;

public final class ImmutableClass
{
 private final Integer test1;

 private ImmutableClass(Integer test1)
 {      this.test1 = test1;
 }
     public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
 {
  return new ImmutableClass(fld1, fld2, date);
 }

 //Provide no setter methods

 public Integer getTest1() {
  return test1;
 }