Tuesday, March 29, 2016

How to get SAML Token from WebView in Android



Following code can be used to get SAML token Id from SAML

 //Calling method to display Token id from the SAML Reponse
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementsByName('SAMLResponse')[0].value);");

don't forget to use below inner class

class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        @JavascriptInterface
        public void showHTML(String html) {
            System.out.println("html>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:"+html);
            new AlertDialog.Builder(ctx).setTitle("Token Id").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
Please refer to the below files for complete code

1- MainActivity

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import android.view.KeyEvent;
import android.view.MotionEvent;



public class MainActivity extends AppCompatActivity {


    private long pageStartTime = 0;
    private WebView wv;
    private ImageButton newActivityBtn;
    private EditText et;
    private TextView pageLoadTime;




    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wv = (WebView) findViewById(R.id.wv);

        newActivityBtn = (ImageButton) findViewById(R.id.new_activity);
        pageLoadTime = (TextView) findViewById(R.id.page_load_time);
        et = (EditText) findViewById(R.id.et);

        // setup edit text
        et.setSelected(false);
        if (getIntent().getStringExtra("url") != null) {
            et.setText(getIntent().getStringExtra("url"));
        } else {
            et.setText("");
        }


        //wv.setWebChromeClient(new WebChromeClient());

        WebSettings settings = wv.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAppCacheEnabled(false);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");



        wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                et.setText(url);
                pageStartTime = System.currentTimeMillis();
                pageLoadTime.setText("0ms");

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (pageStartTime == 0) {
                } else {

                   //Calling method to display Token id from the SAML Reponse
                   view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementsByName('SAMLResponse')[0].value);");

                    long loadTime = (System.currentTimeMillis() - pageStartTime);
                    pageLoadTime.setText(String.format("%sms", loadTime));
                    System.out.println(String.format("page load time: %sms", loadTime));
                    view.clearCache(true);
                    view.clearView();
                }
            }
        });
        handleLoadUrl();

        // setup events
        newActivityBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    newActivityBtn.setColorFilter(getResources().getColor(android.R.color.holo_blue_dark));
                    return false;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    newActivityBtn.setColorFilter(null);
                    return false;
                }
                return false;
            }
        });
        newActivityBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                intent.putExtra("url", et.getText().toString());
                startActivity(intent);
            }
        });
        et.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    handleLoadUrl();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }


    private void handleLoadUrl() {
        String url = et.getText().toString();
        if (url.startsWith("http://")) {
        } else if (url.startsWith("https://")) {
        } else {
            url = String.format("http://%s", url);
        }
        wv.loadUrl(url);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        @JavascriptInterface
        public void showHTML(String html) {
            System.out.println("html>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:"+html);
            new AlertDialog.Builder(ctx).setTitle("Token Id").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }

}

For  Android Menifest file and content_main.xml Please refer to below site

https://shdhumale.wordpress.com/2016/03/30/how-to-get-saml-token-from-webview-in-android/

How to check if Application is installed in Android Device

We can use below code to check if the Package com.package.name is installed in the Android Device. If not then we can direct the user to google Play Store link for the same.

Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(""https://play.google.com/store/apps/details?id=com.package.name"));
startActivity(intent);

Tuesday, March 15, 2016

Android Loggin example using Web service and Navigating to another page


Step 1- MainActivity

package com.scrum.siddhu.scrumapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
String username;
String password;
String soapResponse;
private final String NAMESPACE = "http://main.siddhu.com";
private final String URL = "http://10.226.171.182:8088/mockExposeWebServiceSoap11Binding?wsdl";
private final String SOAP_ACTION = "http://main.siddhu.com/getUserLogin";
private final String METHOD_NAME = "getUserLogin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tx1=(TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
Intent in=new Intent(MainActivity.this,SecondPageActivity.class);
startActivity(in);
}*/
if(null != ed1.getText() && null != ed2.getText())
{
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute();
username = ed1.getText().toString();
password= ed2.getText().toString();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
//tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}

private class AsyncCallWS extends AsyncTask {
@Override
protected Void doInBackground(String... params) {
//Log.i(TAG, "doInBackground");
getSoapResponse(username, password);
return null;
}
@Override
protected void onPostExecute(Void result) {
//Log.i(TAG, "onPostExecute");
System.out.println("soapResponse >>>>>>>>>>>>>>>>>>>>>" + soapResponse);
Intent in=new Intent(MainActivity.this,SecondPageActivity.class);
startActivity(in);
}
@Override
protected void onPreExecute() {
//Log.i(TAG, "onPreExecute");
//tv.setText("Calculating...");
Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Void... values) {
// Log.i(TAG, "onProgressUpdate");
}
}

public void getSoapResponse(String username, String password) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
/*PropertyInfo userLogin = new PropertyInfo();
//Set Name
userLogin.setName("username");
//Set Value
userLogin.setValue(ed1.getText().toString());
//Set dataType
userLogin.setType(String.class);
PropertyInfo userLoginPassword = new PropertyInfo();
//Set Password
userLoginPassword.setName("password");
//Set Value
userLoginPassword.setValue(ed2.getText().toString());
//Set dataType
userLoginPassword.setType(String.class);
request.addProperty(userLogin);
request.addProperty(userLoginPassword);
*/
request.addProperty("username",ed1.getText().toString());
request.addProperty("password",ed2.getText().toString());
//Add the property to request object
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
//envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the response
//SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//SoapObject result = (SoapObject)envelope.bodyIn;
SoapObject result = (SoapObject)envelope.getResponse();
//soapResponse = result.toString();
//Assign it to fahren static variable
System.out.println("result:" + result);
//if(result.getProperty(5).toString().equals(ed1.getText().toString()) && result.getProperty(6).toString().equals(ed2.getText().toString()))
if(result.getProperty("userName").toString().equals(ed1.getText().toString()) && result.getProperty("userPassword").toString().equals(ed2.getText().toString()))
{
soapResponse = result.toString();
//Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Sgtep 2- Using Dependent JAR
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.scrum.siddhu.scrumapplication"
minSdkVersion 8
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile files('libs/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar')
}
Step 3- settings.gradle
include ':app', ':ksoap2-android-assembly-2.5.8-jar-with-dependencies'

Step 4- activity_main.xml

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.scrum.siddhu.scrumapplication.MainActivity">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
Step 5- AndroidManifest.xml

package="com.scrum.siddhu.scrumapplication">


android:allowBackup="true"
android:icon="@drawable/scrum"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">






Step 6- content_main.xml

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.scrum.siddhu.scrumapplication.MainActivity"
tools:showIn="@layout/activity_main">
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scrum Project"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff56ff12"
android:textSize="35dp" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter User Name"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/scrumlogin"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:textColorHint="#ffff299f"
android:hint="Password" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts Left:"
android:id="@+id/textView2"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/textView2"
android:layout_toEndOf="@+id/textview"
android:textSize="25dp"
android:layout_toRightOf="@+id/textview" />
Step -7 - activity_main_second.xml

android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

Step -8- SecondPageActivity
package com.scrum.siddhu.scrumapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SecondPageActivity extends AppCompatActivity {
WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_second);
/*wv = (WebView) findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("https://shdhumale.wordpress.com");*/
}

private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}





Download link : https://drive.google.com/open?id=0B1EOBpl9Kvo1S09TWDc0TjJEbUU





















































































































Sunday, March 13, 2016

ORA-28002: the password will expire

When you get below error from Oracle DB it indicate its time for you to change the Password. However you can get ride of this message if you set the password expired field as unlimited. I am using sqldeveloper hence showing you the UI screen wise navigation to do the same.
A database warning was encountered performing the requested operation:
ORA-28002: the password will expire within 7 days
28002. 00000 - "the password will expire within %s days"
*Cause: The user's account is about to expire and the password
needs to be changed
*Action: change the password or contact the DBA
Vendor code 28002
Use another user to log into any database connection you have, you can also use the default "system" or "sys" username.
Open connection tree and find the "Other Users" node and open that like so :
Image-1
Image1
Find your username in the child notes under "Other Users" and right click to edit user like so:
Image2
Type in your new password and Un-check password expired, then apply. Right click edit user again to see if the settings were changed if you wish.
Image3

Thursday, March 10, 2016

Simple Hello world Phone Gap Program

Step -1 : Installation of Phone Gap on PC

There are two ways to install it.

1- Desktop :- We will get GUI for installation
2- AppCLI :- Through command prompt

Dowload the exe from and Follow the below link for installions:

http://docs.phonegap.com/getting-started/1-install-phonegap/desktop/

Step 2- Insatallion of PhoneGap Developer

This can be done from  depending on your Mobile O/S.

Follow below link
http://docs.phonegap.com/getting-started/2-install-mobile-app/

iTunes :- https://itunes.apple.com/app/id843536693
Google Play :- https://play.google.com/store/apps/details?id=com.adobe.phonegap.app
Windows Phone Store :[- http://www.windowsphone.com/en-us/store/app/phonegap-developer/5c6a2d1e-4fad-4bf8-aaf7-71380cc84fe3


Step 3- Hello World Example

(A)- Create your appplication by giving proper name and package structure.

Make sure to start your application.

http://docs.phonegap.com/getting-started/3-create-your-app/desktop/

If you are not able to connect through Mobile screen you can also check the same screen using your PC browser.
Note:- Make sure your application run properly on PhoneGap Mobile. Ruuning application on browser is work arround