Amazon SimpleDB Web Service with Typica API and Java
In this article I will explain how to use Amazon SimpleDB web service from a Java application.
I am going to create a student object. After creating the student object, we will use Amazon SimpleDB web service to create a student in Amazon SimpleDB database, update the student, list all students in the datbase, print count of students in the database, delete a student from the database.
All we are doing is CRUD operations [Create, Read, Update, Delete] with student object.
Prerequisites:
To test this you will need a Amazon SimpleDB account with Amazon Web Services.
Step 0: let us create a database in Amazon SimpleDB
com.xerox.amazonws.sdb.SimpleDB studentDB = new SimpleDB(key,password);
The key and password above are provided by Amazon web service, when you register with them.
Step 1: Now let us create our Student Domain
studentDB.createDomain(“student”);
Domain is same as a table in relational database with columns.
Each row in a domain is called item.
Each item will have attributes.
Each attribute will have a name and value.
Step 2: Create Student object (Student.java)
package com.vulab.domain;
import java.util.Date;
public class Student {
private String id;
private String salutation;
private String jobTitle;
private String department;
private String company;
private String firstName;
private String lastName;
private String addressLineOne;
private String addressLineTwo;
private String city;
private String state;
private String zip;
private String country;
private String workPhone;
private String workPhoneExtension;
private String fax;
private String homePhone;
private String cellPhone;
private String email;
private String userId;
private String password;
private String dateOfBirth;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSalutation() {
return salutation;
}
public void setSalutation(String salutation) {
this.salutation = salutation;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddressLineOne() {
return addressLineOne;
}
public void setAddressLineOne(String addressLineOne) {
this.addressLineOne = addressLineOne;
}
public String getAddressLineTwo() {
return addressLineTwo;
}
public void setAddressLineTwo(String addressLineTwo) {
this.addressLineTwo = addressLineTwo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getWorkPhoneExtension() {
return workPhoneExtension;
}
public void setWorkPhoneExtension(String workPhoneExtension) {
this.workPhoneExtension = workPhoneExtension;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
Step 3: Let us code the Student Data Access Object (StudentDAO.java) Create Read Update Delete Functionality
package com.vulab.dao;
import java.util.List;
import com.vulab.domain.Student;
public interface StudentDAO {
public Student createStudent(Student student)throws Exception;
public void updateStudent(Student student)throws Exception;
public Student getStudentById(int studentId)throws Exception;
public void deleteStudentById(int studentId)throws Exception;
public void deleteStudent(Student student)throws Exception;
public List<Student> getAllStudents()throws Exception;
public int getTotalCountOfStudents()throws Exception;
}
Step 4: Let us code the StudentDAO implementation (StudentDAOImpl.java)
package com.vulab.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.vulab.domain.Student;
import com.vulab.util.SimpleDBUtil;
import com.xerox.amazonws.sdb.Domain;
import com.xerox.amazonws.sdb.Item;
import com.xerox.amazonws.sdb.ItemAttribute;
import com.xerox.amazonws.sdb.QueryResult;
import com.xerox.amazonws.sdb.SimpleDB;
public class StudentDAOImpl implements StudentDAO {
public static final String domain = "student";
public Student createStudent(Student student) throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Item studentItem;
List<ItemAttribute> attributes = new ArrayList<ItemAttribute>();
Domain domain = studentDB.getDomain(this.domain);
Random randomGenerator = new Random();
int id = randomGenerator.nextInt(100000);
studentItem = domain.getItem(String.valueOf(id));
student.setId(String.valueOf(id));
attributes.add(new ItemAttribute("id", student.getId(), false));
attributes.add(new ItemAttribute("firstName", student.getFirstName(), false));
attributes.add(new ItemAttribute("lastName", student.getLastName(), false));
attributes.add(new ItemAttribute("addressLineOne", student.getAddressLineOne(), false));
attributes.add(new ItemAttribute("addressLineTwo", student.getAddressLineTwo(), false));
attributes.add(new ItemAttribute("city", student.getCity(), false));
attributes.add(new ItemAttribute("state", student.getState(), false));
attributes.add(new ItemAttribute("zip", student.getZip(), false));
attributes.add(new ItemAttribute("country", student.getCountry(), false));
attributes.add(new ItemAttribute("workPhone", student.getWorkPhone(), false));
attributes.add(new ItemAttribute("workPhoneExtension", student.getWorkPhoneExtension(), false));
attributes.add(new ItemAttribute("fax", student.getFax(), false));
attributes.add(new ItemAttribute("homePhone", student.getHomePhone(), false));
attributes.add(new ItemAttribute("cellPhone", student.getCellPhone(), false));
attributes.add(new ItemAttribute("email", student.getEmail(), false));
attributes.add(new ItemAttribute("userId", student.getUserId(), false));
attributes.add(new ItemAttribute("password", student.getPassword(), false));
attributes.add(new ItemAttribute("dateOfBirth", student.getDateOfBirth(), false));
attributes.add(new ItemAttribute("salutation", student.getSalutation(), false));
attributes.add(new ItemAttribute("jobTitle", student.getJobTitle(), false));
attributes.add(new ItemAttribute("department", student.getDepartment(), false));
attributes.add(new ItemAttribute("company", student.getCompany(), false));
studentItem.putAttributes(attributes);
return student;
}
public void updateStudent(Student student) throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
Item studentItem = domain.getItem(String.valueOf(student.getId()));
if(studentItem==null)
throw new Exception("Cannot update db as item does not exist in domain with id "+student.getId());
List<String> attributesToGet = new ArrayList<String>();
List<ItemAttribute> attrs = studentItem.getAttributes(attributesToGet);
List<ItemAttribute> attributes = new ArrayList<ItemAttribute>();
attributes.add(new ItemAttribute("id", student.getId(), true));
attributes.add(new ItemAttribute("salutation", student.getSalutation(), true));
attributes.add(new ItemAttribute("jobTitle", student.getJobTitle(), true));
attributes.add(new ItemAttribute("department", student.getDepartment(), true));
attributes.add(new ItemAttribute("company", student.getCompany(), true));
attributes.add(new ItemAttribute("firstName", student.getFirstName(), true));
attributes.add(new ItemAttribute("lastName", student.getLastName(), true));
attributes.add(new ItemAttribute("addressLineOne", student.getAddressLineOne(), true));
attributes.add(new ItemAttribute("addressLineTwo", student.getAddressLineTwo(), true));
attributes.add(new ItemAttribute("city", student.getCity(), true));
attributes.add(new ItemAttribute("state", student.getState(), true));
attributes.add(new ItemAttribute("zip", student.getZip(), true));
attributes.add(new ItemAttribute("country", student.getCountry(), true));
attributes.add(new ItemAttribute("workPhone", student.getWorkPhone(), true));
attributes.add(new ItemAttribute("workPhoneExtension", student.getWorkPhoneExtension(), true));
attributes.add(new ItemAttribute("fax", student.getFax(), true));
attributes.add(new ItemAttribute("homePhone", student.getHomePhone(), true));
attributes.add(new ItemAttribute("firstName", student.getFirstName(), true));
attributes.add(new ItemAttribute("lastName", student.getLastName(), true));
attributes.add(new ItemAttribute("cellPhone", student.getCellPhone(), true));
attributes.add(new ItemAttribute("email", student.getEmail(), true));
attributes.add(new ItemAttribute("userId", student.getUserId(), true));
attributes.add(new ItemAttribute("password", student.getPassword(), true));
attributes.add(new ItemAttribute("dateOfBirth", student.getDateOfBirth(), true));
studentItem.putAttributes(attributes);
}
public Student getStudentById(int studentId) throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
Item studentItem = domain.getItem(String.valueOf(studentId));
Student student = new Student();
List<String> attributesToGet = new ArrayList<String>();
List<ItemAttribute> attrs = studentItem.getAttributes(attributesToGet);
for (ItemAttribute currentAttribute : attrs) {
if (currentAttribute.getName().equals("id")) {
student.setId(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("salutation")) {
student.setSalutation(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("jobTitle")) {
student.setJobTitle(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("department")) {
student.setDepartment(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("company")) {
student.setCompany(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("firstName")) {
student.setFirstName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("lastName")) {
student.setLastName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("addressLineOne")) {
student.setAddressLineOne(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("addressLineTwo")) {
student.setAddressLineTwo(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("city")) {
student.setCity(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("state")) {
student.setState(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("zip")) {
student.setZip(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("country")) {
student.setCountry(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("workPhone")) {
student.setWorkPhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("workPhoneExtension")) {
student.setWorkPhoneExtension(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("fax")) {
student.setFax(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("homePhone")) {
student.setHomePhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("firstName")) {
student.setFirstName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("lastName")) {
student.setLastName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("cellPhone")) {
student.setCellPhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("email")) {
student.setEmail(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("userId")) {
student.setUserId(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("password")) {
student.setPassword(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("dateOfBirth")) {
student.setDateOfBirth(currentAttribute.getValue());
}
}
return student;
}
public void deleteStudentById(int studentId) throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
domain.deleteItem(String.valueOf(studentId));
}
public void deleteStudent(Student student) throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
domain.deleteItem(student.getId());
}
public List<Student> getAllStudents() throws Exception {
List<Student> studentList = new ArrayList<Student>();
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
List<Item> items;
QueryResult result = null;
result = domain.listItems();
items = result.getItemList();
List<String> attributesToGet = new ArrayList<String>();
for (Item studentItem : items) {
Student student = new Student();
List<ItemAttribute> attrs = studentItem.getAttributes(attributesToGet);
for (ItemAttribute currentAttribute : attrs) {
if (currentAttribute.getName().equals("id")) {
student.setId(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("salutation")) {
student.setSalutation(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("jobTitle")) {
student.setJobTitle(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("department")) {
student.setDepartment(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("company")) {
student.setCompany(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("firstName")) {
student.setFirstName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("lastName")) {
student.setLastName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("addressLineOne")) {
student.setAddressLineOne(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("addressLineTwo")) {
student.setAddressLineTwo(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("city")) {
student.setCity(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("state")) {
student.setState(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("zip")) {
student.setZip(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("country")) {
student.setCountry(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("workPhone")) {
student.setWorkPhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("workPhoneExtension")) {
student.setWorkPhoneExtension(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("fax")) {
student.setFax(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("homePhone")) {
student.setHomePhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("firstName")) {
student.setFirstName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("lastName")) {
student.setLastName(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("cellPhone")) {
student.setCellPhone(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("email")) {
student.setEmail(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("userId")) {
student.setUserId(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("password")) {
student.setPassword(currentAttribute.getValue());
} else if (currentAttribute.getName().equals("dateOfBirth")) {
student.setDateOfBirth(currentAttribute.getValue());
}
}
if (student.getId() != null)
studentList.add(student);
}
return studentList;
}
public int getTotalCountOfStudents() throws Exception {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
Domain domain = studentDB.getDomain(this.domain);
List<Item> items;
QueryResult result = null;
result = domain.listItems();
items = result.getItemList();
return items.size();
}
}
Step 5:let us create a Student Service (StudentService.java)
This service can be used by our web front end actions.
package com.vulab.service;
import java.util.List;
import com.vulab.domain.Student;
public interface StudentService
{
public Student createStudent(Student student)throws Exception;
public void updateStudent(Student student)throws Exception;
public Student getStudentById(int studentId)throws Exception;
public void deleteStudentById(int studentId)throws Exception;
public void deleteStudent(Student student)throws Exception;
public List<Student> getAllStudents()throws Exception;
public int getTotalCountOfStudents()throws Exception;
}
Step 6:let us implement the Student Service Interface (StudentServiceImpl.java)
package com.vulab.service;
import java.util.List;
import com.vulab.dao.StudentDAO;
import com.vulab.dao.StudentDAOImpl;
import com.vulab.domain.Student;
public class StudentServiceImpl implements StudentService {
StudentDAO studentDAO = new StudentDAOImpl();
public Student createStudent(Student student) throws Exception {
return studentDAO.createStudent(student);
}
public void updateStudent(Student student) throws Exception {
studentDAO.updateStudent(student);
}
public Student getStudentById(int studentId) throws Exception {
return studentDAO.getStudentById(studentId);
}
public void deleteStudentById(int studentId) throws Exception {
studentDAO.deleteStudentById(studentId);
}
public void deleteStudent(Student student) throws Exception {
studentDAO.deleteStudent(student);
}
public List<Student> getAllStudents() throws Exception {
return studentDAO.getAllStudents();
}
public int getTotalCountOfStudents() throws Exception {
return studentDAO.getTotalCountOfStudents();
}
}
Step 7:Let us write a JUnit test case to test our Student Service
package com.vulab.test.service;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import com.vulab.domain.Student;
import com.vulab.service.StudentService;
import com.vulab.service.StudentServiceImpl;
/* What are we doing in this test case
* we are creating a student in the domain student
* we are updating the created students first name and last name
* we are retrieving the updated object from database again and checking if the first name is updated
* we are listing all the students in the database
* we are printing the count of students in the database
* we are deleting a student from the database
* we are listing the students in the database after delete
* we are printing the number of students in the database after delete.
*/
public class TestStudentService extends TestCase
{
public void testCreate() throws Exception
{
Student student = new Student();
student.setAddressLineOne("116 Franklin Lane");
student.setAddressLineTwo("none");
student.setCellPhone("5454666");
student.setCity("Nainza");
student.setCompany("alpha");
student.setCountry("beta");
student.setDateOfBirth("june 6th 4532");
student.setDepartment("learn");
student.setEmail("beta@alpha.com");
student.setFax("2342342");
student.setFirstName("John");
student.setHomePhone("2342342342");
student.setJobTitle("learner");
student.setLastName("keller");
student.setPassword("secret");
student.setSalutation("Mr.");
student.setState("NJ");
student.setUserId("user32423");
student.setWorkPhone("534534534");
student.setZip("34345");
StudentService studentService = new StudentServiceImpl();
Student st = studentService.createStudent(student);
System.out.println("Created students first name: "+student.getFirstName());
System.out.println("Student with the following id is created "+st.getId());
student.setFirstName("karen");
student.setLastName("parker");
studentService.updateStudent(student);
System.out.println("Student is updated");
Student studentFromDB = studentService.getStudentById(Integer.parseInt(st.getId()));
System.out.println("Student first name is "+studentFromDB.getFirstName());
List<Student> studentList = new ArrayList<Student>();
studentList = studentService.getAllStudents();
System.out.println("listing all students");
for(Student std: studentList)
{
System.out.println("*************************");
System.out.println("Student Id: "+std.getId());
System.out.println("First Name: "+std.getFirstName());
}
System.out.println("Number of students in domain: "+studentService.getTotalCountOfStudents());
System.out.println("Now I am going to delete a student with id "+studentFromDB.getId());
studentService.deleteStudentById(Integer.parseInt(studentFromDB.getId()));
System.out.println("Now showing all students again");
List<Student> studentAgainList = new ArrayList<Student>();
studentAgainList = studentService.getAllStudents();
System.out.println("listing all students");
for(Student std: studentAgainList)
{
System.out.println("*************************");
System.out.println("Student Id: "+std.getId());
System.out.println("First Name: "+std.getFirstName());
}
System.out.println("Number of students in domain: "+studentService.getTotalCountOfStudents());
}
}
Step 8: Let us review the result from our JUnit testcase
Created students first name: John
Student with the following id is created 15509
Student is updated
Student first name is karen
listing all students
*************************
Student Id: 83746
First Name: John
*************************
Student Id: 39810
First Name: karen
*************************
Student Id: 15509
First Name: karen
Number of students in domain: 3
Now I am going to delete a student with id 15509
Now showing all students again
listing all students
*************************
Student Id: 83746
First Name: John
*************************
Student Id: 39810
First Name: karen
Number of students in domain: 3
Step 9: Additional Utility Classes used for achieving Step 0 and Step 1
For Step 0 & Step 1: To create a SimpleDB instance and then creating a domain called student, I am using the below two classes.
SimpleDBUtil.java
package com.vulab.util;
import com.xerox.amazonws.sdb.SimpleDB;
public class SimpleDBUtil
{
// Please get your own Key and Value from Amazon Web Service, Registration required.
public static final String key =”";
public static final String secret =”";
public static SimpleDB getDatabase()
{
if (key.equals(“”) || secret.equals(“”)) {
System.err.println(“Please fill in the key and secret with your Amazoin SimpleDB credentials”);
System.err.println(“If you don’t have credentials, please register with Amazon webservices to get one.”);
System.err.println(“Please rememeber that this is a paid service and play around carefully!!”);
System.err.println(“Warning: please do not share your secret key or you might end up with a huge bill!”);
System.exit(0);
}
SimpleDB studentDB = new SimpleDB(key,secret);
return studentDB;
}
}
SimpleDBCreateDomain.java
package com.vulab.util;
/* USAGE: use this program to create your database and table or domain in the database.
* Please run this only once as if you already have data in your domain. It will be lost
* on rerunning this program.
* This program will create a Database in SimpleDB named studentDB
* A domain or table named student will be created in studentDB
*/
import com.xerox.amazonws.sdb.*;
public class SimpleDBCreateDomain {
public static void main(String[] args) {
SimpleDB studentDB = SimpleDBUtil.getDatabase();
try {
studentDB.createDomain(“student”);
} catch (SDBException ex) {
System.err.println(“message : ” + ex.getMessage());
System.err.println(“requestID : ” + ex.getRequestId());
}
}
}
Step 10: Recap what we have done!
We created a SimpleDB instance using Amazon SimpleDB web service.
Tested CRUD functionality with a student object using Amazon Simple DB Web Service.
Step 11: What next?
This work is left for you. Create a domain called Course (learning course).
Enroll a student to a course using Amazon Simple DB and update the above Student Service to add the new functionality.
If you find this article useful, Please leave a comment.
API Used: Typica from Google Code
Typica is a java client library for a variety of Amazon Web Services. The name (TIP-ik-uh) was chosen because this is a coffee grown in Brazil, through which the Amazon flows. (has the Java and Amazon references)
list of jars being used:
- apache-mime4j-0.5.jar
- commons-codec-1.3.jar
- commons-httpclient-3.1.jar
- commons-logging-1.1.1.jar
- httpclient-4.0-beta2.jar
- httpcore-4.0.jar
- httpcore-4.0-beta3.jar
- httpcore-nio-4.0.jar
- httpmime-4.0-beta2.jar
- JAXB2_20070122.jar
- junit-4.5.jar
- typica.jar





