Thursday, April 25, 2013

cURL in PHP to access HTTPS (SSL/TLS) protected sites

The problem


From PHP, you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP, FTP, LDAP.

If you simply try to access a HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. Say you have the following code: (Error handling omitted for brevity)

// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);

If $url points toward an HTTPS resource, you’re likely to encounter an error like the one below:

Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

The quick fix


There are two ways to solve this problem. Firstly, we can simply configure cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view, but if you’re not passing sensitive information back and forth, this is probably alright. Simply add the following line before calling curl_exec():


curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Wednesday, April 24, 2013

Use Android’s ContentObserver in Your Code to Listen to Data Changes such as contact change.

ContentObserver make some work easier, such if you want to track by your own sdk application suppose when your contacts being changed, you can easily do that.

To use the ContentObserver you have to take two steps:
  • Implement a subclass of ContentObserver
  • Register your content observer to listen for changes 

Implement a subclass of ContentObserver

ContentObserver is an abstract class with no abstract methods. Its two onChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.
Since Google added one of the two overloaded onChange() methods as recently as API-level 16, this method’s default behavior is to call the other, older method.
Here is, what a normal implementation would look like:

class MyObserver extends ContentObserver {       
   public MyObserver(Handler handler) {
      super(handler);           
   }

   @Override
   public void onChange(boolean selfChange) {
      this.onChange(selfChange, null);
   }       

   public void onChange(boolean selfChange, Uri uri) {
      System.out.println("HMM");
   }       
}

Also notice the Handler parameter in the constructor. This handler is used to deliver the onChange() method. So if you created the Handler on the UI thread, the onChange() method will be called on the UI thread as well. In this case avoid querying the ContentProvider in this method. Instead use an AsyncTask or a Loader.
If you pass a null value to the constructor, Android calls the onChange() method immediately – regardless of the current thread used. I think it’s best to always use a handler when creating the ContentObserver object.

Register your content observer to listen for changes

To register your ContentObserver subclass you simply have to call the ContentResolver's registerContentObserver() method:

getContentResolver().registerContentObserver(Phone.CONTENT_URI, true, new MyObserver(null));

It takes three parameters. The first is the URI to listen to. I cover the URI in more detail in the next section.
The second parameter indicates whether all changes to URIs that start with the given URI should trigger a method call or just changes to exactly this one URI. This can be handy for say the ContactsContract URI with its many descendants. But it can also be detrimental in that the actual change, that caused the method call, is even more obscure to you.
The third parameter is an instance of your ContentObserver implementation.

 

Tuesday, April 23, 2013

Android sdk create and update and delete contact

The following permissions need to handle contacts on android application:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> 

And import of 
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
are also important.
 
/* CREATE A NEW CONTACT */
String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.Contacts.STARRED,
        ContactsContract.Contacts.TIMES_CONTACTED,
        ContactsContract.Contacts.CONTACT_PRESENCE,
        ContactsContract.Contacts.PHOTO_ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER,
    };
ArrayList<ContentProviderOperation> ops5 = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops5.size();

Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_TYPE, null);
builder.withValue(RawContacts.ACCOUNT_NAME, null);
ops5.add(builder.build());

// Name
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Pritom"+ " " +"Kumar");
ops5.add(builder.build());

// Number
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "01727499452");
builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
ops5.add(builder.build());

// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(r.getPhoto()));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
    builder.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}

// Add the new contact
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops5);
}
catch (Exception e)
{
    e.printStackTrace();
}
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" +Pritom+ " " +"Kumar"+ "\" )";
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(c);

if (c.moveToNext())
{
    System.out.println("NEW ID: "+c.getString(0));
}

/* UPDATE CONTACT BY RAW ID */
int id = 2;
String firstname = "Pritom";
String lastname = "Kumar";
String number = "01727499452";
String photo_uri = "android.resource://com.my.package/drawable/default_photo";

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

// Name
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE});
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastname);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstname);
ops.add(builder.build());
// Number
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?"+ " AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)});
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
ops.add(builder.build());
// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(photo_uri));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);

    builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
    builder.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (Exception e)
{
    System.out.println(e.getMessage());
}

/* DELETE CONTACT BY RAW CONTACT ID AND CONTACT ID */
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID +" = ?", new String[]{"3"}, null);
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{"3"}, null);
while (pCur.moveToNext())
{
    String lookupKey = pCur.getString(pCur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
    getContentResolver().delete(uri, null, null);
}

Android how to use ContactsContract to retrieve phone numbers and email addresses

ContactsContract is the contract between a contacts provider and applications 
that want to use contacts. The following code shows how to find a contact based on 
name, and once it's found, how to retrieve the various types of phone numbers and 
email addresses:
 
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;  
 
String NAME = "Pritom Mondal";
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
 String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
 Cursor phones = managedQuery(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
 while (phones.moveToNext()) {
  String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
  int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" NUMBER: "+number);
 }
 phones.close();
 
 Cursor emails = managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID + " = " + contactId, null, null);
 while (emails.moveToNext()) {
  String number = emails.getString(emails.getColumnIndex(Email.DATA));
  int type = emails.getInt(emails.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" EMAIL: "+number);
 }
 emails.close();
}
cursor.close();

How to read android sim contacts and phone contacts separately

The <uses-permission> should be contained in the <manifest> element. See Structure of the Manifest File. So trying putting it before <application>.
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
 

try {
    	String[] PROJECTION=new String[] {Contacts._ID,
    	        Contacts.DISPLAY_NAME,
    	        Phone.NUMBER
    	    };
    	Cursor c = managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
    	if (c.moveToFirst()) {
    		String ClsPhonename = null;
            String ClsphoneNo = null;
            do 
            {
                ClsPhonename = c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME));
                ClsphoneNo = c.getString(c.getColumnIndex(Phone.NUMBER));
                System.out.println(c.getString(c.getColumnIndex(Contacts._ID)));

                ClsphoneNo.replaceAll("\\D", "");
                ClsPhonename=ClsPhonename.replaceAll("&", "");
                ClsPhonename.replace("|","");
                String ClsPhoneName=ClsPhonename.replace("|","");
                System.out.println("Name: "+ClsPhoneName);
                System.out.println("Phone: "+ClsphoneNo);
            } while(c.moveToNext());
    	}
    	
    	
    	Uri simUri = Uri.parse("content://icc/adn"); 
        Cursor cursorSim = this.getContentResolver().query(simUri,null,null,null,null);
        String ClsSimPhonename = null; 
        String ClsSimphoneNo = null;
        while (cursorSim.moveToNext()) 
        {      
            ClsSimPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
            ClsSimphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
            ClsSimphoneNo.replaceAll("\\D","");
            ClsSimphoneNo.replaceAll("&", "");
            ClsSimPhonename=ClsSimPhonename.replace("|","");
                System.out.println("SimContacts"+ClsSimPhonename);
                System.out.println("SimContactsNo"+ClsSimphoneNo);

        }
    } catch (Exception ex) {
    	System.out.println(ex.getMessage());
    	ex.printStackTrace();
    }

Create an Android Emulator SD Card and Write Data To It

Create the SD Card...

For instance, if you want to load MP3 files on a “real” Android phone, you’ll probably insert an SD card into the phone. The emulator can emulate this, but you need to jump through a few hoops:
Let's create a 64MB sd card for our Android emulator, shall we?
Linux
From a terminal...
# cd ~/android-sdk-linux/tools
# ./mksdcard 64M ~/Desktop/sdcard.iso
Windows XP
From a DOS prompt...
Actually where is your android-sdk-windows exists.
cd C:\Program Files\android-sdk-windows\tools
mksdcard 64M c:\documents and settings\tyler\desktop\sdcard.iso
Now you can use the 'Eclipse Android SDK and AVD Manager' to create a new android virtual device that can use the path to the sd card you created.

Write Data to the SD Card...

Linux
From a terminal...
# cd ~/android-sdk-linux/tools
# ./ddms
Windows XP
From a DOS prompt...
cd C:\Program Files\android-sdk-windows\tools
ddms
This will start the Dalvik Debug Monitor Server. Next...
  1. Launch your AVD with SD card from Eclipse that you created earlier
  2. From DDMS, go to 'Device -&gt; File Explorer' 
  3. Select the 'sdcard' folder
  4. Click the 'push file onto device' button
  5. Find your file and click open
That's it!
Now from inside your code you can get to the sd card's path with: Environment.getExternalStorageDirectory()

Grails get view.gsp file output to a string variable

def formValueHtml = g.include(view: "pdf/customerAndInvoiceProductDetails.gsp", model: [
      invoiceProductInstance: invoiceProductInstance,
      invoiceInstance: invoiceInstance,
      customerInstance: customerInstance
]);

Where  customerAndInvoiceProductDetails.gsp is a view file.
And  invoiceProductInstance is data object.