22 October 2014

Google Maps Android API v2 Key

In here i will explain how to generate android goggle map v2 API key for android application.First You have to generate SHA-1 finger print.For that you use terminal.


keytool -list -v -keystore C:\Users\<username>\.android\debug.keystore -storepass android -keypass android














Then you can see SHA-1 is printing.Then go to here(https://code.google.com/apis/console/?noredirect) and create new project.Then go to API access and click the create new android key button.Then add your sha-1 finger print;packagename and genarate key.

Ex :-AC:C7:99:64:B7:9B:C8:25:53:6D:B2:2F:79:59:59:F9:37:1B:AF:A4;com.example.appname

com.example.appname is your android project package name.Then you can see there is key generated.You can use this key for your application.

Android Volley library json parse example

In this post i will describe how to use android volley library for your json request.First you have to download android volley library.I have uploaded this sample projcet to github so you can download volley.jar file from here(https://github.com/sajith4u/Android_volley_Sample/tree/master/Android_Volley/libs).Or you can download from here(https://drive.google.com/?tab=jo&authuser=0#folders/0B6boUJ62bUIXZUJQbUdoS08tMms).First You have to add AppController class to your package.Befor that make sure you have put volley.jar file in to your lib folder.
package com.example.Android_Volley;

import android.app.Application;

import android.text.TextUtils;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.Volley;


public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override

    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;

    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }


    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {

        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

Then You have to Add this class to your manifest file.So inside the Application tag put the name of class.
<application android:label="@string/app_name"

                 android:icon="@drawable/ic_launcher"

                 android:name="com.example.Android_Volley.AppController">

        <activity android:name="MyActivity"

                  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>

        </activity>

    </application>

And also make shure add internet permission in to your application.
 <uses-permission android:name="android.permission.INTERNET"/>

Then inside main activity i have one button and when i click button it will read json object and show in to textview.I have used this public json call to show demo.(http://time.jsontest.com/) it will return date, time and other parameter inside json object.

date:- String
mili seconds :- Double
time:- String

when button clicked it called to this method.
   

    private void makeJsonObjectRequest() {

        showpDialog();

       JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,

                urlJsonObj, null, new Response.Listener<JSONObject>() {

            @Override

            public void onResponse(JSONObject response) {

                try {                    

                 String time = response.getString("time");

                 Double mili = response.getDouble("milliseconds_since_epoch");

                 String date = response.getString("date");

                 jsonResponse = "";

                 jsonResponse += "Time: " + time + "\n\n";

                 jsonResponse += "seconds: " + mili + "\n\n";

                 jsonResponse += "Date: " + date + "\n\n";

                 txtResponse.setText(jsonResponse);

                } catch (JSONException e) {

                    e.printStackTrace();

                    Toast.makeText(getApplicationContext(),

                            "Error: " + e.getMessage(),

                            Toast.LENGTH_LONG).show();
                }

                hidepDialog();

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

            Toast.makeText(getApplicationContext(),

                   error.getMessage(), Toast.LENGTH_SHORT).show();                

                hidepDialog();
            }

        });        

        AppController.getInstance().addToRequestQueue(jsonObjReq);

    }


In this method hideDialog and showDialog methods used to add progressDialog.



21 October 2014

Maven Installation guide

In this Thread i am going to how to use maven.First i will give you what is Maven.Maven is open source Building tool.it is distributed by Apache.If you really new with software development cycle i will tell why we want to use building tool.In software development cycle there are five main development cycles.Planing,Implementation,testing and documenting and Deployment and Maintenance are the development process.So when you build some product there may be bugs,errors.So you have to give the Quality output to your customer.So then you have to testing and development except most bugs fixed.So it is high cost for fixed errors and rebuild.So that's why we used building tool for make easier  our development process.Using Building tool we can test application,documentation easier.

How to install MAVEN in to windows

1 Step :
Download the maven using this url
(http://maven.apache.org/download.cgi)  and extract the zip file in any drive in your machine.

2 Step :
Download and install java in to your machine.

3 Step :
Set Path variables for java and maven.




4 Step:
Check maven is installed properly.


Thanks

Java card Helloworld Applet

This article I will describe how to create java card hello world applet.You have to have
   1.Contact or contact reader
   2.Java card
   3.Eclipse with java card development kit.


First you have to knowledge about how the APDU commands are working in java card.This is the Apdu standard format.




In my example I used CLA value as 80 and INS value as 00 and P1 and P2 are 00,00.The requested format is 80000000.


import javacard.framework.APDU;

import javacard.framework.Applet;

import javacard.framework.ISO7816;

import javacard.framework.ISOException;

import javacard.framework.Util;

public class HelloworldApplet extends Applet {

private static final byte[] helloWorld = { (byte) 'H', (byte) 'e',

(byte) 'l', (byte) 'l', (byte) 'o', (byte) ' ', (byte) 'W',

(byte) 'o', (byte) 'r', (byte) 'l', (byte) 'd', };

private static final byte HW_CLA = (byte) 0x80;

private static final byte HW_INS = (byte) 0x00;

public static void install(byte[] bArray, short bOffset, byte bLength) {

        new HelloworldApplet().register(bArray, (short) (bOffset + 1),

        bArray[bOffset]);

}
public void process(APDU apdu) {

     if (selectingApplet()) {

       return;

}

  byte[] buffer = apdu.getBuffer();

  byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);

  byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);

if (CLA != HW_CLA) {

    ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);

}

switch (INS) {

  case HW_INS:

   getHelloWorld(apdu);

   break;

  default:

   ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);

  }
             }

private void getHelloWorld(APDU apdu) {

      byte[] buffer = apdu.getBuffer();

      short length = (short) helloWorld.length;

     Util.arrayCopyNonAtomic(helloWorld, (short) 0, buffer, (short) 0,

     (short) length);

     apdu.setOutgoingAndSend((short) 0, length);

       }

}

Java Eliptic Curve Cryptography Sign/verify Example

In this Post I am going to talk about the Elliptic curve encryption.First I will tell you why we use ECC. ECC is public-key Cryptography. ECC is used for the Authentication and authorization.Mainly The structure is like this way.In here(http://www.johannes-bauer.com/compsci/ecc/) you can see very good explanation how ECC works. .First Using public key we have sign data.and then using private key we can verify data.In here we verify that compare the signing data and what are the we input data.So I used bouncy castle for ECC. In here (http://www.bouncycastle.org/latest_releases.html) You can download the bouncy castle jar and add to the Project.In here I First sign my data using Private key.Then I Verify the signing data using Public key.

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;


import java.security.PublicKey;

import java.security.SecureRandom;
import java.security.Signature;


import java.security.Security;



import java.security.interfaces.ECPublicKey;



import java.security.spec.InvalidKeySpecException;

import java.security.spec.X509EncodedKeySpec;


import org.bouncycastle.jce.ECNamedCurveTable;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;


public class PublickeyEncryption {



public static void main(String args[]) {



try {



/**

 * ECC signature sign and verify
 */
ECParameterSpec ecSpec = ECNamedCurveTable
.getParameterSpec("prime192v1");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");


g.initialize(ecSpec, new SecureRandom());

// Genarate keypair
KeyPair pair = g.generateKeyPair();
System.out.println("Provider Name :"+BouncyCastleProvider.PROVIDER_NAME);
/**
Genarate Private and Public keys
*/
PublicKey pubKey = pair.getPublic();
PrivateKey prikey = pair.getPrivate();
byte[] inputData = new byte[] { (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01 };
Signature sig = Signature.getInstance("ECDSA", "BC");
/**
Initialize the sign and update data to be Sign
*/
sig.initSign(prikey);
sig.update(inputData);
/**
SIGN the data using private key
*/
byte[] signatureBytes = sig.sign();
System.out.println("Sign byte arry:" + Arrays.toString(signatureBytes));
/**
Initialize the verify and update data to be Verify
*/
sig.initVerify(pubKey);
sig.update(inputData);
/**
Check verify true or False
*/
System.out.println("VERIFY :" + sig.verify(signatureBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
}

Java RSA Encryption and Decryption Example

This is the sample code

package sajith.foru.rsaencryption;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RsaEncryption {

/**
 * Generate RSA private and public key and Encrypt/Decrypt
 *
 * @param args
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
/**
 * Generate KeyPair
 */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // key size can be change to 512,1024
KeyPair kp = keyGen.genKeyPair();
/**
 * Generate private and public key
 */
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
/**
 * String want to be encrypted
 */
String text = "Your text Message";
Cipher cipher = Cipher.getInstance("RSA");
/**
 * Enable Encrypt mode
 */
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(text.getBytes());
String encryptedText = new String(encryptedData);
System.out.println("Text Encrypted : " + encryptedText);
/**
 * Enable Decrypt mode
 */
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptDataValue = cipher.doFinal(encryptedData); // decrypted
// the
// encrypted
// data
String decryptedText = new String(decryptDataValue);
System.out.println("Text Decryted : " + decryptedText);

}



}

Replace sentence or word in file linux

For replace world in file

sed -i 's/OLd_text/new_text/g' fileName

ex sed -i 's/my_world/hello_world/g' hello.txt

output :-


For replace Sentence

14 October 2014

Android TimePicker Dialog

Android TimePicker Dialog Example

If you want to add TimePicker dialog when your OnClick events you can use this code line.

            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    eReminderTime.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();