Thursday, May 26, 2011

Log4j - Email errors using Gmail

Most of the small projects doesn't have a dedicated person to monitor log file all the times, and its handy to send these errors as email to an email list.

Pros

  1. Never miss an error.
  2. Delete Emails which you want to ignore because of invalid inputs or connectivity issues etc.
  3. Proactively identify bugs and fix them.
  4. Email list is handy i.e. multiple person can receive emails.
  5. If you have different modules in your project and different teams work on them, adding a Labels to your log can by handy since most of the Email Servers can Label emails and redirect them to different folders.
Cons
  1.    Sending email from code takes few seconds, workaround is the create Logger wrapper which logs in a separate thread.

log4j.properties

log4j.rootLogger=ERROR, gmail
log4j.appender.gmail=org.apache.log4j.net.SMTPAppender
log4j.appender.gmail.SMTPProtocol=smtps
log4j.appender.gmail.SMTPUsername=username@gmail.com
log4j.appender.gmail.SMTPPassword=password
log4j.appender.gmail.SMTPHost=smtp.gmail.com
log4j.appender.gmail.SMTPPort=465
log4j.appender.gmail.Subject=Some subject line
log4j.appender.gmail.To=username@gmail.com
log4j.appender.gmail.From=email-list@gmail.com
log4j.appender.gmail.layout=org.apache.log4j.PatternLayout
log4j.appender.gmail.layout.ConversionPattern=%d{MM/dd/yyyy HH:mm:ss}  [%M] %-5p %C - %m%n
log4j.appender.gmail.BufferSize=10


Required Jar files

Activation  download from here

Sample Code

public class Log4jGmailDemo {

    public static void main(String[] args) {
        try {
            int z = 4 / 0;
        } catch (RuntimeException re) {
            logger.error("Module-1", re);
        }
    }
    static Logger logger = Logger.getLogger(Log4jGmailDemo.class);
}

This is only if you are interested using Threads 


public class CustomLogger extends Logger {

    public CustomLogger(String clazz) {
        super(clazz);
    }

    @Override
    public void error(Object message) {
        Runnable runnable = new LoggerRunnable(this, message, null);
        LogExecutor.getInstance().execute(runnable);
    }

    @Override
    public void error(Object message, Throwable throwable) {
        Runnable runnable = new LoggerRunnable(this, message, throwable);
        LogExecutor.getInstance().execute(runnable);
    }

    public static Logger getLogger(Class clazz) {
        return new CustomLogger(clazz.getSimpleName());
    }
}

class LogExecutor {

    private static LogExecutor executor = new LogExecutor();

    private LogExecutor() {
    }
    private ExecutorService service = Executors.newFixedThreadPool(5);

    public static LogExecutor getInstance() {
        return executor;
    }

    public void execute(Runnable runnable) {
        service.execute(runnable);
    }
}

class LoggerRunnable implements Runnable {

    private Logger logger;
    private Object message;
    private Throwable throwable;

    public LoggerRunnable(Logger logger, Object message, Throwable throwable) {
        this.logger = logger;
        this.message = message;
        this.throwable = throwable;
    }

    @Override
    public void run() {
        logger.error(message, throwable);
    }
}

Sample Usage



public class Log4jGmailDemo {

    public static void main(String[] args) {
        try {
            int z = 4 / 0;
        } catch (RuntimeException re) {
            logger.error("Module-1", re);
        }
    }
    static Logger logger = CustomLogger.getLogger(Log4jGmailDemo.class);
}

Wednesday, May 25, 2011

Data Types in Java

Session 1 - Data Types in Java

What is Data ?
 Most of you have shopped online and this is what a typical purchase looks like

  1.     You select a product which has a Price, Tax, Quantity
  2.     You pay using your Credit Card by entering Name, CC Number, Expiration Date, Billing    Address, Zipcode
Words above in Bold are data.


What is then Data Type ?
   Can we say Price, Tax, Quantity is of type Number because we can apply Arithmetic (+, -, /, *, %) Operations on them, i.e. we multiply Price Quantity and than add Tax.
Similarly Your Name, Address are text because it doesn't make sense to have Arithmetic Operation on them and in Java we call them String.



Supported Data Types in Java
  String   -  Text
  double  - Real Numbers i.e. 33.2, 20.0 etc
  int         - Non-Real Numbers i.e. 10, 30, 3453 etc



Typical Java Programs using the above Data Types

public class DataTypesDemo {
    public static void main(String[] args) {

        // define a Data Variable message of type String
        String message = "Hello World!";
        
        // print to console i.e. black screen
        System.out.println(message);
    }
}

        Code Snippet - 1

        // define a Data Variables of type int
        int x = 10;
        int y = 20;
        int z = x + y;
        // print to console i.e. black screen
        System.out.println(z);

        Code Snippet - 2
       // define a Data Variables of type int
        double x = 10.0;
        double y = 20.0;
        double z = x + y;
        // print to console i.e. black screen
        System.out.println(z);
  
Question for you.
  what type is Phone No. (i.e. int or String) ?
    Its String since you will never apply Arithmetic Operations on it.

Homework
There are few others Data Types which I missed that can be found in any book. 

Saturday, May 21, 2011

How I teach Java in 1hr 5 sessions

I know a lot of people can disagree with this but I am trying to keep it simple and as only my own opinion.

It took me more than 5 yrs to design this syllabus to help beginners learn and get motivated to program in Java. When I started teaching I use to take 10-15 days to teach java and I can clearly see on participants faces that they were not confident even after spending so much time with them. However recently I was able to successfully use a shorter And I am sure this won't be the final one and it will change a lot after few more batches. And the only way I do this is by
focusing on important concepts and cutting dumb one's in a language to accomplish my objectives.

Session 1
  1.   Data Types (int, double, String )  Class Notes
  2.   Operators (Arithmatic - +,-,*,/ )
  3.   Functions
  Homework -

  •  Write 50 functions and execute them from main method            
  •  Write functions with 0 or more input parameters
  •  Write functions that returns a value



Session 2 (Point here is to introduce Objects early and not to bullshit with amazing powers of Object, keep it simple)
  1.   Introduce Class and Objects 
  2.   Introduce Java Beans Classes (i.e. Objects with only Data) 
  3.   Introduce Classes with only functions (i.e. Service Layer or Business Logic Classes)
  4.   Introduce ArrayList (i.e. Object with data and logic to operate on it)
  5.   Summary - We mostly use Object in the above three ways.
  Homework -

  •  Write 20 Java Beans classes              
  •  Write some classes which operates on the above classes as Service Layer or Business Logic


 Session 3 (Write Simple Applications)
  1.  ContactApp - Contact Java Bean class and ContactService with ArrayList to add and getAll functions
  2.   FeedbackApp - Feedback.java bean and FeedbackService for add and getAll
  3.  RegistrationApp
 Session 4 (Try writing more simple applications, introduce interface)
  1.   Introduce Interfaces
  2.   Introduce Map, HashMap, List, ArrayList, Set, HashSet
  3.   Start writing interfaces for Service classes introduced in Session-2 & Session-3
  Homework

  •    Exception handling              
  •    Write 5 small two class apps


 Session 5 (Write more small apps and introduce control and loop statements)
  1.    Introduce Control and Loop statements
  2.    Build 3 small apps with 2 Java Beans, Interface and Implementation
    Homework - Learn from the book (Arrays, Generics, Annotations)


  

Thursday, May 19, 2011

How to Schema Validate Metro SOAP Request


@SchemaValidation does the trick checkout the sample code below

package com.palm.appstore.wsc;


import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import com.sun.xml.ws.developer.SchemaValidation;

/**
*
* @author Intesar Mohammed
*/
@WebService(serviceName = "Echo")
@SchemaValidation
public class Echo {

    /** This is a sample web service operation */
    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "no") int txt) {
        return "Hello " + txt + " !";
    }
}

Valid Request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsc="http://wsc.appstore.palm.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <wsc:hello>
         <no>33</no>
      </wsc:hello>
   </soapenv:Body>
</soapenv:Envelope>

Response
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:helloResponse xmlns:ns2="http://wsc.appstore.palm.com/">
         <return>Hello 33 !</return>
      </ns2:helloResponse>
   </S:Body>
</S:Envelope>

InValid Request without @SchemaValidation
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:helloResponse xmlns:ns2="http://wsc.appstore.palm.com/">
     <!â��missing no element -- >
      </ns2:helloResponse>
   </S:Body>
</S:Envelope>


Response
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:helloResponse xmlns:ns2="http://wsc.appstore.palm.com/">
         <return>Hello 0 !</return>
      </ns2:helloResponse>
   </S:Body>
</S:Envelope>

InValid Request with @SchemaValidation
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:helloResponse xmlns:ns2="http://wsc.appstore.palm.com/">
     <!â��missing no element -- >
      </ns2:helloResponse>
   </S:Body>
</S:Envelope>

Response (Auto Validated)
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Client</faultcode>
         <faultstring>org.xml.sax.SAXParseException: cvc-complex-type.2.4.b: The content of element 'wsc:hello' is not complete. One of '{no}' is expected.</faultstring>
  ---
</s:Envelope>