Click here to Skip to main content
15,891,136 members
Articles / Web Development

A Simple Mobile Enterprise Application

Rate me:
Please Sign up or sign in to vote.
4.70/5 (6 votes)
30 May 2012CPOL6 min read 46.4K   4.4K   29  
How to make a simple, end-to-end, mobile, Java enterprise application including a RESTful web service and an Android client.
package com.mbdavis.blog.simpleuser;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SimpleUserRESTServiceClientActivity extends Activity {
	private Button createButton;
	private EditText createEditText;
	private Button retrieveAllButton;
	private Button retrieveDetailsButton;
	private SimpleUser currentUser;
	private Button updateEmailButton;
	private Button deleteButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Create user button
		createButton = (Button) findViewById(R.id.createButton);
		createButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				// Get the name to use for the new user.
				createEditText = (EditText) findViewById(R.id.createEditText);
				Editable name = createEditText.getText();

				// Request the service to create the new user.
				SimpleUser user = new SimpleUser(0, name.toString(), "emailVal@dai.com");
				createUser(user);
			}
		});

		// Retrieve all users button
		retrieveAllButton = (Button) findViewById(R.id.retrieveAllButton);
		retrieveAllButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				retrieveAllUsers();
			}
		});

		// Retrieve user details button
		retrieveDetailsButton = (Button) findViewById(R.id.retrieveDetailsButton);
		retrieveDetailsButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				retrieveUserDetails();
			}
		});

		// Update user details button
		updateEmailButton = (Button) findViewById(R.id.updateEmailButton);
		updateEmailButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				updateUserDetails();
			}
		});

		// Delete user button
		deleteButton = (Button) findViewById(R.id.deleteButton);
		deleteButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				deleteUser();
			}
		});
	}

	private void createUser(SimpleUser user) {
		URL url;
		HttpURLConnection connection = null;
		try {
			// Create connection.
			String wsUri = getBaseContext().getResources().getString(
					R.string.rest_web_service_uri);
			url = new URL(wsUri);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");
			String userSer = user.getJSONSerialization();
			connection.setRequestProperty("Content-Length", Integer
					.toString(userSer.getBytes().length));
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request.
			DataOutputStream wr = new DataOutputStream(connection
					.getOutputStream());
			wr.writeBytes(userSer);
			wr.flush();
			wr.close();

			// Display response.
			String msg = Integer.toString(connection.getResponseCode()) + " "
					+ connection.getResponseMessage();
			if (connection.getResponseCode() == 201)
				msg += ": " + connection.getHeaderField("Location");
			else {				
				// Load in the response body.
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				String rspBody = sb.toString();
				if ((rspBody != null) && !rspBody.isEmpty())
					msg += ": " + rspBody;
			}

			connection.disconnect();
			
			Toast.makeText(SimpleUserRESTServiceClientActivity.this, msg, Toast.LENGTH_LONG).show();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	private void retrieveAllUsers() {
		URL url;
		HttpURLConnection connection = null;
		try {
			// Create connection.
			String wsUri = getBaseContext().getResources().getString(
					R.string.rest_web_service_uri);
			url = new URL(wsUri);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept", "application/json");
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request.
			connection.connect();
			int rspCode = connection.getResponseCode();
			
			// Load in the response body.
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			String rspBody = sb.toString();

			if (rspCode == HttpURLConnection.HTTP_OK) {
				// Remove the escape chars.
				rspBody = rspBody.replaceAll("\\\\", "");
				
				// Parse out the resource identifiers in the links.
				ArrayList<String> linkList = new ArrayList<String>();
				int s = 0;
				while (true) {
					int i = rspBody.indexOf("\"", s);
					int j = rspBody.indexOf("\"", ++i);
					String link = rspBody.substring(i, j);
					int r = link.lastIndexOf("/");
					String linkRrs = link.substring(r + 1);
					linkList.add(linkRrs);
					int k = rspBody.indexOf(",", ++j);
					if (k < 0)
						break;
					else
						s = k + 1;
				}

				// Load the spinner with the links.
				Spinner spinner = (Spinner) findViewById(R.id.retrieveAllSpinner);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_spinner_item);
				adapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				for (String link : linkList)
					adapter.add(link);
				spinner.setAdapter(adapter);
			}

			// Display response.
			String msg = Integer.toString(rspCode) + " " + connection.getResponseMessage();
			if (rspCode != 200) {
				if ((rspBody != null) && !rspBody.isEmpty())
					msg += ": " + rspBody;
			}

			connection.disconnect();
			
			Toast.makeText(SimpleUserRESTServiceClientActivity.this, msg, Toast.LENGTH_LONG).show();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	private void retrieveUserDetails() {
		URL url;
		HttpURLConnection connection = null;
		try {
			// Create connection with the selected user. 
			String wsUri = getBaseContext().getResources().getString(R.string.rest_web_service_uri);
			Spinner spinner = (Spinner) findViewById(R.id.retrieveAllSpinner);
			String userId = (String) spinner.getSelectedItem();
			wsUri += userId;
			url = new URL(wsUri);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept", "application/json");
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request.
			connection.connect();
			int rspCode = connection.getResponseCode();
			
			// Load in the response body.
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			String rspBody = sb.toString();

			if (rspCode == HttpURLConnection.HTTP_OK) {
				// Deserialize the SimpleUser.
				currentUser = new SimpleUser(rspBody);

				// Load the detail text view.
				TextView detailsTextView = (TextView) findViewById(R.id.detailsTextView);
				String userLabel = currentUser.getName() + " (" + currentUser.getId() + ")";
				detailsTextView.setText(userLabel);
				
				// Load the email edit view.
				EditText emailEditText = (EditText) findViewById(R.id.emailEditText);
				emailEditText.setText(currentUser.getEmail());
			}

			// Display response.
			String msg = Integer.toString(rspCode) + " " + connection.getResponseMessage();
			if (rspCode != 200) {
				if ((rspBody != null) && !rspBody.isEmpty())
					msg += ": " + rspBody;
			}

			connection.disconnect();
			
			Toast.makeText(SimpleUserRESTServiceClientActivity.this, msg, Toast.LENGTH_LONG).show();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	private void updateUserDetails() {
		URL url;
		HttpURLConnection connection = null;
		try {
			// Create connection with current email.
			String wsUri = getBaseContext().getResources().getString(R.string.rest_web_service_uri);
			url = new URL(wsUri);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("PUT");
			connection.setRequestProperty("Content-Type", "application/json");
			EditText emailEditText = (EditText) findViewById(R.id.emailEditText);
			Editable newEmail = emailEditText.getText();
			currentUser.setEmail(newEmail.toString());
			String userSer = currentUser.getJSONSerialization();
			connection.setRequestProperty("Content-Length", Integer.toString(userSer.getBytes().length));
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request.
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.writeBytes(userSer);
			dos.flush();
			dos.close();

			// Display response.
			int rspCode = connection.getResponseCode();
			String msg = Integer.toString(rspCode) + " " + connection.getResponseMessage();
			if (rspCode != 200) {
				// Load in any response body.
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				String rspBody = sb.toString();
				if ((rspBody != null) && !rspBody.isEmpty())
					msg += ": " + rspBody;
			}

			connection.disconnect();
			
			Toast.makeText(SimpleUserRESTServiceClientActivity.this, msg, Toast.LENGTH_LONG).show();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	private void deleteUser() {
		URL url;
		HttpURLConnection connection = null;
		try {
			// Create connection with current user.
			String wsUri = getBaseContext().getResources().getString(R.string.rest_web_service_uri);
			wsUri += currentUser.getId();
			url = new URL(wsUri);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("DELETE");
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request.
			connection.connect();
			int rspCode = connection.getResponseCode();

			// Display response.
			String msg = Integer.toString(rspCode) + " " + connection.getResponseMessage();
			if (rspCode != 204) {
				// Load in any response body.
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				String rspBody = sb.toString();
				if ((rspBody != null) && !rspBody.isEmpty())
					msg += ": " + rspBody;
			}

			connection.disconnect();
			
			Toast.makeText(SimpleUserRESTServiceClientActivity.this, msg, Toast.LENGTH_LONG).show();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
I'm a software developer in Toronto, Ontario who has programmed and studied mostly Java off and on since 2000.

Comments and Discussions