Category Archives: Uncategorized

How to setup static website on Amazon AWS S3?

All instructions here:

https://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html

Remember that if you bought your domain name elsewhere like godaddy.com, then you need to tell godaddy to point its NS records to Amazon Route53 NS records.

Settings > Name Servers > Custom: Here add the Name Servers that you see in AWS Console > Route53 > Your Hosted Zone > NS Values

Here’s another reference (does not contain info. about the DNS part):

http://aws.amazon.com/blogs/aws/root-domain-website-hosting-for-amazon-s3/

 

How do i integrate Facebook Login in Android app?

The Activity Layout File

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:facebook=”http://schemas.android.com/apk/res-auto&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center_horizontal”
android:orientation=”vertical”
android:padding=”20dp” >

<com.facebook.login.widget.LoginButton
android:id=”@+id/login_button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center_horizontal”
android:layout_marginTop=”30dp”
android:layout_marginBottom=”30dp” />

</LinearLayout>

===

The Activity

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import com.yourapp.R;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;

public class FBConnect1 extends Activity {

private com.facebook.login.widget.LoginButton loginButton;
private Button logoutBtn;
private Button closeBtn;
private TextView userName;

boolean isFetching = false;
CallbackManager callbackManager;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(“FACEBOOK STARTING”);
FacebookSdk.sdkInitialize(getApplicationContext());

setContentView(R.layout.activity_fbconnect1);

callbackManager = CallbackManager.Factory.create();

loginButton = (com.facebook.login.widget.LoginButton) findViewById(R.id.login_button);

loginButton.setReadPermissions(“user_friends”);
// If using in a fragment
// loginButton.setFragment(this);
// Other app specific specialization

// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback() {
@Override
public void onSuccess(LoginResult loginResult) {
System.out.println(“SUCCESS FACEBOOK LOGIN”);

Profile profile = Profile.getCurrentProfile();
System.out.println(“FACEBOOK PROFILE onSuccess ” + profile);
System.out.println(“FACEBOOK USER: ” + profile.getName());

// Get User Name
//mTextDetails.setText(profile.getName() + “”);
//loginResult.
// App code
}

@Override
public void onCancel() {

System.out.println(“FACEBOOK SUCCESS FACEBOOK CANCELED”);
// App code
}

@Override
public void onError(FacebookException exception) {

System.out.println(“FACEBOOK ERROR : ” + exception);
// App code
}
});
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}

}

How do i develop Android applications on Mac OS?

Install Eclipse IDE

Add ADT Plugin

https://dl-ssl.google.com/android/eclipse

Download Android SDK

http://developer.android.com/sdk

Use the SDK Manager, to update Packages.

Configure Android SDK path in Eclipse Preferences.

How to add Twitter Login (Authentication) to Android Mobile App?

NOTE: This is not the best way to go about it becz:

  • This opens a new browser window for login
  • After logging in, the app’s callback is not being invoked.

Step 0: Create a Twitter App

Create a Twitter App here: https://apps.twitter.com/

Make sure you:

  • Put some URL in Callback URL – it wouldn’t matter what you put there.
  • Sign in with Twitter is Yes.

You will get Consumer Key and Access Key here.

Step 1: Download Twitter 4j

Download jar from here: http://twitter4j.org/en/index.html

Add jar to your Mobile Android App. You can put it in Android App Prokect > lib directory.

Step 2: Create Twitter Activity Java Class, Layout XML, Update Android Manifest

package com.whatever.activity;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.whatever.R;

public class TwitterActivity extends Activity {

Twitter twitter;
RequestToken requestToken;
//Please put the values of consumerKy and consumerSecret of your app
public final static String consumerKey = “YOUR_TWITTER_CONSUMER_KEY;
public final static String consumerSecret = “YOUR_TWITTER_CONSUMER_SECRET_KEY”;
private final String CALLBACKURL = “T4J_OAuth://callback_main”;

//Callback URL that tells the WebView to load this activity when it finishes with twitter.com. (see manifest)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);

MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
}

void OAuthLogin() {
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
String authUrl = requestToken.getAuthenticationURL();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(authUrl)));
} catch (TwitterException ex) {
//Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
Log.e(“in Main.OAuthLogin”, ex.getMessage());
}
}
/*
* – Called when WebView calls your activity back.(This happens when the user has finished signing in)
* – Extracts the verifier from the URI received
* – Extracts the token and secret from the URL
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
try {
String verifier = uri.getQueryParameter(“oauth_verifier”);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
String token = accessToken.getToken(), secret = accessToken
.getTokenSecret();
//–displayTimeLine(token, secret); //after everything, display the first tweet

} catch (TwitterException ex) {
Log.e(“Main.onNewIntent”, “” + ex.getMessage());
}

}

private class MyAsyncTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String… params) {
OAuthLogin();
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//
}

}
}

 

Twitter Layout XML: res\layout\activity_twitter.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:facebook=”http://schemas.android.com/apk/res-auto&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center_horizontal”
android:orientation=”vertical”
android:padding=”20dp” >

<LinearLayout

android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello” />
</LinearLayout>

</LinearLayout>

 

Make sure Manifest file of your Android App has the following:

<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

….

<activity
android:name=”com.whatever.activity.TwitterActivity”
android:label=”The Twitter Login~” >

<intent-filter>
<action android:name=”android.intent.action.VIEW” />
<category android:name=”android.intent.category.DEFAULT” />
<category android:name=”android.intent.category.BROWSABLE” />
<data android:scheme=”T4J_OAuth” android:host=”callback_main” />
</intent-filter>
</activity>

Step 3: Invoke Twitter Login 

Intent intent1 = new Intent(this, TwitterActivity.class);
startActivity(intent1);

….

Space in LDAP SSL URL causes: ‘MalformedURLException: Invalid URI:’

Problem Statement:

You are trying to connect to LDAP(SSL) from a Java Program as follows:

...
prop.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
...
prop.put(Context.PROVIDER_URL, "ldap://host:636/OU=My Org,DC=domain,DC=com");
LdapContext ctx =new InitialLdapContext(prop,null);
...

And you see error message like:
MalformedURLException: Invalid URI: Invalid URI: Org,DC=domain,DC=com]


Solution

This error is caused by the space in URI. So in this case space in: ‘My Org’ part of the URL.
If you replace ‘My Org’ with ‘My%20Org’, the error should go away.

So, your code should now look like:
...
prop.put(Context.PROVIDER_URL, "ldap://host:636/OU=My%20Org,DC=domain,DC=com");
...

How to take a Java Heap Dump and analyze it?

To take a Heap Dump from Command Line:

First get the Java Applications Process Id, one way to do this is with: jps

jmap -dump:format=b,file=dump.bin <javaProcessIdHere>

The size of the heap dump file will be same as the heap memory in use at the time the command is run. For large heap sizes this can take several minutes to run, and can stall (make it unresponsive) the application during this time.

To get a summary of Object Instances and Sizes you can use this command:

jmap -histo:live <javaProcessIdHere>

Generally, this command will run quickly, and should be used when taking a heap dump will be too costly in terms of time-taken/size etc.

To get Heap Dump on Out of Memory Exception (available from Java 1.5.0_07 onwards):

Add the following param: -XX:+HeapDumpOnOutOfMemoryError

If you want the dump to go in a particular path then add: -XX:+HeapDumpOnOutOfMemoryError XX:HeapDumpPath=/usr/local/dumps

To initiate Heap Dump from within the Application Code:

We can also use jmap from our code. To get a pid from code use we need to use java.lang.management.ManagementFactory.

String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.substring(0, name.indexOf("@"));
After that we can start jmap process like this:
String[] cmd = { "jmap", "-dump:file=/usr/local/heapdumps/dump.bin", pid };
Process p = Runtime.getRuntime().exec(cmd);

A simple Shell Script to Take Heap Dump every 30 seconds:

while true
do
  jmap -dump:file=/tmp/java-`date +%s`.hprof <processIdOfJVM>
  sleep 30
done

Heap Dump Analysis Tools
  • Eclipse Memory Analyzer
  • Java Visual VM (part of JDK)
  • jhat – Java Heap Analysis Tool (Suitable for analyzing very big heap files)


							
						

How does -XX:NewSize -XX:MaxNewSize effect Garbage Collection?

If you have the following JVM options:
-XX:NewSize=nnn -XX:MaxNewSize=mmm Then you will get Memory (Heap) usage graph as follows:
Without the NewSize options, you will get Memory (Heap) usage graph as follows:
What does this indicate?In the first case short-lived objects are allowed to grow in Eden Space until it gets full, and then Full GC happens.In the Second case minor GC keeps happening frequently, and short-lived objects are GC’ed frequently.

How to resolve: Spring XSD schema error – schema_reference.4: Failed to read schema document

Problem Statement

While loading a Spring Context XML file i get the following error:
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document …because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not

Solution
This error is caused by the fact that the XSD being referred is not found (either because it does not exist OR there is no internet connection).

1. Download the XSD and place it in your Classpath.
2. In the xsi:schemaLocation=”…” section of your Spring Context file, change the path to XSD from http to classpath.

Originally:
<beans schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;

After Change:
<beans schemalocation="http://www.springframework.org/schema/beans
classpath:spring-beans.xsd

Thats it.

How to find Query Execution Time in Oracle database?

Try:
select * from v$sql;

You will notice that you can further filter on lot of useful stuff.

For eg: Lets say you want to see only those queries coming via a JDBC Thin Driver, you can do:
select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elasped from v$sql
WHERE MODULE='JDBC Thin Client'
ORDER BY LAST_LOAD_TIME DESC

To see all the columns in this table:
desc v$sql

Spring Exception: org.xml.sax.SAXParseException Cannot find the declaration of element ‘beans’.

Problem Statement

When i run my Spring Application in App Server (Tomcat in my case), i get the following error:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 3 in XML document from ServletContext resource [/WEB-INF/spring/root-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
...
at java.lang.Thread.run(Thread.java:662)
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
...
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
... 23 more

Solution
This can be caused by Spring not being able to find the relevant XSD(spring-beans-3.1.xsd in example below) defined in Spring Config File.

In my case i have these lines at the beginning of Spring Config File:

<beans xmlns="http://www.springframework.org/schema/beans&quot; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

If you are behind a Proxy(to access internet), add the following lines my Tomcat startup – this resolves the problem:
-Dhttp.proxyHost=whatever -Dhttp.proxyPort=whatever -Dhttp.proxyUser=whatever