Tuesday, 15 July 2014

JSP implicit objects

JSP implicit objects are created by container while translating JSP page to Servlet source to help developers. We can use these objects directly in scriptlets that goes in service method, however we can’t use them in JSP Declaration because that code will go at class level.
We have 9 implicit objects that we can directly use in JSP page. Seven of them are declared as local variable at the start of _jspService() method whereas two of them are part of _jspService() method argument that we can use.
  1. out Object
  2. request Object
  3. response Object
  4. config Object
  5. application Object
  6. session Object
  7. pageContext Object
  8. page Object
  9. exception Object
  1. out Object

    JSP out implicit object is instance of javax.servlet.jsp.JspWriter implementation and it’s used to output content to be sent in client response. This is one of the most used JSP implicit object and thats why we have JSP Expression to easily invoke out.print() method.
  2. request Object

    JSP request implicit object is instance of javax.servlet.http.HttpServletRequest implementation and it’s one of the argument of JSP service method. We can use request object to get the request parameters, cookies, request attributes, session, header information and other details about client request.
  3. response Object

    JSP response implicit object is instance of javax.servlet.http.HttpServletResponse implementation and comes as argument of service method. We can response object to set content type, character encoding, header information in response, adding cookies to response and redirecting the request to other resource.
  4. config Object

    JSP config implicit object is instance of javax.servlet.ServletConfig implementation and used to get the JSP init params configured in deployment descriptor.
  5. application Object

    JSP application implicit object is instance of javax.servlet.ServletContext implementation and it’s used to get the context information and attributes in JSP. We can use it to get the RequestDispatcher object in JSP to forward the request to another resource or to include the response from another resource in the JSP.
  6. session Object

    JSP session implicit object is instance of javax.servlet.http.HttpSession implementation. Whenever we request a JSP page, container automatically creates a session for the JSP in the service method.
    Since session management is heavy process, so if we don’t want session to be created for JSP, we can use page directive to not create the session for JSP using <%@ page session="false" %>. This is very helpful when our login page or the index page is a JSP page and we don’t need any user session there.
  7. pageContext Object

    JSP pageContext implicit object is instance of javax.servlet.jsp.PageContext abstract classimplementation. We can use pageContext to get and set attributes with different scopes and to forward request to other resources. pageContext object also hold reference to other implicit object.
  8. page Object

    JSP page implicit object is instance of java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.
  9. exception Object

    JSP exception implicit object is instance of java.lang.Throwable class and used to provide exception details in JSP error pages. We can’t use this object in normal JSP pages and it’s available only in JSP error pages.

For Example Refer my next post  

Monday, 14 July 2014

Servlets Vs CGI

Servlets Vs CGI 

Servlet CGI (Common Gateway Interface)

Servlets can link directly to the Web server. CGI cannot directly link to Web server.
Servlets can share data among each other. CGI does not provide sharing property.
Servlets can perform session tracking and caching of previous computations. CGI cannot perform session tracking and caching of previous computations.
Servlets are portable. CGI is not portable.
In Servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread. In CGI, each request is handled by a heavyweight operating system process.
Servlets automatically parse and decode the HTML form data. CGI cannot automatically parse and decode the HTML form data.
Servlets can read and set HTTP headers, handle cookies, tracking sessions. CGI cannot read and set HTTP headers, handle cookies, tracking sessions.
Servlets is inexpensive than CGI. CGI is more expensive than Servlets



Advantages of servlets over CGI
  • Request is run in a separate thread,so faster than CGIs
  • Scalable,can serve many more requests,
  • Robust and Object Oriented.
  • Can be written in Java Programming language.
  • Platform independent.
  • Access to Logging Capabilities.
  • Error handling and Security.

CGI -  
  • CGI creates a new process for each request Whereas Servlet creates a thread for each request and services the request in that thread.
  • For each process created by CGI the process is assinged seperate address space.SO there is memory overload on the server.Whereas for every thread created by the servlet no seperate address space is created all threads operate in the same parent process address space.so there is no memory overlaod.
  • CGI is not based on pooling Whereas servlet are container managed pooled objects.

Throw vs Throws in java

Throw vs Throws in java

1. Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance variable and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception andthrows clause is used in method declaration (signature).
for e.g.
Throw:

try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}

Throws:
public void sample() throws ArithmeticException{
 //Statements

.....

 //if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
 throw exp;
...
}
4. By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.
for e.g.
Throw:
throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException, 
ArrayIndexOutOfBoundsException

Send Email from Anonymous Id java

Send Email from Anonymous ID java 

Note - Pass your anonymous email id in from parameter of send mail .
Using this function you can also send file as well as have some one in CC

public static void sendEmail(String from ,String to,String cc, String subject, String text) throws IOException 
{
try 
{
Properties properties = new Properties();
String mailSmtpHost = "";
final String username = "";
final String password = ""
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "false");
properties.put("mail.smtp.host", mailSmtpHost);
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties,
 new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
 });
Message emailMessage = new MimeMessage(session);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
if(cc!=null && cc!=""){
emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
}
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setText(text);

        session.setDebug(true);

Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}


Friday, 11 July 2014

Direct Memory Access Java

Does Java Allow Direct Memory Access

Well, there is a sun.misc.Unsafe class. It allows direct memory access, so you can implement some magic like reinterpret casts and so on. The thing is you need to use hacky reflection approach to get the instance and this class is not realy well documented. In general you need a very good reason to use this kind of tool in production code.
Here's an example how to get it:

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
 
 
There are 105 methods, allowing different low-level stuff. These methods are devoted to direct memory access:
  • allocateMemory
  • copyMemory
  • freeMemory
  • getAddress
  • getInt - Gets you a value from the memory whose

 

Request Forward Vs Request SendRedirect

 Forward Vs SendRedirect

Forward transfers the control forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

Thursday, 10 July 2014

Learn how to trace an email address

Learn how to trace an email address

Trace an email address in the most popular programs like Microsoft Outlook, Hotmail, Yahoo, Gmail, AOL, by finding the header

What is an email header?

Each email you receive comes with headers. The headers contain information about the routing of the message and the originating Internet Protocol address of the message. Not all electronic messeges you receive will allow you to track them back to the originating point and depending on how you send messages determines whether or not they can trace an email address back to you. The headers don't contain any personal information. At most, the results of the trace with show you the origination IP and the computer name that sent the email. After viewing the trace information, the initiating IP can be looked up to determine from where the message was sent. IP address location information DOES NOT contain your street name, house number, or phone number. The trace will most likely determine the city and the ISP the sender used.

How do I get the header to start the trace email process?

Each electronic messaging program will vary as to how you get to the message options. I'll cover the basics to start the trace...the rest is up to you.
  • Outlook - Right click the message while it's in the inbox and choose Message Options. A window will open with the headers in the bottom of the window.
  • Windows Live - Right click the correspondence while it's in the inbox, choose Properties, then click the Details tab.
  • GMail - Open the correspondence. In the upper right corner of the email you'll see the word Reply with a little down arrow to the right. Click the down arrow and choose Show Original.
  • Hotmail - Right click the memo and choose View Message Source.
  • Yahoo! - Right click the note and choose View Full Headers.
  • AOL - Click Action and then View Message Source.
You can see that no matter the program, the headers are usually just a right click away.

I've got the header, now how do I start the trace?

The next step to trace an email address is to find the first IP listed in the header. This is most likely the IP initiating point. However, there are exceptions to this. You'll have to look at the information logically to deduce the originating IP.

Can you trace any email address?

Yes and No. For example, someone who sends a message to your hotmail account shows in the X-Originating IP section of the headers. However, someone who sends you a message from GMail will ONLY trace back to Google IP addresses.
We've got more information in our Trace An Email forum

Wednesday, 9 July 2014

Method Overidding vs Method Overloading

Difference between overloaded methods and overidden methods in Java



Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for co-variant returns
Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change Must not make more restrictive (can be less restrictive)
Invocation Reference type determines which overloaded version is selected. Happens at compile time. Object type determines which method is selected. Happens at run-time.

Abstraction Vs Encapsulation

 Difference  between Abstraction and encapsulation 

  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs. 
eg . Interface and the class implementing the interface 

eg . public interface ABC {
             void display();
}

Here abstraction is provided by the interface meaning it will be the face of the class implementing the interface ABC

Encapsulation can be done as 

public class DEF implements ABC{
             void display(){
                    System.out.println("DEF");
             }
}

In the above example 

Inteface ABC provides abstraction , while class DEF provides encapsulation i.e. binding the data and the code together.

REST Basic Definitions

What is REST ?

  •  REST stands for  Representational State Transfer.
  • REST is an architectural style which is based on web-standards and the HTTP protocol. 
  • REST was first described by Roy Fielding in 2000.
  • In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods.
  • In a REST based architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modifies the REST resources.
  • Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).
  • REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation). 

 

Friday, 4 July 2014

Stack Versus Heap in Java


Difference between Stack and Heap memory in Java

Stack - 

          Stack is a memory area where we store local variables , function calls,current location of execution i .e .Program Counter value.
        Stack follows the procedure of First In Last Out (FILO)i.e.  object/function call that is last inserted into stack will be taken first for further execution . 
     e.g 
          void a(){
                    b();
                    c();
         }

     In this case the stack will contain the following things - 



       On completion of c it will start executing b from the point it left and finally a will execute after b completes its execution.

Heap  - 

          Heap is a memory area where we store objects created by the program.


void somefunction( )
{
/* create an object "m" of class Member
    this will be put on the heap since the 
    "new" keyword is used, and we are 
   creating the object inside a function
*/
  
  Member m = new Member( ) ;
  
  /* the object "m" must be deleted
      otherwise a memory leak occurs
  */

 
} 


This will create an object on the heap.




   

Wednesday, 2 July 2014

Java annotation

Java annotations


A java annotation in any language is a form of syntactic metadata that can be added to the java source code.

There are following types of annotations in Java - 

Annotations applied to Java code:

  • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.
  • @SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics varargs parameter, since Java 7.
  • @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface, since Java 8.

Annotations applied to other annotations:
  • @Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at runtime through reflection.
  • @Documented - Marks another annotation for inclusion in the documentation.
  • @Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
  • @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
  • @Repeatable - Specifies that the annotation can be applied more than once to the same declaration.

Tuesday, 1 July 2014

Active Directory Basics

Active Directory -

              It is a centralized database system which contains people / user's information which can be used to authenticate them.Active directory not only contains people information but it can have computer's and other resources' information in it which can be used to authenticate users/services  using these.  Most IT administrators use Active directory to maintain order in the organization. In other words it is used to implement the AAA protocol i.e. Authorization , Authentication and Accounting

Authorization - As the name suggested it is the process of verifying if the person is legitimate to access the resource.

Authentication - It is the process to verify the identity of the person.

Accounting - It is the process of documenting that the authorized & authenticated person has accessed the resource.

Core components of Active Directory -


Domain controller -  Every active directory has at-least one domain controller .  A domain controller takes care of managing the Active Directory, authentication , authorization and accounting of the users in Active Directory including its database hosting . Most Active Directory structure implement using Windows 2003 server but now there is a clean shift of focus towards Windows 2008 server

Fig below shows the organization of data in Active Directory 

      







            Fig(a) Organization of data in Active Directory (pic credits :- check here)







Object :- Everything that the Active Directory manages is called as objects. An object may be  a user, a system , a service  or a resource that may be tracked by the Active Directory


Forests :-  Forests are at the top of the hierarchy. It contains all the attributes and their syntax.

Domain Component :- These are the collections of computers/resources linked through policies , users or any other attribute in the Active Directory.It creates a copy of every server based activity.

Organizational Units (OU) :- OU are combination of various domains.It is used for grouping domains that may be tightly coupled with each other. By using OU a network adminstrator can configure different users based on different user policies.

Domain Component(DC) :- A DC can be used to classify different types of users based on role. For ex people with  manager role may belong to DC as manager , whereas,  people with employee role may  belong to employee-DC.

Common Name (CN):-  A common name may contain values such as first name,last name etc.

Distinguished Name (DN) :-  A distinguished name may contain values such as user Id .

Apart from these commonly used components there are other supported components such as password and other components

Accessing an object in Active Directory 

For accessing an object in Active Directory you need to use the fully qualified namespace of the object

Typically an object namespace may be like - 

CN=Sandesh,CN=Mutha,DN=smutha,DC=blogger,DC=com,OU=Technology

Links to refer 
  1.  WordPress
  2.  Technet.Microsoft.com




         



Configure Session timeout in Servlet - Web.xml

Configure Session Timeout in Servlet - Web.xml 


The session timeout can be configured in two ways - 


1. Specify the session timeout in (web.xml)


You need to use session-config tag in web.xml. Specify the session timeout in minutes in session-config . 

This is how you can do it.


             <web-app ...>
                    <session-config>
                            <session-timeout>20</session-timeout>
                    </session-config>
             </web-app>
 
This will kill the servlet container on 20 minutes of inactive session . 
 
 

2. Timeout with setMaxInactiveInterval()

 
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(20*60);
 
The above setting is only apply on session which call the “setMaxInactiveInterval()” method, and session will be kill by container if client doesn’t make any request after 20 minutes.
 
Note - Here the interval is in seconds