01: /*
02: * $Id: OrderPetImpl.java,v 1.9 2007/03/12 10:46:15 agoubard Exp $
03: */
04: package com.mycompany.petstore.api;
05:
06: import java.sql.ResultSet;
07: import java.sql.SQLException;
08: import java.sql.Statement;
09:
10: /**
11: * Implementation of the <code>OrderPet</code> function.
12: *
13: * <p>Description: Order a pet.
14: *
15: * @version $Revision: 1.9 $ $Date: 2007/03/12 10:46:15 $
16: * @author John Doe (<a href="mailto:john.doe@mycompany.com">john.doe@mycompany.com</a>)
17: */
18: public final class OrderPetImpl extends OrderPet {
19:
20: /**
21: * Constructs a new <code>OrderPetImpl</code> instance.
22: *
23: * @param api
24: * the API to which this function belongs, guaranteed to be not
25: * <code>null</code>.
26: */
27: public OrderPetImpl(APIImpl api) {
28: super (api);
29: }
30:
31: /**
32: * Calls this function. If the function fails, it may throw any kind of
33: * exception. All exceptions will be handled by the caller.
34: *
35: * @param request
36: * the request, never <code>null</code>.
37: *
38: * @return
39: * the result of the function call, should never be <code>null</code>.
40: *
41: * @throws Throwable
42: * if anything went wrong.
43: */
44: public Result call(Request request) throws Throwable {
45: if (!_sessionManager.getBoolProperty(_sessionManager
46: .getSessionId())) {
47: return new NotLoggedInResult();
48: }
49: int requestedQuantity = 1;
50: if (request.isSetQuantity()) {
51: requestedQuantity = request.getQuantity().intValue();
52: }
53:
54: try {
55: Statement statement = _databaseConnection.getConnection()
56: .createStatement();
57: ResultSet quantityQuery = statement
58: .executeQuery("SELECT quantity FROM PETS WHERE id="
59: + request.getPetID());
60: int stock = 0;
61: if (quantityQuery.next()) {
62: stock = quantityQuery.getInt(1);
63: }
64: if (stock <= 0) {
65: return new ProductNotAvailableResult();
66: }
67:
68: // Note that the quantity is not passed as input parameter.
69: // The user can only order one pet.
70: statement
71: .executeUpdate("INSERT INTO ORDERS (petid, email, quantity, status) VALUES ("
72: + request.getPetID()
73: + ", '"
74: + _sessionManager.getProperty("email")
75: + "', "
76: + requestedQuantity
77: + ", 'ordered')");
78:
79: statement.executeUpdate("UPDATE PETS SET quantity="
80: + (stock - requestedQuantity) + " WHERE id="
81: + request.getPetID());
82: } catch (SQLException sqlEx) {
83: return new DatabaseFailureResult();
84: }
85:
86: SuccessfulResult result = new SuccessfulResult();
87: return result;
88: }
89: }
|