Wednesday, 21 January 2015

Android Example to upload file to Amazon S3 Bucket



Amazon S3

Amazon Simple Storage Service is storage for the Internet. It is designed to make web-scale computing easier for developers.
Amazon S3 has a simple web services interface that you can use to store and retrieve any amount of data, at any time, from anywhere on the web. It gives any developer access to the same highly scalable, reliable, fast, inexpensive data storage infrastructure that Amazon uses to run its own global network of web sites. The service aims to maximize benefits of scale and to pass those benefits on to developers.
Buckets
A bucket is a container for objects stored in Amazon S3. Every object is contained in a bucket. Buckets serve several purposes: they organize the Amazon S3 namespace at the highest level, they identify the account responsible for storage and data transfer charges, they play a role in access control, and they serve as the unit of aggregation for usage reporting.
Steps to upload a file to Amazon S3 Bucket

·         Create an instance of the AmazonS3Client.

·         Execute one of the AmazonS3Client.putObject overloads depending on whether you are uploading data from a file, or a stream.
·         Amazon S3 credentials are needed i.e Access Key and Secret Key which are given by account holder
·         Amazon S3 Bucket name is needed which is created by the account holder
AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials("access_key","secret_key"));
try {
System.out.println("Uploading a new object to S3 from a file\n");
File file = new File(uploadFileName);
s3client.putObject(new PutObjectRequest(bucketName, "folder/"+keyName, file));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException”);
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException”);
}
}

Monday, 19 January 2015

Java Example to upload file to Amazon S3 Bucket


This example needs android sdk jars to be included in libs 
Following link sdk is available

http://aws.amazon.com/mobile/sdk/

import java.io.File;
import java.io.IOException;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;

public class UploadObjectSingleOperation {
//This should be already created in the Amazon S3
    private static String bucketName = "sample";
    private static String keyName = "Photo.JPEG";
// windows file path
//    private static String uploadFileName = "D://Pics//mypic.JPG";
//Mac file path
    private static String uploadFileName = "/Users/xxx/Pictures/Photo.jpg";
    public static void main(String[] args) throws IOException {
       
        AmazonS3 s3client = new AmazonS3Client(new BasicAWSCredentials("accesskey", "secretkey"));
        try {
            System.out.println("Uploading a new object to S3 from a file\n");
            File file = new File(uploadFileName);
            s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which "
                    + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response"
                    + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which "
                    + "means the client encountered "
                    + "an internal error while trying to "
                    + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}


SourceCode

App share sample code

Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
            i.putExtra(Intent.EXTRA_TEXT,
                    "https://play.google.com/store/apps/details?id=com.example.first");
            startActivity(Intent.createChooser(i,
                    "Share the app URL"));

Monday, 12 January 2015

Latitude and Longitude using Location Manager API Android

Following example is to obtain lat and long

import java.util.ArrayList;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {

    LocationManager locationManager;
    String provider;
    private List<String> repId = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting LocationManager object
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Creating an empty criteria object
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, true);

        // Getting the name of the provider that meets the criteria

        if (provider != null && !provider.equals("")) {

            // Get the location from the given provider
            Location location = locationManager.getLastKnownLocation(provider);

            locationManager.requestLocationUpdates(provider, 20000, 1, this);

            if (location != null)
                onLocationChanged(location);
            else {
                Toast.makeText(getBaseContext(), "Location can't be retrieved",
                        Toast.LENGTH_SHORT).show();
                checkForNetworkProvider();
            }

        } else {
            Toast.makeText(getBaseContext(), "No Provider Found",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void checkForNetworkProvider() {

        repId = locationManager.getAllProviders();
        for (String pri : repId) {
            System.out.println("print providers are" + pri);
        }

        Location location = locationManager
                .getLastKnownLocation(locationManager.NETWORK_PROVIDER);
        if (location != null)
            onLocationChanged(location);
        else {
            Toast.makeText(getBaseContext(), "Location can't be retrieved",
                    Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        // Getting reference to TextView tv_longitude
        TextView tvLongitude = (TextView) findViewById(R.id.tv_longitude);

        // Getting reference to TextView tv_latitude
        TextView tvLatitude = (TextView) findViewById(R.id.tv_latitude);

        // Setting Current Longitude
        tvLongitude.setText("Longitude:" + location.getLongitude());

        // Setting Current Latitude
        tvLatitude.setText("Latitude:" + location.getLatitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

Layout file:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
   
    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/str_tv_location"
        android:textStyle="bold" />
   
    <TextView
        android:id="@+id/tv_longitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_location"
        android:layout_centerHorizontal="true" />
   
    <TextView
        android:id="@+id/tv_latitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_longitude"
        android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_latitude"
        android:layout_marginLeft="34dp"
        android:layout_marginTop="28dp"
        android:background="@android:color/black"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

Manifest Permissions:


 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />   
 <uses-permission android:name="android.permission.INTERNET" />


Strings

 <string name="title_activity_main">Location From GPS</string>
 <string name="str_tv_location">Current Location</string>

SourceCode 

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...