import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class BurritoInventoryServlet extends HttpServlet { // How many "servings" of each item do we have? private int cheese = 0; private int rice = 0; private int beans = 0; private int chicken = 0; // Add to the inventory as more servings are prepared. public void addCheese(int added) { cheese += added; } public void addRice(int added) { rice += added; } public void addBeans(int added) { beans += added; } public void addChicken(int added) { chicken += added; } // Called when it's time to make a burrito. // Returns true if there are enough ingredients to make the burrito, // false if not. Decrements the ingredient count when there are enough. synchronized public boolean makeBurrito() { // Burritos require one serving of each item if (cheese > 0 && rice > 0 && beans > 0 && chicken > 0) { cheese--; rice--; beans--; chicken--; return true; // can make the burrito } else { // Could order more ingredients return false; // cannot make the burrito } } // Display the current inventory count. public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Current Ingredients"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("
Current ingredients:
Cheese:" + cheese + "
Rice:" + rice + "
Beans:" + beans + "
Chicken:" + chicken + "
"); out.println(""); } // Load the stored inventory count public void init(ServletConfig config) throws ServletException { super.init(config); loadState(); } public void loadState() { // Try to load the counts FileInputStream file = null; try { file = new FileInputStream("BurritoInventoryServlet.state"); DataInputStream in = new DataInputStream(file); cheese = in.readInt(); rice = in.readInt(); beans = in.readInt(); chicken = in.readInt(); file.close(); return; } catch (IOException ignored) { // Problem during read } finally { try { if (file != null) file.close(); } catch (IOException ignored) { } } } public void destroy() { saveState(); } public void saveState() { // Try to save the counts FileOutputStream file = null; try { file = new FileOutputStream("BurritoInventoryServlet.state"); DataOutputStream out = new DataOutputStream(file); out.writeInt(cheese); out.writeInt(rice); out.writeInt(beans); out.writeInt(chicken); return; } catch (IOException ignored) { // Problem during write } finally { try { if (file != null) file.close(); } catch (IOException ignored) { } } } }