Thursday, November 15, 2012

Download mails from all Folders via IMAPS protocol

In previous post am mention about how download mails from gmail server

than new question occurs how download all mail from all folder like spam, important, sent, draft etc
first need to list out all folder exist in your mail account by this
Folder[] folder = store.getDefaultFolder().list("*");

output some thing like this
INBOX
Notes
Personal
Receipts
Travel
Work
[Gmail]/All Mail
[Gmail]/Drafts
[Gmail]/Important
[Gmail]/Sent Mail
[Gmail]/Spam
[Gmail]/Starred
[Gmail]/Trash

and than extract all mail from the folder and same mail in eml format see below code

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class test {


public static long start;

public static void main(String args[]) throws Exception {

 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", "--mail id--", "--password--");
  folder = store.getDefaultFolder().list("*");
  for (javax.mail.Folder folder1 : folder) {
            if ((folder1.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
                System.out.println(folder1.getFullName() + ": " + folder1.getMessageCount());
                folder1.open(Folder.READ_ONLY);
                for(Message msg : folder1.getMessages()){
                 
                 File ff = new File("C:/Desktop/mails", "msg/"+folder1.getFullName());
                 if(!ff.exists())
                  ff.mkdirs();
                 File emlFile = new File(ff.getAbsolutePath()+System.getProperty("file.separator")+msg.getHeader("message-id")[0].replace("<", "").replace(">", "")+".eml");
                 emlFile.createNewFile();
                 msg.writeTo(new FileOutputStream(emlFile));
                }
                
                if (folder1 != null) {
                    try {
                     folder1.close(true);
                    } catch (MessagingException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                    }
                   }
            }
        }
  
 } catch (Exception e) {
  // TODO: handle exception
  e.printStackTrace();
 } finally {
  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");
 }
 }

}

Saturday, November 10, 2012

Record Video And PlayBack In android

Let us know how record video with audio in andriod .

Firstly device must have in-built camera with device for that use a uses-feature tag in AndroidManifest file
<uses-feature android:name="android.hardware.camera" />

and some permission are required to use camera or write a file in External storage
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

android.view.SurfaceView hold the android camera object and android.media.MediaRecorder object records the video and audio and export the file in java.io.File In Android having two camera rear and front camera, which one can select, for that we use front camera ... by following code
CameraInfo cameraInfo = new CameraInfo(); 
int cameraCount = Camera.getNumberOfCameras();
if(cameraCount >1)
for ( int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++ ) { 
       Camera.getCameraInfo( camIdx, cameraInfo ); 
       if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT  ) { 
           try { 
            prCamera = Camera.open( camIdx ); 
           } catch (RuntimeException e) { 
               Log.i("Camera failed to open: ",e.getLocalizedMessage()); 
           } 
       } 
   }
In this example video encoded format is MPEG_4_SP, audio format is AMR_NB, and period of recording is 2 minutes and output file name create it by this function
String.valueOf(System.currentTimeMillis()) +".mp4"
after recording PlayVideo.java is used for play video file inside the android.widget.VideoView

Whole source of this post avaiable at my github Repository VideoRecording

Tuesday, November 6, 2012

Fetch Android Contact

How fetch contact in android ?
contact save in phone memory and also in sim memory . 
To fetch  list of contact, first add permission in android manifest file for read contact like this

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

in android all contact store in contact database for fetch need to fetch contact from database using cursor see sample code below
Cursor c = this.managedQuery(ContactsContract.Data.CONTENT_URI, null,
  Data.MIMETYPE + "=?", 
  new String[] { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE },
  null);
while (c.moveToNext()) {
 int type = c.getInt(c.getColumnIndex(Phone.TYPE));
 if (type == Phone.TYPE_MOBILE) {
  Log.i("contact name",c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME)));, 
  Log.i("contact number",c.getString(c.getColumnIndex(Phone.NUMBER)));
   }
  }
c.close();
In result,  you see all contact in logcat.

Send SMS in Android

How send sms from android ?
for this you must mention sms send permission in android manifest file like this
<uses-permission android:name="android.permission.SEND_SMS" />
after that use this code for send sms to a mobile number

try {
    smsManager.sendTextMessage("--here mobile number--", null, "--here sms text--", null, null);
    Log.d("Mobile", mobile + " message sent");
 } catch (Exception ex) {
    Log.d("Mobile", "Could not send message to " + mobile);
}
sms receive by mobile if proper network available and sufficient balance available

Sunday, November 4, 2012

titanium notification in iphone and android

ANDROID---create notification and click on notification lunch
//android
var intent = Ti.Android.createIntent( {
  action : Ti.Android.ACTION_MAIN,
  className : Ti.App.id+'activity_name', // activity_name that save inside build\android\bin\classes folder in titanium project
  packageName : Ti.App.id
});
intent.addCategory(Titanium.Android.CATEGORY_LAUNCHER);
var pending = Ti.Android.createPendingIntent( {
    activity : Ti.Android.currentActivity,
    intent : intent,
    type : Ti.Android.PENDING_INTENT_FOR_ACTIVITY,
    flags : Ti.Android.FLAG_ACTIVITY_NO_HISTORY
});
var dateValue = new Date();
var notification = Ti.Android .createNotification( {
         contentIntent : pending,
         contentTitle : '--Title of noticaification--',
         contentText : '----message would you want to show------',
         when : dateValue.getTime(), //show timing in  notification
         icon : Ti.App.Android.R.drawable.appicon,
         flags : Titanium.Android.ACTION_DEFAULT | Titanium.Android.FLAG_AUTO_CANCEL | Titanium.Android.FLAG_SHOW_LIGHTS
});
//Ti.Android.NotificationManager.notify(Math.floor(Math.random() * 32, 767), notification);
Ti.Android.NotificationManager.notify(1, notification);
IPHONE---create local notification and click on ok button relunch application
//iphone
var notification = Ti.App.iOS.scheduleLocalNotification({
  alertBody:'-----message would you want to show------',
  alertAction:"OK",
  sound:"default",
  userInfo:{},//pass value to other screen use this userInfo field
  date:new Date(new Date().getTime() + 3000)// 3 seconds after backgrounding
});
for recieve that data that would be pass though notication ..write this code
 Ti.App.iOS.addEventListener('notification', function(d) {
   Ti.API.info('data received = ' + JSON.stringify(d));
 });

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