Wednesday, October 31, 2012

Log4j create separate log files

In apache tomcat, by default create log files of every event performed in server
and lot web-project deploy on server and all log merge in one log
So how create separate log file for each project


the apache provide log4j library for logging in java by using  this library we easily track event by log object


need to download latest log4j jar file from this link http://logging.apache.org/
add this jar file in classpath
and create a log4j.properties file where we mention about


#Set root category priority to All(info,debug, error, info etc) and its only appender to File
log4j.rootCategory=DEBUG, Cust_Error

#daily rolling log file
log4j.appender.Cust_Error=org.apache.log4j.DailyRollingFileAppender
#create log file apache log folder
log4j.appender.Cust_Error.File=${catalina.home}/logs/SaralHiring.log
#date format ,appends for previous dated log file
log4j.appender.Cust_Error.DatePattern='.'yyyy-MM-dd
log4j.appender.Cust_Error.Append=true
log4j.appender.Cust_Error.Encoding=UTF-8
#if only track error
log4j.appender.Cust_Error.Threshold=ERROR
#for particular pattern message in log
log4j.appender.Cust_Error.layout=org.apache.log4j.PatternLayout
log4j.appender.Cust_Error.layout.ConversionPattern=%d [%-5p] [%t]: [%C{1}] %m%n


in java program

first declare the log object like this

private static final org.apache.commons.logging.Log  log = org.apache.commons.logging.LogFactory.getLog(Home.class);

than call below methods
log.trace("");
log.debug("");
log.info("");
log.warn("");
log.error("");
log.fatal("");

Multithreaded Download mail from gmail server in eml format


am find lot of example to download mail from gmail server using imap protocal , but those are single thread that's takes more time , am modify those code and create this to increase time optimization

take look over the code and leave comment to make more efficient


package helper;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.AndTerm;
import javax.mail.search.BodyTerm;
import javax.mail.search.FlagTerm;


public class multithread {

 /**
  * @param args
  */

 private static Object bb = new Object();
 private static Message[] msgs;
 private static int completed = 0;
 public static long start;
 public static void main(String args[]) throws Exception {

  msgs = null;
  Store store = null;
  Folder folder = null;
  try {
   start = System.currentTimeMillis();
  Properties props = System.getProperties();
  props.setProperty("mail.store.protocol", "imaps");
  Session session = Session.getDefaultInstance(props, null);
  session.setDebug(true);
  store = session.getStore("imaps");
  store.connect("imap.gmail.com", "--gmail id--", "--password--");
  folder = store.getDefaultFolder();
  if (folder == null) {
   throw new Exception("No default folder");
  }
  folder = folder.getFolder("INBOX");
  if (folder == null) {
   throw new Exception("No IMAP INBOX");
  }
  folder.open(Folder.READ_WRITE);

  //unread mail flag
  FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
  BodyTerm bt =  new BodyTerm("Sales"); // that keyword which you want to search in mail 
  msgs = folder.search(new AndTerm(bt, ft));
  if(msgs.length!=0){
  ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(msgs.length);
  executorService.prestartAllCoreThreads();
  for(Message m : msgs){
   executorService.execute(new Runs(m));
  }
  executorService.shutdown();
        executorService.awaitTermination(10000, TimeUnit.SECONDS);
  }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  } finally {
   int i=0;
   while(msgs.length!=completed){
    try{
     synchronized (bb) {
      System.out.println("wait for 300 millisecond "+i);
      bb.wait(300);
      i++;
     }
    }catch (Exception e) {
     // TODO: handle exception
     e.printStackTrace();
    }
   }
   if (folder != null) {
    try {
     folder.close(true);
    } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (store != null) {
    try {
     store.close();
    } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
    long end = System.currentTimeMillis() - start;
       System.out.println("--- Done: , end: " + end + "ms");
  }
  
 }

 private static class Runs implements Runnable{

  private Message file;
  
  public Runs(Message m) {
   this.file = m;
  }
  @Override
  public void run() {
   // TODO Auto-generated method stub
   try{
   System.out.println("downloading startsssss ");
   File emlFile = new File("C:/Documents and Settings/india/Desktop/emlss/msg"+file.getHeader("message-id")[0].replace("<", "").replace(">", "")+".eml");
   System.out.println(emlFile.getAbsolutePath());
   emlFile.createNewFile();
   file.writeTo(new FileOutputStream(emlFile));
   completed++;
   synchronized (bb) {
    bb.notifyAll();
   }
   }catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
   }
  }
  
 }
}


Sunday, October 14, 2012

Change Background of Android ToggleButton on check state change

How you change background of Toggle Button when you toggle the check state of button ?



using selector in android

see example of background.xml



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bar2_02" android:state_checked="true"/>
    <item android:drawable="@drawable/bar2_01" android:state_checked="false"/>
    <item android:drawable="@drawable/bar2_01"></item>
</selector>




for call this selector xml(background.xml) in toogle button



<ToggleButton
                android:id="@+id/sbar2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/background.xml"
                android:button="@null"
                android:textOff=""
                android:textOn="" />



on click set border in android view (button/imageview) by using drawable xml


lot of time we using different drawable to show effect on press event in android. for example when we press a icon/button/imageview, want to set some border outside the image,



  • You have to use layer-list, when android:state_pressed become ture , one for bitmap(image) and another for border using android shape
  • when android:state_pressed become false or normal state of view, using drawable 




sample background.xml



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <layer-list>
            <item>
                <bitmap android:gravity="center" android:src="@drawable/ic_launcher" android:tileMode="repeat" />
            </item>
            <item>
                <shape>
                     <solid android:color="#00000000" />
         <corners android:radius="3dp" />
         <stroke android:color="#FEA900" android:width="1dp" />
                </shape>
            </item>
        </layer-list>
    </item>
    <item android:drawable="@drawable/ic_launcher" android:state_pressed="false"/>
    <item android:drawable="@drawable/ic_launcher"></item>
</selector>



and how to used this background.xml see below button xml


<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/background" />

see the sample video :- http://screencast.com/t/vtI10uAC