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;
 }


Tuesday, 15 July 2014

How to use implicit objects in JSP


Example of how to use implicit objects in JSP


<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ page import="java.util.Date" %>
<!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=US-ASCII">
<title>Index JSP Page</title>
</head>
<body>
<%-- out object example --%>
<h4>Hi There</h4>
<strong>Current Time is</strong>: <% out.print(new Date()); %><br><br>
 
<%-- request object example --%>
<strong>Request User-Agent</strong>: <%=request.getHeader("User-Agent") %><br><br>
 
<%-- response object example --%>
<%response.addCookie(new Cookie("Test","Value")); %>
 
<%-- config object example --%>
<strong>User init param value</strong>:<%=config.getInitParameter("User") %><br><br>
 
<%-- application object example --%>
<strong>User context param value</strong>:<%=application.getInitParameter("User") %><br><br>
 
<%-- session object example --%>
<strong>User Session ID</strong>:<%=session.getId() %><br><br>
 
<%-- pageContext object example --%>
<% pageContext.setAttribute("Test", "Test Value"); %>
<strong>PageContext attribute</strong>: {Name="Test",Value="<%=pageContext.getAttribute("Test") %>"}<br><br>
 
<%-- page object example --%>
<strong>Generated Servlet Name</strong>:<%=page.getClass().getName() %>
 
</body>
</html>