How to set bucket policies for Amazon AWS S3?

In Amazon AWS S3 Console > Select your bucket > hit Properties tab on right-hand side > Edit bucket policies button

Public bucket policy:

{
“Version”:”2008-10-17″,
“Statement”:[{
“Sid”:”MyAllowPublicRead”,
“Effect”:”Allow”,
“Principal”: {
“AWS”: “*”
},
“Action”:[“s3:GetObject”],
“Resource”:[“arn:aws:s3:::YOUR_BUCKET/*”
]
}
]
}

 

 

How to configure secure access Amazon AWS S3 bucket?

Create a IAM User

In Amazon AWS Console > IAM :

Create a User, you will get Access Key Id, and Secret Key for that user.

Create a Policy

In Amazon AWS Console > IAM > Policies

{
“Version”: “2012-10-17″,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“s3:Get*”
],
“Resource”: “arn:aws:s3:::YOUR_BUCKET/*”
}
]
}

Attach this Policy to the User (Or Group, if you added user to a Group)

Use Attach button (available in the policy page) for this.

All set – Now access S3 Bucket from Java Program:

NOTE: You will need AWS-JAVA_SDK in path eg: aws-java-sdk-1.9.17.jar

package com.s3test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class S3Test {

static AWSCredentials credentials = null;
static String bucketName = “BUCKET_NAME”;
static String key = “YOUR_FILE_IN_BUCKET”;

public static void main(String[] args) {
//– credentials = new ProfileCredentialsProvider()..getCredentials();
credentials = new BasicAWSCredentials(“USER_ACCESS_KEY_ID”, “USER_SECRET_ACCESS_KEY”);
AmazonS3 s3 = new AmazonS3Client(credentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_1);//Make sure region is same as where S3 bucket exists
s3.setRegion(usWest2);

S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
System.out.println(“Content-Type: ” + object.getObjectMetadata().getContentType());
try {
displayTextInputStream(object.getObjectContent());
} catch (IOException e) {

e.printStackTrace();
}
}

private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;

System.out.println(” ” + line);
}
System.out.println();
}
}

 

That’s It

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);

….

How to setup Google Analytics for Android Apps?

Using Google Android Analytics API v4

The official documentation is here: https://developers.google.com/analytics/devguides/collection/android/v4 – but it is confusing.

Download Google Play Services

Using Android SDK Manager download Extras > Google Play Services.

Add Google Play Services to your Eclipse as a Project:

  • File > Import > Android > Existing Android Code into Workspace > Choose Google Play Services Lib project (that you just downloaded)
  • Make sure that yous select: Copy Project into Workspace checkbox.

Add Google Play Services Project as a Library to your Project

Eclipse > Your Android Project > Properties > Android > Library > Add (do not check Is Library checkbox)

Update Android Manifest

Add following in your manifest xml under Application node:

<meta-data
android:name=”com.google.android.gms.analytics.globalConfigResource”
android:resource=”@xml/global_tracker” />
<meta-data
android:name=”com.google.android.gms.version”
android:value=”@integer/google_play_services_version” />

Create Global Tracker XML

Create this file: res/xml/global_tracker.xml

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

<!– the Local LogLevel for Analytics –>
<string name=”ga_logLevel”>verbose</string>

<!– how often the dispatcher should fire –>
<integer name=”ga_dispatchPeriod”>200</integer>

<!– Treat events as test events and don’t send to google –>
<bool name=”ga_dryRun”>false</bool>

<!– The screen names that will appear in reports –>
<!– <screenName name=”com.whatever.My1Activity”>My 1 Activity</screenName> –>
</resources>

Create App Tracker

Create this file: res/xml/app_tracker.xml

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

<!– The apps Analytics Tracking Id. Important: Update this –>
<string name=”ga_trackingId”>XX-WHATEVER-Y</string>

<!– Percentage of events to include in reports –>
<string name=”ga_sampleFrequency”>100.0</string>

<!– Enable automatic Activity measurement –>
<bool name=”ga_autoActivityTracking”>true</bool>

<!– catch and report uncaught exceptions from the app –>
<bool name=”ga_reportUncaughtExceptions”>true</bool>

<!– How long a session exists before giving up –>
<integer name=”ga_sessionTimeout”>300</integer>

<!– If ga_autoActivityTracking is enabled, an alternate screen name can be specified to
substitute for the full length canonical Activity name in screen view hit. In order to
specify an alternate screen name use an <screenName> element, with the name attribute
specifying the canonical name, and the value the alias to use instead. –>
<!– <screenName name=”com.activity.My2Activity”>My 2 Activity</screenName> –>

</resources>

 

Create App Class

package com.whatever;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

import java.util.HashMap;

public class YourApp extends Application {

// The following line should be changed to include the correct property id.
private static final String PROPERTY_ID = “XX-WHATEVER-Y”; //Important: Update this

// Logging TAG
private static final String TAG = “MyApp”;//Only used for logging

public static int GENERAL_TRACKER = 0;

public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg:
// roll-up tracking.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a
// company.
}

HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

public YourApp() {
super();
}

public synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {

GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);

Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)

: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID)

: analytics.newTracker(R.xml.app_tracker);
mTrackers.put(trackerId, t);

}
return mTrackers.get(trackerId);
}
}

 

Update your My1 Activity Class (i.e any Activity Class you want to track)

In onCreate method, just after: setContentView, add following:

((YourApp) getApplication()).getTracker(YourApp.TrackerName.APP_TRACKER);

Also add following two methods:

@Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}

@Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}

Add this code to all Activity Classes you want to track.

That’s it – Run your application.

Go to https://www.google.com/analytics – to see Analytics

Open Questions

  • There does not seem to be any way to track Active Users outside the context of Activities i.e If you do not care about tracking activities, but only want to track active user’s in your app (they maybe on any activity) – there is no way. You have to enable activity level tracking.  Anyone knows better?
  • What if Google Play App (assuming google play services uses Google Play internally) dies on the Android Mobile, will my app hang or get stuck?
  • How can we ensure that our App is unaffected (speed/performance) even if Google Play Services is not working for some reason.
  • Any other considerations – please leave your comments below – will add them to this blog post.

How to setup https/ssl on Tomcat 6?

Generate a keystore using this command:

c:\work\keytool -genkey -alias myalias -keyalg RSA -keystore mykeystore

 

Your Tomcat server.xml should have an entry like below:

<Connector port=”8443″ protocol=”org.apache.coyote.http11.Http11Protocol”  SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” keystoreFile=”C:\work\mykeystore”
keystoreType=”JKS” keystorePass=”123456″ />

This may also be needed (note the SSLEngine=off ):

<Listener className=”org.apache.catalina.core.AprLifecycleListener” SSLEngine=”off” />

 

Note, your site now will work on both http and https – assuming you have not removed the http connector from server.xml

If you want to force some URLs to work only in https then add the following in web.xml:

 

<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/secure/*</url-pattern>
</web-resource-collection>

<user-data-constraint>
<!– All access to this area will be SSL protected –>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

 

Now, all the URLs that are like: /secure/whatever – can be accessed only over https. If you attempt to access them over http, it will redirect to https automatically.

Note: We have generated and used a dummy certificate above, altho it works – when u open url using https://.. in your browser – you will see a warning and a red mark. To use a real ssl certificate (you will have to buy) – the steps will be slightly different.

How to share folders between Windows Host, and Linux Guest OS on VMWare (Workstation)?

 

First Way

  1. On Windows Host, Right Click > Properties > Share (with Everyone)
  2. On Linux Host: Applications > File Browser > File > Connect to Server > Service Type: Windows Share , Server:  Give-Desktop-IP > Connect.
  3. On being prompted enter windows username/group/password – Thats it, your shared folder will show up

 

Second Way

  • You could always run a Web-Server on your Windows Host, and access it from Linux Host (either browser or wget). Not exactly file sharing, but files can be downloaded from Windows Host to Linux this way (just in case nothing else is working for you!)

 

Third Way

  • With VMWare Tools – it should be possible too… have not got it to work yet.

Error Message: No suitable driver found for jdbc:mysql:.. in a maven jpa/hibernate/mysql project

Problem Statement

In your maven project, with appropriate dependencies for Hibernate/MySQL, you get the following error – when jpa-hibernate code is invoked:

WARN : org.hibernate.connection.DriverManagerConnectionProvider – no JDBC Driver class was specified by property hibernate.connection.driver_class
WARN : org.hibernate.cfg.SettingsFactory – Could not obtain connection to query metadata
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/somedb

Solution

The solution is in the warning itself. Note the line that says:  no JDBC Driver class was specified by property hibernate.connection.driver_class

In your persistence.xml file add the following line:
<property name=”hibernate.connection.driver_class” value=”com.mysql.jdbc.Driver” />

That’s It!

How to resolve: Maven Error: [ERROR] No plugin found for prefix ‘archetype’ in the current project…

Problem Statement

You get this error while doing  maven build:

[ERROR] No plugin found for prefix ‘archetype’ in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
repositories [local (C:\Documents and Settings\<user>\.m2\repository), central (http://repo1.maven.org/maven2)%5D

Solution

Very likely, your proxy settings are the problem. If you are behind a firewall setup your proxy correctly.
Proxy settings are in settings.xml config file of maven. This file usually exists in two places:

  • <MAVEN_HOME>\conf
  • c:\documents and settings\<user>\.m2

Thats it!

Simple image (widget for) zoom, rotate?

Ref: https://github.com/can3p/iviewer

Here is an example (only zoom, fit etc.. for rotate see iviewer website):

<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>jquery.iviewer test</title>
<script type=”text/javascript” src=”imgtest/jquery.js” ></script>
<script type=”text/javascript” src=”imgtest/jqueryui.js” ></script>
<script type=”text/javascript” src=”imgtest/jquery.ui.core.js” ></script>
<script type=”text/javascript” src=”imgtest/jquery.mousewheel.min.js” ></script>
<script type=”text/javascript” src=”imgtest/jquery.iviewer.js” ></script>
<script type=”text/javascript”>
var $ = jQuery;
$(document).ready(function(){
var iv1 = $(“#viewer”).iviewer({
src: “test_image.jpg”,
update_on_resize: false,
zoom_animation: false,
mousewheel: false,
onMouseMove: function(ev, coords) { },
onStartDrag: function(ev, coords) { return false; }, //this image will not be dragged
onDrag: function(ev, coords) { }
});

$(“#in”).click(function(){ iv1.iviewer(‘zoom_by’, 1); });
$(“#out”).click(function(){ iv1.iviewer(‘zoom_by’, -1); });
$(“#fit”).click(function(){ iv1.iviewer(‘fit’); });
$(“#orig”).click(function(){ iv1.iviewer(‘set_zoom’, 100); });
$(“#update”).click(function(){ iv1.iviewer(‘update_container_info’); });

$(“#chimg”).click(function()
{
iv1.iviewer(‘loadImage’, “imgtest/test_image2.jpg”);
return false;
});
});
</script>
<link rel=”stylesheet” href=”imgtest/jquery.iviewer.css” />
<style>
.viewer
{
width: 80%;
height: 800px;
border: 1px solid black;
position: relative;
}

.wrapper
{
overflow: hidden;
}
</style>
</head>
<body>
<h1>JQuery.iviewer test</h1>
<!– wrapper div is needed for opera because it shows scroll bars for reason –>
<div class=”wrapper”>
<span>
<a id=”in” href=”#”>+</a>
<a id=”out” href=”#”>-</a>
<a id=”fit” href=”#”>fit</a>
<a id=”orig” href=”#”>orig</a>
<a id=”update” href=”#”>update</a>
</span>
<a href=”#” id=”chimg”>Change Image</a>
<div id=”viewer” class=”viewer”></div>
</div>
</body>
</html>

Follow

Get every new post delivered to your Inbox.