Navigation

    Cyberian
    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Pro Blog
    • Users
    • Groups
    • Unsolved
    • Solved
    Quiz 100% Result
    • CS506 Assignment 1 Solution and Discussion

      zareen

      Please read the following instructions carefully before solving & submitting assignment:

      Uploading Instructions:
      • You are not allowed to use any IDE tool like NetBeans for this assignment.
      • Use Notepad or Notepad++ for coding and JDK package for Java source code compilation and running.
      • Place all the source code (.java & .class files) in a Zip/RAR file, save with your own Student ID (e.g. bc000000000.zip) and Upload it on VULMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • No assignment will be accepted through email.

      Rules for Marking:
      It should be clear that your assignment will not get any credit if:

      o The assignment is submitted after due date.
      o The submitted assignment does not open or file is corrupted.
      o The assignment is fully or partially copied from other student or ditto copy from handouts or Internet; strict disciplinary action will be taken in this case.
      o The assignment is not submitted in .zip /.rar format.

      Note: Do not put any query on MDB regarding this assignment, if you have any query then email at
      Lectures Covered: This assignment covers Lecture # 1-9

      GOOD LUCK

      Problem Statement:
      You are required to write a Java program, named ShoppingCart, for a typical online shopping system. In which a user can add and remove items to the shopping cart. The program will allow the user to proceed with checkout by displaying all items of the shopping cart along with total bill. Further, user will also be fascinated by giving the option of emptying the shopping cart without buying anything. All will be done by using Java basic GUI component i.e. JOptionPane.

      Detailed Description:
      At start, your program should display an Input Dialog (i.e. JOptionPane.showInputDialog) and ask for following options;

      Add Item(s) to Cart

      Remove an Item from Cart

      Go to Checkout

      Empty the Cart

      Exit the Program
      325a7ed0-6918-478f-b72d-4089fb2951bc-image.png
      Fig. 1: Shopping Cart GUI

      Add Item(s) to Cart:

      Each time, user selects this option, s/he will be prompted via two Input Dialogs (i.e. JOptionPane.showInputDialog) for selecting an item from available items list (sample data is given below) and its quantity respectively. If inputs are correct (i.e. found no empty/null value and quantity is between 1 and 10) then selected item and its quantity will be added in the shopping cart by using ArrayList from java.util.* package.

      6d82a223-7546-4d70-8410-4ef52f73bbdb-image.png
      Fig. 2: Adding items in Shopping Cart

      Remove an Item from Cart:

      User can remove any item from the shopping cart by using this option; JOptionPane.showInputDialog should be used here. However, if shopping cart is already empty then message “Cart is empty” via JOptionPane.showMessageDialog should be displayed.

      3525bf78-d6b1-410d-b28e-cb85311d5b33-image.png
      Fig. 3: Remove an Item

      Go to Checkout:

      The program should first check if shopping cart contains any item; if not, it means no item is added yet so ask user to add a new item first. Otherwise, a Message Dialog (i.e. JOptionPane.showMessageDialog) will be opened, displaying all added items along with their quantity and prices. Furthermore, total number of items and grand total should be provided at bottom as well.
      b50126f2-d0fe-4194-a223-e9868bfc9bad-image.png
      Fig. 4: Go to Checkout
      4. Empty the Cart:

      User can remove all items from the shopping cart at once by using this option; successful deletion message should be displayed by using JOptionPane.showMessageDialog. However, if shopping cart is already empty then appropriate message like "Cart is empty" should be displayed.

      5e025e0e-385a-4bc6-88f1-257a4ea8f686-image.png
      Fig. 5: Empty the Cart
      5. Exit the Program:

      Exit option will terminate the program and show the developer information (i.e. Student Id and name) via JOptionPane.showMessageDialog.
      e3379e0d-f3fc-4e50-a9e5-b17939f45ccd-image.png
      Fig. 6: Developer Info
      Required Java Classes:
      For this purpose, you have to create three java classes (i.e. Product, Cart and MainClass). Data members, member functions and other details of these classes are given below;

      Product Class:

      • id: int • name: String • price: float • quantity: int • Constructors: default, parameterized and copy constructor • Standard Setters: setId(…), setName(…), setPrice(…), setQuantity(…) • Standard Getters getId(), getName(), getPrice(), getQuantity()

      Cart Class:

      Cart Class: • cartItems: ArrayList • Constructors: default, parameterized and copy constructor • Member Functions: addItem(…), removeItem(…), emptyCart(), getItemsList(), getProductIndex(…)

      Main Class:

      • myCart: Cart • Constructors: default, parameterized and copy constructor • Member Functions: main(), showGUI(), addItem(), removeItem(), checkOutCart(), removeAll(), developerInfo()

      Sample Data:
      d7ec6a16-87e3-4031-a64f-7ca48f75d253-image.png

      Important Things to Implement:

      For GUI, you have to use JOptionPane.showInputDialog and JOptionPane.showMessageDialog for taking input from user and showing output to user respectively. Use single ArrayList for adding/removing items to/from shopping cart. Need to make sure that exceptions are managed properly throughout the program; especially NullPointerException and NumberFormatException while taking input from user. All images and sample data, given in this document, are just for reference purpose only; you have to provide your own implementations. It is not required to be exactly the same.

      Good Luck

      CS506 - Web Design and Development
    • CS506 Past Mid Term Paper Solved By Moaaz

      cyberian

      Please share your Past and Current Paper to help in Midterm Exams.

      CS506 - Web Design and Development
    • CS506 Assignment 2 Solution and Discussion

      zaasmi

      Re: CS506 Assignment 2 Solution and Discussion

      Please read the following instructions carefully before solving & submitting assignment:

      Uploading Instructions:
      • You are not allowed to use any other software/IDE except NetBeans IDE for this assignment development.
      • The submission must be a complete NetBeans IDE project folder (which should contain complete source code, Java files, database file and builds etc.). After finalizing, compress it with Zip or RAR format, save with your own Student ID (e.g. bc000000000.zip) and submit it at VU-LMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • No assignment will be accepted through email.

      Rules for Marking:
      It should be clear that your assignment will not get any credit if:

      o The assignment is submitted after due date.
      o The assignment is not submitted in .zip /.rar format.
      o The submitted assignment does not open or file is corrupted.
      o The assignment is fully or partially copied from other student or ditto copy from handouts or Internet; strict disciplinary action will be taken in this case.
      o The submitted code is unable to compile/execute in NetBeans IDE; during evaluation, submitted code will be checked on NetBeans IDE. If unable to execute then ZERO marks will be awarded and no excuses will be accepted in this regard.

      Note: Do not put any query on MDB regarding this assignment, if you have any query then email at [email protected]
      Lectures Covered: This assignment covers Lectures # 1-16

      GOOD LUCK

      Problem Statement:
      You are required to develop a Java program named MyATM, which should simulate behavior of a typical ATM (Automated Teller Machine). In which a user, after entering card details, can deposit amount, withdraw cash and check current balance. The program should be based on a user friendly interface; need to use Java Swing based GUI components for this purpose. Further, all information must be saved in a backend database using MS Access.

      Detailed Description:
      At start, your program should ask the user to provide card number and pin code as input. After taking input from user the program should fetch user data corresponding to the input values from database and store in a class level global variable. Taking input from user is shown in figure no 1.

      Fig. 1: Taking input from User

      If input values are correct (i.e. found a user against provided card number and pin code) then following ATM services should be displayed via GUI;

      Deposit Amount Withdraw Cash Check Balance

      Fig. 2: ATM Services GUI

      However, in case if input values are not correct (i.e. found no user against provided card number and pin code) then appropriate message should be shown, like; “Invalid Card No or Wrong Pin Code”.

      Deposit Amount:

      Each time, user selects this option, s/he will be prompted to enter money for deposit that must be in multiple of Rs. 500/- (hint is given below) and up to a maximum of Rs. 25000/- per transaction. If inputs are correct then the amount must be added in current balance and as well as in database. However, in case of wrong input, appropriate message should be displayed.

      Fig. 3: Deposit Amount GUI
      2. Withdraw Cash:

      User can withdraw any cash but in multiple of Rs. 500/- (hint is given below) and up to a maximum of Rs. 25000/- per transaction by using this option. However, if balance is zero or withdraw amount is greater than the balance, then appropriate message should be displayed. Otherwise, amount must be deducted from current balance and as well as database should be maintained.

      Fig. 4: Cash Withdraw GUI

      Check Balance:

      The program should fascinate the user by displaying the current balance as well via GUI.

      Fig. 5: Check Balance GUI
      Note: At the end of each successful transaction, the user must be asked to proceed with another transaction or not; if yes then start from displaying ATM services again and if not then show developer information (i.e. Student Id and name) via GUI.

      Fig. 6: Developer Info
      Required Stuff:
      Java Classes:
      DebitCard.java (id,username,cardno,pincode,balance)
      DbHelper.java (should contain all database related code)
      MainClass.java (should contain GUI code)

      Database file:
      BSxxxxxxxx.accdb (must be same as your own VU student id)

      Note: need to put database file in assets folder in NetBeans project directory; as shown below;

      Fig. 7: Folder “assets” in NetBeans project directory
      Sample Data:
      Id Username Card No Pin Code Balance
      1 Ahmad 20201001 1041 3000
      2 Ali 20201002 1226 0
      3 Sana 20201003 2592 7000
      4 Amna 20201004 6372 12000
      5 Umar 20201005 9241 25000

      Tab. 1: Sample Users Data

      Tab. 2: Users Table in MS Access Database file
      Hint:
      if (amount % 500 == 0) {
      // it is a multiple of 500.
      }

      Setup Files & Video Tutorials:
       To download JDK setup file for Windows x64 , Download;

       To download JDK setup file for Windows x32 , please visit;

       To install JDK and create a HelloWorld program in Java, please watch;

       To install & create a HelloWorld Java program in NetBeans IDE, please watch;

       To use UCanAccess driver to connect with MS Access database, please watch;

      Important Things to Implement:
       For GUI, relevant components (i.e. JFrame, JPanel, JButton, JTextArea, JTextField and JLable etc.) from AWT and Swing packages should be used.
       You will have to use UCanAccess driver to connect to MS Access database. In this case, you are suggested to view the video tutorial shared above.
       For storing/fetching data to/from database, you will need to use proper SQL queries.
       Data must be stored/fetched to/from database table in the form of Java class object/s.
       You can use same Java classes (DebitCard and DbHelper etc.) as provided in assignment # 1 and also can make changes as required.
       Java classes must have proper Data Members and Member Functions along with Constructors, Standard Setters and Getters etc.
       Need to make sure that exceptions are managed properly throughout the program; especially NullPointerException, NumberFormatException, ClassNotFoundException and SQLException etc.
       All images, tables and sample data, given in this document, are just for reference purpose only; you have to provide your own implementations. It is not required to be exactly the same.

      Good Luck

      CS506 - Web Design and Development
    • CS506 Assignment 1 Solution and Discussion

      zaasmi

      Re: CS506 Assignment 1 Solution and Discussion

      Please read the following instructions carefully before solving & submitting assignment:

      Uploading Instructions:
      • You are not allowed to use any IDE tool like NetBeans for this assignment.
      • Use Notepad or Notepad++ for coding and JDK package for Java source code compilation and running.
      • Place all the source code (.java & .class files) in a Zip/RAR file, save with your own Student ID (e.g. bc000000000.zip) and Upload it on VULMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • No assignment will be accepted through email.

      Rules for Marking:
      It should be clear that your assignment will not get any credit if:

      o The assignment is submitted after due date.
      o The submitted assignment does not open or file is corrupted.
      o The assignment is fully or partially copied from other student or ditto copy from handouts or Internet; strict disciplinary action will be taken in this case.
      o The assignment is not submitted in .zip /.rar format.

      Note: Do not put any query on MDB regarding this assignment, if you have any query then email at [email protected]
      Lectures Covered: This assignment covers Lectures # 1 to 9

      GOOD LUCK

      Problem Statement:
      You are required to develop a Java program named MyATM, which should simulate behavior of a typical ATM (Automated Teller Machine). In which a user, after entering card details, can deposit amount, withdraw cash and view current balance. The program should be based on a user friendly interface; need to use Java basic GUI component (i.e. JOptionPane) for this purpose. Further, all information must be saved in a backend database using simple text file.

      Detailed Description:
      At start, your program should ask the user to provide card number (e.g. vu-bsxxxxxxx) and pin code (e.g. 1234) as input. After taking input from user the program should fetch user data corresponding to the input from database (i.e. text file) and store in a global variable (e.g. debitCard). Taking input from user is shown in figure no 1.

      Fig. 1: Taking input from User

      If input values are correct (i.e. provided values are same as given in text file) then following ATM services should be displayed via GUI;

      Deposit Amount Withdraw Cash Check Balance Exit the Program

      However, in case, if input values are not correct (i.e. found no user against provided card number and pin code) then appropriate message should be shown, like; “Invalid Card No or wrong Pin Code”. Fig. 2: ATM Services GUI

      Deposit Amount:

      Each time, user selects this option, s/he will be prompted to enter money for deposit that must be in multiple of Rs. 500/- (hint is given below) and up to a maximum of Rs. 25000/- per transaction. If inputs are correct then the amount must be added in current balance and as well as in database. However, in case of wrong input, appropriate message should be displayed.
      ef11517c-71c8-48c4-a485-1480435fac31-image.png
      Fig. 3: Deposit Amount GUIs

      Withdraw Cash:

      User can withdraw any cash but in multiple of Rs. 500/- (hint is given below) and up to a maximum of Rs. 25000/- per transaction by using this option. However, if balance is zero or withdraw amount is greater than the balance, then appropriate message should be displayed. Otherwise, amount must be deducted from current balance and database should be maintained.
      c6313333-e8ec-4fa8-a769-018f97ea70eb-image.png
      Fig. 4: Cash Withdraw GUIs

      Check Balance:

      The program should fascinate the user by displaying the current balance via GUI.
      e42491ae-8649-43e6-b89d-121a920bebc1-image.png
      Fig. 5: Check Balance GUI

      Exit the Program:
      369c8f49-00d0-4af7-a897-8b4f7d1dd64d-image.png

      Before exiting, the program should display the developer information (i.e. Student Id and name) via GUI.

      Fig. 6: Developer Info GUI
      Required Stuff:
      For this purpose, you have to create a text file and three separate Java classes, details are as follows;

      Text File:

      A simple text file, which should contain single line “vu-bsxxxxxxx,1234,0” in it and must be saved as bsxxxxxxx.txt.

      Here, “bsxxxxxxx” at both (i.e. file name and single line text) must be same as your own student id.
      And “vu-bsxxxxxxx” is card no, “1234” is pin code and “0” is initial balance.

      abd70d78-98cf-48e3-8491-692fc16402fb-image.png
      Fig. 7: Sample Data in Database (.txt file)

      DebitCard.java: Data Members: • cardNo: String • pin: int • balance: long Constructors: • default, parameterized & copy constructor Standard Setters: • setCardNo(…), setPin(…) & setBalance(…) Standard Getters: • getCardNo(), getPin()& getBalance() DbHelper.java: Data Members: • FILE_NAME: String // static and final variable Member Functions: • loadData() & saveData(…) Main Class: Data Members: • debitCard: DebitCard • dbHelper: DbHelper Constructor: • default Member Functions: • main(…), initLoginGUI(), initServicesGUI(), depositAmoount(), cashWithdraw(), checkBalance() & showDeveloperInfo() Hint: if (amount % 500 == 0) { // it is a multiple of 500. }

      Video Tutorials:
       To download & install JDK and create a HellowWorld program in Java, please watch;


       To download JDK setup file for Windows x64 from VU-LMS, please visit;

      Important Things to Implement:
       You have to provide Java classes in separate .java files as guided above. Merging of two or more will result in deduction of marks.
       Each Java class must have proper Data Members and Member Functions along with Constructors, Standard Setters and Getters etc. as discussed above.
       For GUI, you have to use JOptionPane.showInputDialog and JOptionPane.showMessageDialog for taking input from user and showing output to user respectively.
       Need to make sure that exceptions are managed properly throughout the program; especially NullPointerException and NumberFormatException while taking input from user.
       All images and sample data, given in this document, are just for reference purpose only; you have to provide your own implementations. It is not required to be exactly the same.

      Good Luck

      CS506 - Web Design and Development
    • CS506 MCQ's Final Term Paper

      zareen
      JSP ____________ action element is used to obtain a reference to an existing JavaBean object.

      Select correct option:
      useBean
      setProperty
      getProperty
      None of these
      Question:2
      When JSP page compiled, it is translated into?
      Select correct option:
      Applet
      Application
      Servlet
      Web Browser
      Question:3
      Hidden Forms Fields contain the information that is needed to send to the
      Select correct option:
      Client
      Server
      Both server and client
      Neither server nor client
      Question:4
      Which of the following is used to work with javaBean to include pages at request time and
      forward request to other sources?
      Select correct option:
      JSP action element
      JSP declaration
      Scriptlets
      JSP expression
      Question:5
      To define the error page in JSP we use following tag?
      Select correct option:
      exception-type
      error-type
      error-page
      exception-page

      Question:6
      setAttribute(String, Object) associates a ----------with a name.
      Select correct option:
      Value
      Object
      String
      Both String and Object
      Question:7
      “application” is a object of
      Select correct option:
      ServletContext
      HttpSession
      ServletConfig
      Both ServletConfig and HttpSession
      Question:8
      JSP comments are declared through following tag
      Select correct option:
      <%@ %>
      <%-- --%>
      <%! %>
      <%= %>
      Question:9
      Which of the following is NOT true about JavaBean?
      Select correct option:
      It should not have any public variable.
      It must be serializable.
      It must not have any zero argument constructor.
      Private instances must be accessed via setters/getters.
      Question:10
      JSP page is a ---------------document that describes how to process a request to create a response.
      Select correct option:
      Text-based
      xml-based
      Both text-based and xml-based
      Neither xml-based nor Text-based

      Question:11
      From the following which is not a basic function of web-based application:
      Select correct option:
      Presentation
      Debugging
      Business Logic
      Data Management
      Question:12
      Client is referred as a
      Select correct option:
      Computer user
      Computer that a person is using for communication purpose
      Person which carry out web surfing
      None of these
      Question:13
      To destroy the session in Servlet we use?
      Select correct option:
      session.destroy()
      session.invalidate()
      session.end()
      session.Kill()
      Question:14
      “application” is a object of
      Select correct option:
      ServletContext
      HttpSession
      ServletConfig
      Both ServletConfig and HttpSession
      Question:15
      Which of the following is NOT a JSP action element?
      Select correct option:
      useBean
      setProperty
      getProperty
      javaBean

      Question:16
      From the following indicators; which is added in user session to know the session time out?
      Select correct option:
      Sessiontimeoutindicator
      SessionTimeOutIndicator
      SessionTimeoutIndicator
      sessionTimeOutIndicator
      Question:17
      From following which one is the object of JspWriter used to send output to the client.
      Select correct option:
      request
      out
      response
      Both request and response
      Question:18
      Which of the following is NOT true about JavaBean?
      Select correct option:
      It should not have any public variable.
      It must be serializable.
      It must not have any zero argument constructor.
      Private instances must be accessed via setters/getters.
      Question:19
      Relationship between JSP and servlets is
      Select correct option:
      Servlets are built on JSP semantics and all servlets are compiled to JSP pages for runtime
      usage
      JSP and servlets are unrelated technologies
      Servlets and JSP are competing technologies for handling web requests. Servlets are
      being superseded by JSP, which is preferred. The two technologies are not useful in
      combination
      JSPs are built on servlet semantics and all JSPs are compiled to servlets for runtime usage
      Question:20
      getId( ) returns the unique ID of
      Select correct option:
      Current session
      Previous session
      Next session
      Both Next and Previous session

      Question:21
      Which of the following is used to work with javaBean to include pages at request time and
      forward request to other sources?
      Select correct option:
      JSP action element
      JSP declaration
      Scriptlets
      JSP expression
      Question:22
      Packages are the way to organize files into different -------------according to their functionality,
      usability as well as category they should belong to.
      Select correct option:
      Directories
      Folders
      Libraries
      Both Folders and Libraries
      Question:23
      getAttribute(String) extracts----------- stored value from a session object
      Select correct option:
      Subsequently
      Currently
      Previously
      Both Currently and Subsequently
      Question:24
      What is the initial contact point for handling a web request in a Page-Centric architecture?
      Select correct option:
      JSP page
      JavaBean
      servlet
      HTML page
      Question:25
      From the following methods, which method cannot be overridden in the JSP page
      Select correct option:
      _jspService()
      jspDestroy()
      jspInit()
      Both jspDestroy()and jspInit()

      Question:26
      JSP ____________ action element is used to obtain a reference to an existing JavaBean object.
      Select correct option:
      useBean
      setProperty
      getProperty
      None of these
      Question:27
      In JSP Instance variables and method are declared through following tag
      Select correct option:
      <%@ %>
      <%-- --%>
      <%! %>
      <%= %> (not sure)
      Question:28
      All -----------data is kept at the application server.
      Select correct option:
      Dynamic
      Static
      Both dynamic and static
      Neither Static nor Dynamic
      Question:29
      A java program that has some design conventions is called_________?
      Select correct option:
      Java servlet
      JSP
      JSF
      JavaBean
      Question:30
      A cookie is a piece of ------- that a web server can store on a client’s hard disk.
      Select correct option:
      Text
      Number
      String
      Both Number and String

      Question:32
      Which of the following Environment variable tells the system about the root directory of TOMCAT?
      Select correct option:
      JAva_HOME
      CATALINA_HOME
      CLASSPATH
      PATH
      Question:33
      Which of the following statement is correct to assign maximum priority to thread “t2”?
      Select correct option:
      t2.setPriority(Thread.PRIORITY_MiX);
      t2.setPriority(Thread.PRIORITY_MAX)
      t2.setPriority(Thread.MAX_PRIORITY);
      t2.setPriority(Thread.MIX_PRIORITY);
      Question:34
      Which of the following object contains information specific to a servlet?
      Select correct option:
      ServletContext
      ServletConfig
      ServletRequest
      ServletResponse
      Question:35
      Which of the following range of response code signify error by server?
      Select correct option:
      200-299
      300-399
      400-499
      500-599
      Question:36
      From the following which ID is transmitted between the client and the server
      Select correct option:
      Session ID
      Network ID
      Server ID
      None of these
      Question:37
      Which of the following is NOT a web technoloy of Java?
      Select correct option:
      Servlet
      JSP
      ASP
      JSF
      Question:38
      Moving session from one server to another in case of server failure is known as
      Select correct option:
      Session Migration
      Session Tracking
      Session Hijacking
      Both Session Hijacking and Tracking
      Question:39
      Which one is used to collect data when a user navigates between web pages?
      Select correct option:
      Session Tracking
      User Tracking
      Session Migration
      Both User Tracking and Session Migration
      Question:40
      Which of the following method allows any other thread of same priority to execute?
      Select correct option:
      sleep()
      wait()
      notify()
      yield()
      Question:41
      From the following which session tracking technique is used when new session is started?
      Select correct option:
      Cookies
      URL Rewriting
      Both Cookies and URL Rewriting
      None of these
      Question:42
      Which of the following object is used for sharing resources among different servlets of same
      application?
      Select correct option:
      ServletConfig
      ServletRequest
      ServletResponse
      ServletContext
      Question:43
      Which of the following interface needs to implement while creating threads?
      Select correct option:
      Serializable
      Runnable
      ActionListener
      WindowListener

      Question:44
      Session Tracking is done through following techniques?
      Select correct option:
      Cookies
      Hidden fields
      URL Rewriting
      Cookies, Hidden fields and URL Rewriting
      Question:45
      Servlets are used to
      Select correct option:
      Create graphics
      Provide dynamic web contents which extend web servers
      Develop applets
      Create GUI
      Question:46
      Which of the following is/are not correct about Thread(s)?
      Select correct option:
      Light weight
      Heavy weight
      Share same memory
      Light weight and share same memory
      Question:47
      From following which code can be used to create session object in the Servlet:
      Select correct option:
      HttpSession session = req.getSession(true);
      HttpSession session = req.getSession(false);
      HttpSession session = req.getSession(1);
      HttpSession session = req.setSession(1);
      Question:48
      JVM assigns CPU to the threads based on __________.
      Select correct option:
      Thread priorities
      System priorities
      Collective priorities
      Both System and Collective priorities
      Question:49
      Which of the following method is called only once during life cycle of Servlet?
      Select correct option:
      service()
      init()
      destroy()
      start()
      Question:50
      HTTP is a ---------protocol.
      Select correct option:
      Stateless
      Connectionless
      Connection oriented
      Both Connectionless and Stateless
      Question:51
      Which of the following is NOT true about HTTP?
      Select correct option:
      HTTP is a stateless protocol
      HTTP is a request response communication model
      HTTP maintains user session between successive requests.
      HTTP has no built-in state management between successive requests.
      Question:52
      Why we use RequestDispatcher to forward a request to another resource(servlet, html, jsp), instead of
      using a sendRedirect()?
      Select correct option:
      sendRedirect() is not supported in servlet API.
      RequestDispatcher is not supported in servlet API.
      RequestDispatcher is efficient and allows the server to maintain request status.
      None of these not sure
      Question:53
      getParameters() method returns an array of strings containing the values for a specified servlet
      parameter.
      Select correct option:
      True
      False
      Question:54
      Which of the following is not the part of http response?
      Select correct option:
      Result Code
      Header files
      Status code
      URI
      Question:55
      web.xml is a ___________
      Select correct option:
      java file
      configuration file
      jar file
      servlet file

      Question:56
      A ______ is a small text file used by servers to store pieces of data on a client for later retrieval.
      Select correct option:
      session
      cookie
      URL rewriting
      Session object
      Question:57
      HttpSession stores session information in
      Select correct option:
      File system of client
      File system of server
      A cookie
      A session object not sure
      Question:58
      Which of the following is NOT a part of HTTP request?
      Select correct option:
      Request method
      URI
      Status code
      Header fields
      Question:59
      Which of the following folder contains configuration file?
      Select correct option:
      classes
      lib
      bin
      WEB-INF
      Question:60
      Which of the following problem occurs with lower priority threads?
      Select correct option:
      Race condition
      Starvation
      Average waiting time
      Process death
      Question:61
      Which of the following approch is used to create threads in java?
      Select correct option:
      inheritance
      interface
      Both inheritance and interface
      None of these

      Question:62
      Which of the following method needs to override while handling threads in java?
      Select correct option:
      init()
      start()
      run()
      runnable()
      Question:63
      From the following packages which one is used to write the servlets?
      Select correct option:
      javax
      java
      java.util
      java.lang
      Question:64
      Servlets are used to
      Select correct option:
      Create graphics
      Provide dynamic web contents which extend web servers
      Develop applets
      Create GUI
      Question:65
      getrequest() method gets information from a client and postrequest() method posts data to a
      client.
      Select correct option:
      False
      True
      Question:66
      JSP scripting elements is/are
      Select correct option:
      Declarations
      Scriptlets
      expressions
      All of these
      Question:67
      From following methods; which method is not a part of the JSP life cycle?
      Select correct option:
      jspInit()
      jspService()
      _jspService()
      jspDestroy()

      Question:68
      From the following which one is not a JSP directive?
      Select correct option:
      page
      include
      taglib
      out
      Question:69
      To provide global control of JSP we use following tag
      <%@ %> right Answer)
      <%-- -%>
      <%! %>
      <%= %>
      Question:70
      javax.servlet.jsp.PageContext, is used to give a ---------point of access to many of the page
      attributes.
      Select correct option:
      Single
      Multiple
      Question:71
      In JSP Instance variables and method are declared through following tag
      Select correct option:
      <%@ %>
      <%-- --%>
      <%! %>
      <%= %>
      Question:72
      Which of the following approach is also called page-with-bean approach.
      Select correct option:
      Page-Centric approach
      MVC Model1
      MVC Model2
      MVC Model3

      Question:73
      A separate controller is a part of which of the following approach?
      Select correct option:
      Page-Centric approach
      MVC Model1
      MVC Model2
      MVC Model3
      Question:74
      From following tags, which one is the Special JSP tag?
      Select correct option:
      <jsp: .…. />
      <%! %>
      <%= %>
      <%@ %>
      Question:75
      JSTL stands for __.
      JavaServer Pages Standard Tag Library
      JavaSrvlet Pages Standard Tag Library
      Java Pages Standard Tag Library
      Question:76
      JSP page is a ---------------document that describes how to process a request to create a response.
      Text
      XML
      Both
      None
      Question:77
      A java program that has some design conventions is called

      java sevlet
      jsp
      jsf
      javabean

      Question:78
      Which of the following is not included in simple tag while creating JSP custom tags?
      Select correct option:
      Start of tag
      End of tag
      Attributes
      None of these
      Question:79
      Which of the following represent state of the components in MVC?
      Model
      View
      Control
      Both Model and View
      Question:80
      A user defined component that is used to perform certain action is called______.
      Select correct option:
      Built-in Tags
      JSP action element
      Custom tag not sure
      jsp:useBean
      Question:81
      A Tier represents the _______ view of application.
      Select correct option:
      Physical
      Logical
      Biological
      Local
      Question:82
      Which of the following is the best choice as a controller in MVC Model Architecture?
      Select correct option:
      Java
      Servlet
      JavaScript
      JSP

      Question:83
      . The HTTP response values in the range __________ specify that the request was successful.
      100-199
      200-299
      300-399
      400-499
      Question:84
      With the help of _____________ we can better organize our files into different directories.
      Classes
      Interfaces
      Session
      Packages
      Question:85
      . Entire JSP page gets translated into a servlet ____________.
      Once (pg 323)
      Every time when it is accessed
      Every time when the page is refreshed
      Every time when the browser is restarted
      Question:86
      A bean class ___________ have a zero argument constructor.
      Can
      Can’t
      Must (pg 356)
      Shouldn’t
      Question:87
      . Layers represent the _____________ view of application.
      Physical
      Logical (pg 435)
      External
      None of these
      Question:88
      High coupling makes classes difficult or impossible to reuse because _____________.
      They are independent of other classes
      They depend on so many other classes
      They have limited functionality
      They are not properly implemented
      Question:89
      _____________ is a standard web based application framework.
      Java

      Servlet
      JSP
      JSF
      Question:90
      Which of the following is a correct order for Bean scope in JSP page from most visible to least
      visible?
      application, session, request, page
      page, request, session, application
      session, page, request, application
      application, session, page, request
      Question:91
      The dot operator in Expression Language is typically used for accessing the --------------------of
      an object.
      Properties (pg 458)
      Elements
      Values
      Attributes
      Question:92
      Initialization parameters of a servlet are defined in __________ file.
      html
      JSP
      web.xml (pg 275)
      servlet
      Question:93
      On every request from the client, the server creates a new ________ and calls the _______
      method.
      thread, service()
      thread, init()
      process, service()
      process, init()
      Question:94
      . By ____________, the original request can be forwarded to the next servlet.
      request dispatching
      response redirection
      both request dispatching and response redirection
      None of the given options
      Question:95
      Which of the following is NOT appropriate for Page-centric approach?
      The maintenance of the application becomes a nightmare.

      A lot of code is also get duplicated.
      Scaling of such kind of application is easy. (pg 397)
      The code becomes a mixture of presentation, business and data access logic.
      Question:96
      Which of the following ‘statement’ object is used for executing precompiled SQL statements?
      Statement
      PreparedStatement (pg 147)
      CallableStatement
      None of the given options
      Question:97
      RPC stands for
      Remote Personal Computer (RPC)
      Remote Procedure Client
      Remote Procedure Calls (RPC).
      None of the given options
      Question:98
      . UDDI stands for
      Universal Description, Discovery & Integration (UDDI) (pg490)
      Universal Data, Discovery & Integration (UDDI)
      Universal Data, Database & Integration (UDDI)
      None of the given options
      Question:99
      Managed Beans have _______ Model
      Declarative
      Sequential
      Iterative
      None of the given options (pg465) Managed beans represent the data model
      Question:100
      DataBaseMetaData object can be derived from ___________ object.
      ResultSet
      Connection (pg165)
      Statement
      ResultSetMetaData
      Question:101
      DSN stands for ___________.
      Domain System Name
      Data Source Name (pg150)
      Database System Name
      Database Simple Name

      Question:102
      From following functions which function is invoked first?
      paint()
      paintComponet( )
      paintBorder( )
      paintChildern( )
      Question:103
      There is/are _____ form(s) of response redirection.
      1
      2 (pg 270)
      3
      4
      Question:104
      Expression is a code fragment which returns ___________.
      Integer
      String (pg326)
      Depends on the expression
      Nothing
      Question:105
      The dot operator in Expression Language is typically used for accessing the --------------------of
      an object.
      Properties (pg458)
      Elements
      Values
      Attributes
      Question:106
      The sleep(int time) method causes the currently executing thread to wait for the time specified
      in --------------
      Milliseconds (pg221)
      Nenoseconds
      Seconds
      Minutes
      Question:107
      Java was developed in………
      1990
      1994
      1995
      1996

      Question:108
      CREATE TABLE, DROP TABLE, and ALTER TABLE etc are -----------.
      DML statements
      DDL statements(pg144)
      DCL statements
      None of given options
      Question:109
      Extra sheet can be appended to URL using _________
      i. Extra path information
      ii. Added Parameters
      iii. Custom Change
      iv. All of the given options
      Question:110
      Initialization ________ of web application are also called ______________
      i. Parameters, Context Attributes not sure
      ii. Context Attributes, Parameters
      iii. Parameters, Variables
      iv. Context Attributes, Variables
      Question:111
      J2EE is developed for which of the following application
      i. Very large applications
      ii. GUI based applications
      iii. Mobile devices
      iv. Network based applications
      Question:112
      ODBC stands for ______________
      i. Open database communication
      ii. Open database connection
      iii. Open database connectivity
      iv. Open database Commission
      Question:113
      Which of the following command is used to compile Java code?
      i. java filename
      ii. javac filename.java
      iii. javac filename
      iv. java filename.java

      Question:114
      What if the main method is declared as private?

      The program does not compile The program compiles but does not run The program compiles and runs properly The program throws an exception on compile time
      Question:115
      Java program code is compiled into form called Machine code native Code Byte Code Source Code
      Question:116
      A top level class without any modifier is accessible to any class any class within the same package any class within the same file any subclass of this class
      Question:117
      Overloading is _______ whereas overriding is _____ Run time binding, compile time binding Late binding, compile time binding Compile time binding, run time binding Run time binding, late time binding
      Question:118
      Static methods only access ___ instance variable instance method static variables and methods both static and instance members
      Question:119
      Which of the following is modifier is provided by default if no access is written explicitly? public Private Protected Default
      Question:120
      A top level class may have only the following access modifier. Package Private Protected Public

      Question:121
      Which of the following is used for inheritance in java?

      implements extends : (colon) inherit
      Question:122
      A collection can store … Homogenous objects Heterogeneous objects Objects as well as primitive values At most 100 objects
      Question:123
      Window frame and dialog use ________ as their default layout. Border layout Flow layout GridBag layout Grid layout
      Question:124
      There are _________ types of exceptions in Java 2 3 4 5
      Question:125
      Which of the following belongs to a category of checked exception? Null Pointer exception IOException Array index out of bounds NumberFormatException
      Question:126
      Which of the following exception belongs to a category of un-checked exception? IOException Null Pointer exception AWTException ClassNotFoundException

      Question:127
      All the exceptions and errors in java are inherited from _____ class.

      Exception Error Throwable IOException
      Question:128
      Exceptions must be handled while handling files otherwise it may lead to _____ Logical error Syntax error Run-time error No error
      Question:129
      Which of the following package needs to be import while handling files? java.util java.io java.awt javax.swing
      Question:130
      When defining a method you must include a/an … to declare any exception that
      might be thrown but is not caught in the method: try block finally block catch block throws clause
      Question:131
      Which of the following syntax is used to attach an input stream to console ? FileReader fr = new FileReader(’ input.txt ') ; FileReader fr = new FileReader(FileDescriptor.in); FileReader fr = new FileReader(FileDescriptor); FileReader fr = new FileReader(console);
      Question:132
      The classes which contain the word _____ are byte oriented streams. Reader Writer Stream Byte

      Question:133
      Which of the following stream read/write data in the form of bytes?

      FileReader FileWriter PrintWriter FileInputStream
      Question:134
      Which of the following is called ’ pure abstract class ’ ? Concrete class Wrapper class Interface Abstract class with no abstract method
      Question:135
      Which of the following is true about abstract class? An abstract class must have all methods declared as abstract methods. A class must have at least one abstract method to be an abstract class. A class without any abstract method can be declared as abstract class. An instance of abstract class can be created.
      Question:136
      Which of the following stream is a filter stream? FileWriter FileReader BufferedReader All of given options
      Question:137
      An instance of abstract class cannot be created. TRUE FALSE
      Question:138
      Anabstractclass ---------------instantiated. Cannot be Can be Must None of these
      Question:139
      The relationship between class and interface is called ________ ’ Is a ’ relationship ’ Has a ’ relationship ’ Responds to ’ relationship

      Question:140
      BorderLayout is the default layout manager for a JFrame content pane

      TRUE FALSE
      Question:141
      Which of the following is a general purpose container? JFrame Dialog JPanel JApplet
      Question:142
      JPanel and Applet use ________ as their default layout. Flow layout Border layout Grid layout GridBag layout
      Question:143
      Which of the following is true about AWT and SWING components? AWT components creates a process whereas SWING component creates a
      thread. AWT components creates a thread whereas SWING component creates a
      process. Both AWT and SWING component creates a process. Both AWT and SWING component creates a thread.
      Question:144
      Which of the following function will be used to register event handler with events
      generator (button)? addAction() addActionListener() addListener() registerListener()
      Question:145
      Event source can have --------- listeners registered on it. Single Double Triple Multiple

      Question:146
      If a class needs to handle events generated by button then which of the following
      interface a class needs to implement?

      ComponentListener KeyListener MouseListener ActionListener
      Question:147
      Which of the following function is declared in MouseMotionListener interface?
      public void mousePressed (MouseEvent me); public void mouseDragged (MouseEvent me); public void mouseClicked (MouseEvent me); public void mouseEntered (MouseEvent me);
      Question:148
      WindowListener interface contains _______ methods. Four Six Seven Eight
      Question:149
      Mouse events can be trapped for ________ GUI component. JPanel JFrame JButton All of given
      Question:150
      Adapter classes have been defined for listener interfaces except ______ interface. MouseListener KeyListener WindowListener ActionListener
      Question:151
      Which of the following package needs to import while interacting with relational
      database? java.io java.sql javax.swing java.awt

      Question:152
      Which of the following method is used to execute SELECT SQL statements?

      executeUpdate(sql); ExecuteUpdate(sql); executeQuery(sql); ExecuteQuery(sql);
      Question:153
      Which of the following method is used to execute INSERT, UPDATE and Delete SQL
      statements? executeQuery(sql); ExecuteQuery(sql); executeUpdate(sql); ExecuteUpdate(sql);
      Question:154
      Which of the following statement object is used to execute stored procedures? Statement PreparedStatement CallableStatement None of given options
      Question:155
      HahMap takes key as a/an _________ Object Array Primitive value Function
      Question:156
      A …defines the way and method of communication between two parties Compiler Protocol Tool Technique
      Question:155
      To create DataBaseMetaData object we write following line of code
      DataBaseMetaData db = con.getMeataData(); ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.setMetaData(); DataBaseMetaData db = con.setMeataData();

      Question:156
      Which of the following are passed as an argument to the paint () method:

      A Canvas object2. A Graphics object3. An Image object4. A paint objectQuestion:157
      The code below draws a line. What color is the
      line?g.setColor(Color.red.green.yellow.red);g.drawLine(0, 0, 100,100); Red Green Yellow Black
      Question:158
      Which of the following methods are invoked by the AWT to support paint and repaint
      operations? paint( ) repaint( ) draw( ) redraw( )
      Question:159
      If a super class method is protected then overriding method _________ must be protected must be public must be private may be either protected or public
      Question:160
      Socket is a --------------communication channel between hosts. Uni-directional Bi-directional Multi-directional None of these
      Question:161
      You can ---------to a network using sockets. Read Write Read/Write None of these

      Question:162
      A serializable class must implement the method(s)…

      readObject and writeObject Either readObject or writeObject, or both, depending upon the desired behavior No need to implement any method: None of the given option
      Question:163
      Aside from the Scanner class, which of the following class/es can be used for text file
      file input ObjectInputStream BufferedReader StringTokenizer None of these
      Question:164
      In which of the following application we do not need to maintain sessions Cause registering web application Web based shopping carts Web reputation systems Windows shopping systems
      CS506 - Web Design and Development
    • CS506 GDB 1 Solution and discussion

      zareen

      Re: CS506 Gdb1 Solution and discussion

      GDB Topic:

      In general, a typical Java program is dealt with the following kinds of thread:

      Main Thread; initial application code is executed.

      Worker Thread; time-consuming and background tasks are executed.

      Well, Java based smart devices (embedding Java code in smart devices) have revolutionaries the human life. At one side, these devices provide ease of use of technology. But on the other side, their unresponsiveness or delay in response to user’s actions may result in human frustration. One of the main reasons is, these devices mostly run on a single Main Thread.

      Being a Java developer what do you think, “Use of Worker Threads along with Main Thread will reduce the response delay or increase the work load in Java based Smart Devices?”

      CS506 - Web Design and Development
    • CS506 Assignment 2 Solution and Discussion

      mehwish

      Please read the following instructions carefully before solving & submitting assignment:

      Uploading Instructions:
      • You are not allowed to use any other software/IDE except NetBeans IDE for this assignment development.
      • The submission must be a complete NetBeans IDE project folder (which should contain complete source code, Java files, database file and builds etc.). After finalizing, compress it with Zip or RAR format, save with your own Student ID (e.g. bc000000000.zip) and submit it at VU-LMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • No assignment will be accepted through email.

      Rules for Marking:
      It should be clear that your assignment will not get any credit if:

      o The assignment is submitted after due date.
      o The assignment is not submitted in .zip /.rar format.
      o The submitted assignment does not open or file is corrupted.
      o The assignment is fully or partially copied from other student or ditto copy from handouts or Internet; strict disciplinary action will be taken in this case.
      o The submitted code is unable to compile/execute in NetBeans IDE; during evaluation, submitted code will be checked on NetBeans IDE. If unable to execute then ZERO marks will be awarded and no excuses will be accepted in this regard.

      Note: Do not put any query on MDB regarding this assignment, if you have any query then email at [email protected]
      Lectures Covered: This assignment covers Lecture # 1-17

      GOOD LUCK

      Problem Statement:
      You are required to write a Java program, named ShoppingCart, for a typical online shopping system. In which a customer can add and remove items to the shopping cart. The program will calculate the total bill as the items are added/removed to/from shopping cart and will display the amount via user friendly Interface on real time basis. Further, all orders will be saved in a backend database using MS Access so that the administrator could process the orders properly.

      Detailed Description:
      At start, your program should read Products Data from MS Access database file (sample data is given below) and display a GUI (i.e. Graphical User Interface) which should contain options for selecting quantity of products, sample is given below;
      341e4e99-97bf-4778-9bd0-433661098b3a-image.png
      Fig. 1: Shopping Cart GUI

      Here, the customer can select the quantity (i.e. 0 to 10) for available products by clicking on add (+) or remove (–) buttons; the cart should be updated on each action and correct amount after calculating the number of items, subtotal, shipping charges (shipping charges are given below) and grand total should be displayed.
      When user clicks on “Place Order” then the program should check whether the cart contains any item or not. If cart is empty then a message “Cart is empty!” should be displayed. Otherwise, order details will be saved to MS Access database file and interface will be updated with initial values (i.e. zero quantity for each item and zero in amount fields etc.) as well.
      Further, cross icon at top right corner of the interface should terminate the program and show the developer information (i.e. Student Id and name) via message dialog.

      f8c497e7-b1fb-4061-b8f1-0482a4d0964f-image.png
      Fig. 2: Developer Info
      Required Stuff:
      Java Classes:
      Product.java
      Cart.java
      DatabaseHelper.java (should contain all database related code)
      MainClass.java (should contain GUI code)

      Database file:
      BSxxxxxxxx.accdb (must be same as your own VU student id)

      Note: need to put database file in assets folder in NetBeans project directory; as shown below;

      3f4b9edd-cb2b-46c0-98c2-7328cc407584-image.png
      Fig. 3: Folder “assets” in NetBeans project directory
      Sample Data:

      Item Price ($)

      1 Orange 2.0
      2 Grapes 2.5
      3 Banana 1.5
      4 Mango 3.0

      Tab. 1: Sample Products Data

      No of Items Charges

      1 0 $0
      2 1 to 5 $0.5
      3 6 to 10 $1.0
      4 11 to 15 $1.5
      5 16 to 20 $2.0
      6 21 to 25 $2.5
      7 26 to 30 $3.0
      8 31 to 35 $3.5
      9 More than 35 $4.0

      Tab. 2: Sample Shipping Charges
      4a742fd6-860e-442b-a04f-1bdfb9f7bd90-image.png

      Tab. 3: Products Table in MS Access Database file
      09e2f9aa-a389-4c54-8c0d-179818ac5760-image.png
      Tab. 4: Orders Table in MS Access Database file
      Important Things to Implement:
       For GUI, relevant components (i.e. JFrame, JPanel, JButton, JTextField and JLable etc.) from AWT and Swing packages should be used.
       You will have to use ucanaccess driver to connect to MS Access database. In this case, you are suggested to view the following video tutorial.


       For storing/fetching data to/from database, you will need to use proper SQL queries.
       You can use same Product and Cart Java classes as provided in assignment # 1 and also can make changes as required.
       Java classes must have proper Data Members and Member Functions along with Constructors, Standard Setters and Getters etc.
       Need to make sure that exceptions are managed properly throughout the program; especially NullPointerException, ClassNotFoundException and SQLException.
       All images, tables and sample data, given in this document, are just for reference purpose only; you have to provide your own implementations. It is not required to be exactly the same.

      Good Luck

      CS506 - Web Design and Development
    • CS506 Assignment 3 Solution and Discussion

      zareen

      Please read the following instructions carefully before solving & submitting assignment:

      Uploading Instructions:
      • You are not allowed to use any other software/IDE except NetBeans IDE for this assignment development.
      • The submission must be a complete NetBeans IDE project folder (which should contain complete source code; Java files, servlet files, html files, database file, xml files and builds etc.). After finalizing, compress it with Zip or RAR format, save with your own Student ID (e.g. bs1234567890.zip) and submit it at VU-LMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • No assignment will be accepted through email.

      Rules for Marking:
      It should be clear that your assignment will not get any credit if:

      o The assignment is submitted after due date.
      o The assignment is not submitted in .zip/.rar format.
      o The submitted assignment does not open or file is corrupted.
      o The assignment is fully or partially copied from other student or ditto copy from handouts or Internet; strict disciplinary action will be taken in this case.
      o The submitted code is unable to compile/execute in NetBeans IDE; during evaluation, submitted code will be checked on NetBeans IDE. If unable to execute then ZERO marks will be awarded and no excuses will be accepted in this regard.

      Note: Do not put any query on MDB regarding this assignment, if you have any query then email at [email protected]

      Lectures Covered: This assignment covers Lecture # 1 - 30

      GOOD LUCK
       
      Problem Statement:
      You are required to deploy a basic web application using Apache Tomcat Server, named ShoppingCart, for a typical online shopping system. In which a customer can add/remove items to shopping cart and proceed to place order. The program should calculate total bill and display amount via web page. Further, all orders will be saved in a backend database using MS Access so that administrator could process accordingly.

      Detailed Description:
      The program should facilitate at least one user i.e. Customer. For this purpose, you have to develop an html page (index.html) which should contain a login form, as shown in figure 1. dca5c0c8-9b76-4276-a4c9-c80ac85dbacf-image.png

      The customer should be able to login by using student id (must be your own student id) as username and “vu” as password.

      Now, write a Java Servlet named as LoginServlet.java that will receive submitted information from login form (i.e. index.html) and verify input values; whether entered values are correct or not. If authentication is invalid then print back a message “Invalid Username or Password”.

      If customer credentials (i.e. username and password) are correct, jump to Shopping Cart Page (i.e. ShoppingCartServlet.java) which should list down all available products (i.e. products having one or more items), as shown in figure 2.
      28cacaf4-26e4-4269-9a88-8beb86b51fe3-image.png
      Here, customer can provide quantity of desired product/s and click on Check Out button. If no item is selected (i.e. no quantity is provided), then a message “Cart is empty” should be displayed.

      On the other hand, if cart is not empty, Checkout Page (i.e. CheckOutServlet.java) should serve the customer by displaying total bill, shipping charges along with no. of products & items etc. and also provide an input field for shipping address, as shown in figure 3.
      98ca9dbf-455b-4a49-9dfb-ab453ca140fd-image.png
      To place order, customer must provide shipping address and click on Place Order button. Before displaying message "Order has been placed successfully.”, the program must save order details (i.e. no. of items, subtotal, shipping charges, grand total, shipping address and selected products with quantity) in corresponding database tables. Further, need to maintain quantity of products in database so that customer could not see out of stock products in next shopping.

      Button “Go Back” should take back on Shopping Cart Page. However, customer can sign out from system by pressing “Logout” button. In this case, web developer information (student id, name and email address) should be displayed via an HTML page (info.html), as shown in figure 4.
      9ef54e27-5ef2-44c0-bf01-5913ecb6f0ad-image.png
      Required Stuff:
      Html Pages:
      index.html
      info.html
      Java Servlets:
      LoginServlet.java
      ShoppingCartServlet.java
      CheckOutServlet.java
      Java Classes:
      Product.java
      Cart.java
      Order.java
      OrderDetail.java
      DatabaseHelper.java (must contain all database related code)
      Database file:
      BSxxxxxxxx.accdb (must be same as your own VU student id)

      Shipping Charges:

      Shipping Charges ($) = ((no. of Items / 5) + 1) * 0.5

      Sample Data & Database Tables:
      Tab. 1: Sample Products Data

      # Name Price Quantity 1 Flour $18.00 20 2 Oil $19.00 50 3 Ghee $10.00 0 4 Sauce $22.00 40 5 Sugar $21.35 35 6 Salt $25.00 26 7 Daal $30.00 38 8 Rice $40.00 92 9 Pasta $97.00 63 10 Fruits $35.00 72 11 Dry Fruits $31.00 70 12 Tea $21.00 12 13 Coffee $38.00 9 14 Milk $10.00 10 15 Snacks $23.25 13 16 Dessert $15.50 22 17 Vegetables $17.45 52 18 Chicken $39.00 98 19 Beef $62.50 0 20 Frozen Food $19.20 30 21 Sea Food $81.00 29 22 Sweet $10.00 29 23 Cake $21.00 0 24 Yogurt $26.00 0 25 Pickle $30.00 41

      Tab. 2: Products Table in MS Access Database
      e8814dde-b201-440f-a69e-2a3d27e55528-image.png

      Tab. 3: Orders Table in MS Access Database
      f9420f5c-00a8-493b-863f-d95c3237d986-image.png
      Tab. 4: Order Details Table in MS Access Database
      85596bdd-deaa-486f-83cb-201dd7cc5801-image.png
      Video Tutorials:
      To download and install of Tomcat Server, please watch;


       To create a web application project in NetBeans IDE, please watch;

       To add ucanaccess driver in a NetBeans project, please watch;

      Important Things to Implement:
       You have to provide separate pages, servlets, java files and database tables as guided above. Merging of two or more will result in deduction of marks.
       You need to put database file in assets folder under NetBeans project web directory along with html pages, as shown in figure 5.
       For storing/fetching data to/from database, you will need to use proper SQL queries.
       You can use same Product and Cart Java classes as provided in assignment # 1 & 2 and also can make changes as required.
       Java classes must have proper Data Members and Member Functions along with Constructors, Standard Setters and Getters etc.
       Need to make sure that exceptions are managed properly throughout the program; especially NullPointerException, ClassNotFoundException, NumberFormatException and SQLException etc.
       All images, tables and sample data, given in this document, are just for reference purpose only; you have to provide your own implementations. It is not required to be exactly the same.

      Good Luck

      CS506 - Web Design and Development
    • CS506 Quiz 1 Solution and Discussion

      zareen

      The keyword “this” is used to ________
      invoke constructor of the another class
      invoke alternate constructor of the same class
      invoke constructor of super class from sub class
      invoke constructor of sub class from super class

      Java defines _____ for the listener interfaces having more than one vent handling methods.
      Answer: Adapter Classes (right Answer)

      DSN stands for _________
      Answer: Data Source Name

      JDBC-ODBC stands for ________.
      Answer: JDBC stands for java database connectivity.

      == Operator compares _________ of strings whereas equals() method compares _________ of strings.
      Answer: Addresses, values

      Overloading is _______ whereas overriding is _____
      Answer: Compile time binding, run time binding

      Java defines ________ for the listener interfaces having more than one event handling methods.
      Answer: Event Listeners

      A database that is created in MS Access 2003 will be saved with _________ extension.
      Answer: .mdb

      Based on functionality, the streams can be categorized as ________
      Answer: Node stream and Filter stream

      AWT is a GUI Package used in java. AWT stands for_________
      Answer: Abstract Window Toolkit

      CS506 - Web Design and Development
    • CS506 Gdb1 Solution and discussion

      zaasmi

      GDB:

      IoT (Internet of Things) has opened up a world of possibilities in patient monitoring systems. The smart device like Pacemaker continuously monitors patient’s heart, generates electric pulses to prevent heart rate from going too slow and inform the physician about the health on real time basis. Hence smart devices can save lives in emergency cases as well.

      But what makes these devices “smart”, when they are having several barriers like limited memory, slow processing speed, connectivity issues and security concerns etc. Are they really smart enough?

      Being a Java developer what do you think, “Embedding Java programs in IoT devices, will make them smart or result in bad performance, for health care systems?”

      Instructions:

      Your comment must not be more than 4-5 lines and that must be concise, coherent and to the point comment.

      GDB will not get any grade

      If comment is lengthy and irrelevant.
      If found copied from other student or from internet material.
      If GDB solution is posted via mail within or after due date.
      For any queries, please email at [email protected]

      CS506 - Web Design and Development
    • CS506 Assignment No. 02
 Solution and Discussion

      zaasmi

      9cdcb8e3-e668-40c4-8fa1-8ee2b9b6eccd-image.png

      Assignment No. 02
Semester: Spring 2019
      CS506 – Web Design and Development

      Total Marks: 20

      Due Date: 31/05/2019

      Uploading instructions:

      • It must be complete NetBeans IDE project folder (which should contain complete source code, text files, and builds etc.). After finalizing, compress it with Zip or RAR format and submit it at VU-LMS within due date.
      • Your assignment should be in .zip /.rar format. Other file formats will not be accepted.
      • Save your assignment with your ID (e.g. bc000000000.zip).
      • No assignment will be accepted through email.

      Rules for Marking:

      It should be clear that your assignment will not get any credit if:

      • The assignment is submitted after due date.
      • The submitted assignment does not open, execute or file is corrupted.
      • It is not NetBeans IDE project (any other format will not be accepted in any case).
      • Your assignment is copied from internet, handouts or from any other student (strict disciplinary action will be taken in this case).
      • Do not put any query on MDB about this assignment, if you have any query then email at [email protected]

      Assignment

      Problem Statement:

      You are required to develop a Java program, named Hospital Management System for a typical medical treatment center; in which you will fetch doctors and patients detail from database and schedule appointments. Further, user can search an appointment for a particular patient as well; all data will be shown to user via GUI.

      Detailed Description:

      For this purpose, you have to create one MS Access Database file (the name of file must be same as your own VU ID i.e. BS00000000.accdb) and two Java classes (i.e. Appointment and MainClass). Database file should contain two tables (i.e. Doctors and Patients);

      Fig. 1: Doctors Table in Database

      Fig. 2: Patients Table in Database

      Appointment class should have the following data members and member functions;

      ¥ no: int
      ¥ patient: String
      ¥ doctor: String
      ¥ disease: String
      ¥ scheduledDay: String
      ¥ Constructors: default, parameterized and copy constructor
      ¥ Standard Setters: setNo(…), setPatient(…), setDoctor(…),
      setDisease(…), setScheduledDay (…)
      ¥ Standard Getters: getNo(), getPatient(), getDoctor(),
      getDisease(), getScheduledDay()
      MainClass must contain the main() method which should initialize all GUI components and display following two buttons;

      Appointments

      Search

      Appointments:

      The program will schedule the appointments by matching patient’s diseases with doctor’s specializations by using SQL selection query* and will display the result on GUI; needed to use Swing table component (i.e. javax.swing.JTable).

      *Sample SQL query:

      SELECT … FROM Patients, Doctors
      WHERE Patients.Disease = Doctors.Specialization

      Fig. 3: Appointments Detail on GUI

      Search:

      And, when user clicks on “Search” button then ask user to enter CNIC of a patient (using JOptionPane.showInputDialog). If input is correct (i.e. found no empty/null value) and corresponding patient is found in database then schedule an appointment by matching his/her disease with doctor’s specialization, otherwise a message should be displayed “Found no Patient”.

      *Sample SQL query:

      SELECT … FROM Patients, Doctors
      WHERE Patients.Disease = Doctors.Specialization
      AND Patients.Cnic = ‘proivdedCnic’

      Fig. 4: Search Result

      Note:
      The above given images are just for reference purpose only; you will be making your own GUIs. It is not required to be exactly the same.

      92d3585a-2e65-45ef-b3f5-f5db011e3629-image.png

      Table. 2: Sample Data for Patients Table in Database

      Important Regarding Development:

      If you are using JDK1.8 or above then you’ll have to use ucanaccess driver to connect to MS Access database. In this case, I’ll suggest you to view the following tutorial.

      https://vulms.vu.edu.pk/Courses/CS506/Downloads/UCanAccess.mp4

      Following links will be helpful in creating new database in MS Access.

      https://support.office.com/en-us/article/Create-a-new-database-32a1ea1c-a155-43d6-aa00-f08cd1a8f01e
      http://www.dummies.com/software/microsoft-office/access/how-to-build-a-new-database-in-access-2016/
      https://www.wikihow.com/Make-a-Database-Using-MS-Access

      Important Things to Implement:
      ¬ Java Classes must have proper Data Members and Member Functions along with Constructor/s, Setters and Getters etc.
      ¬ Data will be fetched from database in the form of Java class object/s.
      ¬ For GUI, relevant components (i.e. JFrame, JPanel, JScrollPane, JTable, JButton, and JLable etc.) from AWT and Swing packages should be used.
      ¬ For fetching data from database, you need to use proper SQL queries.
      ¬ Need to make sure that exceptions are managed properly throughout the program.

      GOOD LUCK

      Deadline: Your assignment must be uploaded/submitted on or before 3rd June 2019.

      CS506 - Web Design and Development

    SOLVED CS506 Assignment 2 Solution and Discussion

    CS506 - Web Design and Development
    assignment 2 cs506 discussion fall 2019 solution
    5
    21
    319
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • zareen
      zareen Cyberian's Gold last edited by

      Please join chat room for Solution Code with File.
      @Shaheen @Abu-Mohammad

      S 1 Reply Last reply Reply Quote 0
      • zareen
        zareen Cyberian's Gold @Shaheen last edited by

        @Shaheen This idea solution of Java code you need to create a MS Access DB. and changes required to connect the MSADB.

        1 Reply Last reply Reply Quote 0
        • S
          Shaheen Computer Sciences last edited by

          It seems not the solution of above assignment. It’s totally different. As mentioned above we have also a database file and when we run our project it fetch data from ms access database and show it but the code you paste not describe the solution of above assignment question. If you have the correct solution arrange all files in the zip and upload it. Thanks

          zareen 1 Reply Last reply Reply Quote 0
          • zareen
            zareen Cyberian's Gold last edited by zareen

            2nd Solution Idea
            Listing 29.1 Source Code for ShoppingCartItem.java

                // This class contains data for an individual item in a
                // shopping cart.
            
                import java.net.URL;
            
                public class ShoppingCartItem implements Cloneable
                {
                	public String itemName;
                	public int itemCost;
                	public int quantity;
                	public URL descriptionURL;
            
                	public ShoppingCartItem()
                	{
                	}
            
                	public ShoppingCartItem(String itemName, int itemCost,
                		int quantity, URL descriptionURL)
                	{
                		this.itemName = itemName;
                		this.itemCost = itemCost;
                		this.quantity = quantity;
                		this.descriptionURL = descriptionURL;
                	}
            
                // The add method is a quick method for combining two similar
                // items. It doesn't perform any checks to insure that they are
                // similar, however. You use this method when adding items to a
                // cart, rather than storing two instances of the same item, you
                // add the quantities together.
            
                	public void add(ShoppingCartItem otherItem)
                	{
                		this.quantity = this.quantity + otherItem.quantity;
                	}
            
                // The subtract method is similar to the add method, but it
                // removes a certain quantity of items.
            
                	public void subtract(ShoppingCartItem otherItem)
                	{
                		this.quantity = this.quantity - otherItem.quantity;
                	}
            
                // You can store items in a hash table if you implement hashCode. It's
                // always a good idea to do this.
            
                	public int hashCode()
                	{
                		return itemName.hashCode() + itemCost;
                	}
            
                // The equals method does something a little dirty here, it only
                // compares the item names and item costs. Technically, this is
                // not the way that equals was intended to work.
            
                	public boolean equals(Object other)
                	{
                		if (this == other) return true;
            
                		if (!(other instanceof ShoppingCartItem))
                			return false;
            
                		ShoppingCartItem otherItem =
                			(ShoppingCartItem) other;
            
                		return (itemName.equals(otherItem.itemName)) &&
                			(itemCost == otherItem.itemCost);
                	}
            
                // Create a copy of this object
            
                	public ShoppingCartItem copy()
                	{
                		return new ShoppingCartItem(itemName, itemCost,
                			quantity, descriptionURL);
                	}
            
                // Create a printable version of this object
            
                	public String toString()
                	{
                		return itemName+" cost: "+itemCost+" qty: "+quantity+" desc: "+
                			descriptionURL;
                	}
                }
            
            
            

            Note

            One interesting thing about the ShoppingCartItem class is that it cheats when it comes to object equality. It treats any two objects with the same name and cost as being equal. If they have different quantities, they are still considered equal. This is usually not a good idea, since it can lead to confusion, but in this particular instance, it works nicely. If you have an item with some quantity value, you can search through the cart for the same object (ignoring the quantities) and if you find a matching object, you can just add their quantities together.

            The next item on the agenda is the shopping cart itself. Since this is a very simple model of a cart, independent of the user interface, the cart should be observable. In other words, other objects should be able to watch the shopping cart to see when it changes. This allows you to write a user interface that updates itself whenever the cart is changed, yet you keep the user interface code out of the cart. The Observer/Observable mechanism is very handy for this sort of thing. The shopping cart is a subclass of the Observable class. Whenever the cart changes, it sends a notification to its observers. When you implement an observable object, you frequently need to notify the observers of different types of changes. For instance, in the shopping cart, you can add an item, remove an item, or change the quantity of an item. Since there is only one way to notify the observers that a change has taken place, you need to cram all that information into a single method call. You can accomplish this by creating an object that holds the information about the change. Listing 29.2 shows the ShoppingCartEvent class that holds the change information.

            Listing 29.2 Source Code for ShoppingCartEvent.java

            public class ShoppingCartEvent
            {
            // Define the kinds of changes that can take place
            	public static final int ADDED_ITEM = 1;
            	public static final int REMOVED_ITEM = 2;
            	public static final int CHANGED_ITEM = 3;
            
            // item is the item that is affected
            	public ShoppingCartItem item;
            
            // eventType is the kind of change that has taken
            // place (add/remove/change)
            	public int eventType;
            
            	public ShoppingCartEvent()
            	{
            	}
            
            	public ShoppingCartEvent(ShoppingCartItem item,
            		int eventType)
            	{
            		this.item = item;
            		this.eventType = eventType;
            	}
            }
            

            Now you can create the shopping cart itself. All you really need is a vector object for storing the cart items and a variable for the total cost so far. You must also be sure that you always notify your observers whenever the cart changes. Another object may be keeping a duplicate record of all the items in the cart. If you add or remove an item from the cart without sending a notification, the other object will no longer have an accurate representation of the shopping cart. Listing 29.3 shows the ShoppingCart object.

            Listing 29.3 Source Code for ShoppingCart.java

            import java.applet.*;
            import java.awt.*;
            import java.net.*;
            import java.util.*;
            
            // This class is a simple container of shopping cart items.
            // It is observable, which means that it notifies any interested
            // classes whenever it changes.
            
            public class ShoppingCart extends Observable
            {
            	protected Vector items;	// the items in the cart
            	protected int total;	// the total item cost so far
            
            	public ShoppingCart()
            	{
            		items = new Vector();
            		total = 0;
            	}
            
            // Add a new item and update the total
            
            	public void addItem(ShoppingCartItem newItem)
            	{
            
            // See if there's already an item like this in the cart
            		int currIndex = items.indexOf(newItem);
            
            		ShoppingCartEvent event = new ShoppingCartEvent();
            
            		if (currIndex == -1) {
            // If the item is new, add it to the cart
            			items.addElement(newItem);
            			event.item = newItem;
            			event.eventType = ShoppingCartEvent.ADDED_ITEM;
            		} else {
            
            // If there is a similar item, just add the quantities
            		ShoppingCartItem currItem =
            			(ShoppingCartItem) 
            			items.elementAt(currIndex);
            
            		currItem.add(newItem);
            		event.item = currItem;
            		event.eventType = ShoppingCartEvent.CHANGED_ITEM;
            	}
            
            	total += newItem.itemCost * newItem.quantity;
            
            // Tell the observers what just happened
            	setChanged();
            	notifyObservers(event);
            	}
            
            // Remove item removes an item from the cart. Since it removes
            // n items from the cart at a time, if there are more than n items
            // in the cart, it just subtracts n from the quantity.
            
            	public void removeItem(ShoppingCartItem oldItem)
            	{
            // Find this object in the cart
            	int currIndex = items.indexOf(oldItem);
            	ShoppingCartEvent event = new ShoppingCartEvent();
            
            	if (currIndex == -1) {
            // If it wasn't there, just return, assume everything's okay
            		return;
            	} else {
            		ShoppingCartItem currItem =
            				(ShoppingCartItem)
            				items.elementAt(currIndex);
            
            // If you are trying to subtract more items than are in the cart,
            // adjust the amount you want to subtract so it is equal to the
            // number of items in the cart.
            
            		if (oldItem.quantity > currItem.quantity) {
            			oldItem.quantity = currItem.quantity;
            		}
            
            // Adjust the total
            		total -= oldItem.itemCost * oldItem.quantity;
            
            		currItem.subtract(oldItem);
            
            		event.item = currItem;
            		event.eventType = ShoppingCartEvent.CHANGED_ITEM;
            
            // If the quantity drops to 0, remove the item entirely
            
            		if (currItem.quantity == 0) {
            			items.removeElementAt(currIndex);
            			event.eventType =
            				ShoppingCartEvent.REMOVED_ITEM;
            		}
            			
            		}
            
            // Tell everyone what happened
            
            	setChanged();
            	notifyObservers(event);
            	}
            
            // getItems returns a copy of all the items in the cart
            
            	public ShoppingCartItem[] getItems()
            	{
            	ShoppingCartItem[] itemArray = 
            		new ShoppingCartItem[items.size()];
            
            	items.copyInto(itemArray);
            
            	return itemArray;
            	}
            }
            

            Now that you have the basic framework for a shopping cart, you can work on a user interface for it.

            Creating a Shopping Cart User Interface

            The user interface for an electronic shopping cart is rarely a simple thing. Many shopping cart interfaces are incredibly complex, but also extremely easy to use. You can keep the interface pretty simple and still create a useful shopping cart, however.

            If you think about the structure of a shopping cart application, you’ll see that it really has two parts to it-the shopping cart and the catalog. When you are buying items, you look through the catalog of available items and select the ones you want. The catalog then sends these items to the shopping cart.

            At some point, you go over to the shopping cart and review what you have selected. You may decide to put some of the items back, in which case the shopping cart must remove them from its list and possibly return them to the catalog. There are a number of ways to design a system like this. One of the more interesting ways is to create two separate applets-a catalog applet and a shopping cart applet.

            Tip
            It is frequently useful to split the user interface into separate applets. Many times, you can reuse one of the applets in another project without going through the pain of separating out the other parts of the user interface.

            In order to implement this system with multiple applets, you need a way for the applets to locate each other. While applets can use the AppletContext class to find each other, your best bet is the AppletRegistry class, which was introduced in Chapter 10, “Inter-Applet Communication.” The AppletRegistry class is an observable class, which means that an applet can be notified whenever new applets are loaded. If you don’t use the registry, you must be prepared to occasionally poll for the other applets in case your applet starts up first.

            For a simple user interface, you may decide to present a scrollable list of items both in the catalog and in the shopping cart. Unfortunately, the AWT List class leaves much to be desired when it comes to scrollable lists. The biggest problem with the List class is that is only stores strings. Since the strings you store in the scrollable lists are the strings the user sees, you can’t really hide any information in them. For instance, if you look at the information stored in the ShoppingCartItem class, you realize that you don’t want the URL for the item’s description clogging up space in the list.

            Listing 29.4 shows an ObjectList class that allows you to associate an object with each entry in a scrollable list.

            Listing 29.4 Source Code for ObjectList.java

            import java.awt.*;
            import java.util.*;
            
            // This class is a special version of a scrollable list that
            // associates an object with each element in the list.
            
            public class ObjectList extends List
            {
            	Vector objects;	// the objects that correspond to list entries
            
            	public ObjectList()
            	{
            		objects = new Vector();
            	}
            
            	public ObjectList(int items, boolean multiSelect)
            	{
            		super(items, multiSelect);
            		objects = new Vector();
            	}
            
            	public synchronized void addObject(Object ob)
            	{
            // add a string version of the object to the list
            		super.addItem(ob.toString());
            
            // add the object itself to the object vector
            		objects.addElement(ob);
            	}
            
            	public synchronized void addObject(Object ob, int position)
            	{
            // add a string version of the object to the list
            		super.addItem(ob.toString(), position);
            
            // add the object itself to the object vector
            		if (position >= objects.size()) {
            			objects.addElement(ob);
            		} else {
            			objects.insertElementAt(ob.toString(),
            				position);
            		}
            	}
            
            	public synchronized void addObject(String label, Object ob)
            	{
            // Allow the object to be assigned a label independently of the object
            		super.addItem(label);
            		objects.addElement(ob);
            	}
            
            	public synchronized void addObject(String label, Object ob,
            		int position)
            	{
            // Allow the object to be assigned a label independently of the object
            		super.addItem(label, position);
            		if (position >= objects.size()) {
            			objects.addElement(ob);
            		} else {
            			objects.insertElementAt(ob.toString(),
            				position);
            		}
            	}
            
            	public synchronized void delObject(Object ob)
            	{
            // See if the object is in the vector
            		int index = objects.indexOf(ob);
            
            // If not, just return
            		if (index < 0) return;
            
            // Remove the object from the vector
            		objects.removeElementAt(index);
            
            // Remove the list entry
            		super.delItem(index);
            	}
            
            	public synchronized Object getSelectedObject()
            	{
            // Get the index of the current selection
            		int i = getSelectedIndex();
            
            		if (i == -1) return null;
            
            // Return the object currently selected
            		return objects.elementAt(i);
            	}
            
            	public synchronized Object[] getSelectedObjects()
            	{
            // Get the indices of all the selected objects
            		int[] selectedItems = getSelectedIndexes();
            
            // Create an array of all the selected objects
            		Object[] whichObjects = new Object[
            			selectedItems.length];
            
            		for (int i=0; i < selectedItems.length; i++) {
            			whichObjects[i] = objects.elementAt(i);
            		}
            
            		return whichObjects;
            	}
            
            	public int indexOf(Object ob)
            	{
            // Locate a particular object
            		return objects.indexOf(ob);
            	}
            
            	public Object objectAt(int index)
            	{
            // Return the object at a particular index
            		return objects.elementAt(index);
            	}
            
            	public void replaceObject(Object ob, int index)
            	{
            // Change a specific entry in the vector
            		replaceItem(ob.toString(), index);
            
            // Change a specific entry in the list
            		objects.setElementAt(ob, index);
            	}
            
            	public void replaceObject(String label, Object ob, int index)
            	{
            // Change a specific entry in the vector
            		replaceItem(label, index);
            
            // Change a specific entry in the list
            		objects.setElementAt(ob, index);
            	}
            }
            

            Note
            You should use the ObjectList class in place of the List class in many, if not all, situations. It is important to be able to associate objects with the entries in a list, and even more important to keep the content of the list strings down to the bare minimum needed by the user.

            Creating a Catalog Applet

            The catalog interface should allow a user to browse through the items that are for sale. You should at least provide some sort of description. If you are selling software or online services, it would be even better to offer a small sample. This would also be true for music or video recordings. While Java doesn’t have the ability to display many of these kinds of media yet, that capability is coming. For now, you can take advantage of the wonderful infrastructure of the Web and use simple URLs to describe the product. That way, you can include audio and video clips as you see fit.

            Since the catalog and the shopping cart are different applets, they need some way to communicate back and forth. The ShoppingCart class is the perfect mechanism for this. Whenever someone selects an item from the catalog, the catalog applet adds the item to the ShoppingCart class. The shopping cart applet is an observer of the ShoppingCart class and sees the new item immediately.

            Tip
            If you recall the Model-View-Controller paradigm, which was discussed in Chapter 9 “Creating Reusable Graphics Components,” the ShoppingCart class represents the model of the data. The catalog represents the controller, since it takes user input and translates it into changes in the model. The shopping cart applet is the view of the model, since it displays the items stored in the actual cart. The shopping cart applet also acts as a controller since it also takes input.

            When the catalog applet starts up, it looks for the shopping cart applet via the applet registry. When it finds the other applet, it calls getShoppingCart to locate the instanceof the ShoppingCart class that the two applets will share. Listing 29.5 shows the ItemPickerApplet class, which implements the user interface for the catalog portion of the shopping cart system.

            Listing 29.5 Source Code for ItemPickerApplet.java

            import java.awt.*;
            import java.applet.*;
            import java.net.*;
            import java.util.*;
            import java.io.*;
            
            // This class represents the catalog portion of a shopping cart.
            // You can select items and then either view a description of
            // the item or add the item to the shopping cart.
            
            public class ItemPickerApplet extends Applet implements Observer
            {
            	ObjectList items;
            	ShoppingCart cart;
            	AppletRegistry registry;
            
            	public void init()
            	{
            // Watch the applet registry to see when the Shopping Cart applet
            // becomes active
            		registry = AppletRegistry.instance();
            		registry.addObserver(this);
            
            		items = new ObjectList();
            
            // Get the URL of the list of items that are for sale
            		String itemURL = getParameter("itemList");
            		if (itemURL != null) fetchItems(itemURL);
            
            // Put the items in the center of the screen 
            		setLayout(new BorderLayout());
            		add("Center", items);
            
            		checkForShoppingCart();
            
            // Add this applet to the registry
            		registry.addApplet("Item Picker", this);
            	}
            
            	public void checkForShoppingCart()
            	{
            // See if the shopping cart has been loaded yet
            		Applet applet = registry.findApplet("Shopping Cart");
            		if (applet == null) return;
            
            		ShoppingCartApplet cartApplet = (ShoppingCartApplet)
            			applet;
            
            // Get the shopping cart used by the shopping cart applet
            		cart = cartApplet.getShoppingCart();
            
            // Create the panel for adding items
            		Panel southPanel = new Panel();
            
            // Set up some command buttons for adding and describing items
            		southPanel.add(new CommandButton("Describe Item",
            			new ItemPickerDescribe(this)));
            		southPanel.add(new CommandButton("Add Item",
            			new ItemPickerAdd(this)));
            
            		add("South", southPanel);
            	}
            
            	public void update(Observable obs, Object ob)
            	{
            		if (cart != null) return;
            
            		checkForShoppingCart();
            	}
            
            // When someone presses the "Add Item" button, the doAdd method
            // is called.
            	public void doAdd()
            	{
            // Find out what object was selected
            		Object ob = items.getSelectedObject();
            
            		if (ob == null) return;
            
            // Add the item to the cart
            		cart.addItem(((ShoppingCartItem)ob).copy());
            	}
            
            // When someone presses "Describe Item", the doDescribe method
            // is called.
            
            	public void doDescribe()
            	{
            
            // Find out which object was selected
            		Object ob = items.getSelectedObject();
            
            		if (ob == null) return;
            
            		ShoppingCartItem item = (ShoppingCartItem) ob;
            
            // If it has a description URL, open it up in another frame
            		if (item.descriptionURL != null) {
            			getAppletContext().showDocument(
            				item.descriptionURL, "descframe");
            		}
            	}
            
            // parseItem extracts an item name, cost, and URL from a string. The
            // items should be separated by |'s.
            	public void parseItem(String str)
            	{
            		StringTokenizer tokenizer = new StringTokenizer(str, "|");
            
            		if (tokenizer.countTokens() < 3) return;
            
            		String name = tokenizer.nextToken();
            
            		int cost = 0;
            		try {
            			cost = Integer.parseInt(tokenizer.nextToken());
            		} catch (Exception ignore) {
            		}
            
            		URL descURL = null;
            
            		try {
            			descURL = new URL(tokenizer.nextToken());
            		} catch (Exception ignore) {
            		}
            
            		items.addObject(name,
            			new ShoppingCartItem(name, cost, 1, descURL));
            
            	}
            
            // fetchItems gets a list of available items from the web server and
            // uses parseItem to parse the individual items. If a line begins with
            // the # character, it is ignored (# is typically a comment character).
            
            	public void fetchItems(String urlName)
            	{
            		try {
            			URL url = new URL(urlName);
            
            			DataInputStream inStream =
            				new DataInputStream(
            					url.openStream());
            
            			String line;
            
            			while ((line = inStream.readLine()) != null) {
            				if (line.charAt(0) == '#') continue;
            				parseItem(line);		
            			}
            		} catch (Exception e) {
            		}
            	}
            }
            

            Notice that the ItemPickerApplet uses the CommandButton class that was also introduced in Chapter 10, “Inter-Applet Communication.” The CommandButton class did not have to be changed at all in order to be used with this application. The only necessary items are a few command classes that provide the glue between the command buttons and the catalog applet. Listing 29.6 shows the ItemPickerDescribe command class. The other command classes are almost identical to the ItemPickerDescribe class.

            Listing 29.6 Source Code for ItemPickerDescribe.java

            public class ItemPickerDescribe extends Object implements Command
            {
            	ItemPickerApplet cart;
            
            	public ItemPickerDescribe(ItemPickerApplet cart)
            	{
            		this.cart = cart;
            	}
            
            	public void doCommand()
            	{
            		cart.doDescribe();
            	}
            }
            

            Creating the Shopping Cart Applet

            Now that most of the hard work has been done, the shopping cart interface itself is
            fairly easy. Basically, the shopping cart applet must be an observer of the shopping cart. Whenever the applet receives an update notification telling it that the shopping cart has changed, the applet simply changes its local list of items, which is a scrollable list (actually, it’s an ObjectList). The shopping cart applet is also responsible for sending the order to the Web server. For posting data to the Web server, you can adapt the PostSockURL or URLPost classes from Chapter 6, “Communicating with a Web Server.” Listing 29.7 shows the ShoppingCartApplet class.

            Listing 29.7 Source Code for ShoppingCartApplet.java

            import java.applet.*;
            import java.awt.*;
            import java.util.*;
            import java.net.*;
            import java.io.*;
            
            // This class provides a user interface for the ShoppingCart class
            
            public class ShoppingCartApplet extends Applet
            	implements Observer
            {
            	protected ShoppingCart cart;
            	protected ObjectList itemList;
            	protected TextField customerName;
            	protected TextField totalField;
            
            	public ShoppingCartApplet()
            	{
            // Make this class an observer of the shopping cart
            		cart = new ShoppingCart();
            		cart.addObserver(this);
            
            // Create the list of objects in the cart
            		itemList = new ObjectList();
            
            // Create the field for the total cost so far
            		totalField = new TextField(10);
            		totalField.setEditable(false);
            		totalField.setText("Total: "+cart.total);
            
            		setLayout(new BorderLayout());
            
            // Create a field for the customer name
            		customerName = new TextField(20);
            
            // Combine the label and the name field on a single panel
            		Panel namePanel = new Panel();
            		namePanel.add(new Label("Customer Name: "));
            		namePanel.add(customerName);
            
            // Put the name field up at the top and the item list in the center
            		add("North", namePanel);
            		add("Center", itemList);
            
            // Create buttons for removing items and placing an order and put
            // them along the bottom.
            
            		Panel southPanel = new Panel();
            		southPanel.add(new CommandButton(
            			"Remove Item",
            			new ShoppingCartRemove(this)));
            		southPanel.add(new CommandButton(
            			"Place Order",
            			new ShoppingCartOrder(this)));
            		southPanel.add(totalField);
            
            		add("South", southPanel);
            
            // Tell the applet registry about this applet
            		AppletRegistry.instance().addApplet("Shopping Cart", this);
            	}
            
            	public String makeItemString(ShoppingCartItem item)
            	{
            		return item.itemName+"   Qty: "+item.quantity+
            			"  Cost: "+item.itemCost;
            	}
            
            	public void update(Observable whichCart, Object ob)
            	{
            		ShoppingCartEvent event = (ShoppingCartEvent) ob;
            
            		if (event.eventType == ShoppingCartEvent.ADDED_ITEM) {
            // If there is a new item in the cart, add it to the scrollable list
            			itemList.addObject(makeItemString(event.item),
            				event.item);
            			totalField.setText("Total: "+cart.total);
            			itemList.validate();
            		} else if (event.eventType ==
            // If an item has been removed from the cart, remove it from the list
            			ShoppingCartEvent.REMOVED_ITEM) {
            			itemList.delObject(event.item);
            			totalField.setText("Total: "+cart.total);
            			itemList.validate();
            		} else if (event.eventType ==
            			ShoppingCartEvent.CHANGED_ITEM) {
            // If an item has changed, update the list
            			int index = itemList.indexOf(event.item);
            			itemList.replaceObject(makeItemString(
            				event.item), event.item, index);
            			totalField.setText("Total: "+cart.total);
            			itemList.validate();
            		}
            	}
            
            // If the user clicks on "Remove Item," remove it from he list
            	public void doRemove()
            	{
            		Object ob = itemList.getSelectedObject();
            		if (ob == null) return;
            
            		ShoppingCartItem item = ((ShoppingCartItem)ob).copy();
            		item.quantity = 1;
            		cart.removeItem(item);
            	}
            
            // doPlaceOrder uses PostSockURL to post the order to a web
            // server. You will need to customize this method to fit your needs.
            
            	public void doPlaceOrder()
            	{
            		try {
            			URL postURL = new URL(
            				getDocumentBase().getProtocol(),
            				getDocumentBase().getHost(),
            				getDocumentBase().getPort(),
            				"/shopping");
            
            			ByteArrayOutputStream byteOut = 
            				new ByteArrayOutputStream();
            			PrintStream outStream = 
            				new PrintStream(byteOut);
            
            			outStream.println("Custname: "+
            				customerName.getText());
            			ShoppingCartItem[] items = cart.getItems();
            			for (int i=0; i < items.length; i++) {
            				outStream.println(
            				items[i].itemName+"|"+
            				items[i].quantity);
            			}
            
            			String response = PostSockURL.post(postURL,
            				byteOut.toString());
            			System.out.println(response);
            		} catch (Exception e) {
            			e.printStackTrace();
            		}
            			
            	}
            
            	public ShoppingCart getShoppingCart()
            	{
            		return cart;
            	}
            }
            

            link text

            1 Reply Last reply Reply Quote 0
            • zareen
              zareen Cyberian's Gold last edited by zareen

              We explained everything well enough. I apologize for any confusion.

              import java.util.Scanner;
                
              public class ShoppingCartManager
              {
                
                  private static Scanner input;
               
                  public static void main(String[] args)
                  {
                      ShoppingCart cart = new ShoppingCart();
                      input = new Scanner(System.in);
                
                      System.out.println("Enter Customer's Name:");
                      cart.setCustomerName(input.nextLine());
                      System.out.println("Enter Today's Date:");
                      cart.setDate(input.nextLine());
                      System.out.println("");
                      System.out.println("Customer Name: " + cart.getCustomerName());
                      System.out.println("Today's Date: " + cart.getDate());
                
                      char choice = 'q';
                      do
                      {
                          ShoppingCart.printMenu(cart);
                
                          switch (choice)
                          {
                              case 'a':
                                  ItemToPurchase item = new ItemToPurchase(); // or however you create it
                                  cart.addItem(item);
                                  break;
                              case 'd': //FIX!!
                                  System.out.println("Enter item name:");
                                  cart.removeItem(input.nextLine());
                                  break;
                              case 'c':  //FIX!!!
                                  cart.getNumItemsInCart();
                                  break;
                              case 'i':
                                  cart.printDescription();
                                  break;
                              case 'o':
                                  cart.printTotal();
                                  break;
                          }
                          choice = input.nextLine().toLowerCase().charAt(0);
                      } while (choice != 'q');
                  }
              }
              
              public class ItemToPurchase
              {
                  private String itemName;
                  private String itemDescription;
                  private int itemPrice;
                  private int itemQuantity;
                
                  public ItemToPurchase()
                  {
                      this.itemName = "none";
                      this.itemDescription = "none";
                      this.itemPrice = 0;
                      this.itemQuantity = 0;
                  }
                
                  public ItemToPurchase(String itemName, String itemDescription, int itemPrice, int itemQuantity)
                  {
                      this.itemName = itemName;
                      this.itemDescription = itemDescription;
                      this.itemPrice = itemPrice;
                      this.itemQuantity = itemQuantity;
                  }
                    
                  public String getName()
                  {
                      return itemName;
                  }
                
                  public void setName(String itemName)
                  {
                      this.itemName = itemName;
                  }
                
                  public int getPrice()
                  {
                      return itemPrice;
                  }
                
                  public void setPrice(int itemPrice)
                  {
                      this.itemPrice = itemPrice;
                  }
                
                  public int getQuantity()
                  {
                      return itemQuantity;
                  }
                
                  public void setQuantity(int itemQuantity)
                  {
                      this.itemQuantity = itemQuantity;
                  }
                
                  public String getDescription()
                  {
                      return itemDescription;
                  }
                
                  public void setDescription(String itemDescription)
                  {
                      this.itemDescription = itemDescription;
                  }
                    
                  public void printItemCost()
                  {
                      int quantityCost = (getPrice() * getQuantity());
                        
                      System.out.println(getName() + " " + getQuantity() + " @ $" + getPrice() + " = $" + quantityCost);
                  }
                    
                  public void printItemDescription()
                  {
                      System.out.println(getName() + ": " + getDescription());
                  }
              }
              
              import java.util.ArrayList;
              import java.util.Scanner;
                
              public class ShoppingCart
              {
                
                  private String customerName;
                  private String currentDate;
                  private ArrayList<ItemToPurchase> cartItems = new ArrayList<>();
                
                  public ShoppingCart()
                  {
                      this.customerName = "none";
                      this.currentDate = "January 1, 2016";
                  }
                
                  public ShoppingCart(String customerName, String currentDate)
                  {
                      this.customerName = customerName;
                      this.currentDate = currentDate;
                  }
                
                  public void setCustomerName(String customerName)
                  {
                      this.customerName = customerName;
                  }
                
                  public String getCustomerName()
                  {
                      return customerName;
                  }
                
                  public void setDate(String currentDate)
                  {
                      this.currentDate = currentDate;
                  }
                
                  public String getDate()
                  {
                      return currentDate;
                  }
                
                  public void addItem(ItemToPurchase item) //HAVING TROUBLE PASSING OBJECT THROUGH A PARAMETER
                  {
                      cartItems.add(item);
                  }
                
                  public void removeItem(String itemName)
                  {
                
                      for (int i = 0; i < cartItems.size(); ++i)
                      {
                          ItemToPurchase item = cartItems.get(i);
                          if (itemName.equals(item.getName()))
                          {
                              cartItems.remove(i);
                          } else
                          {
                              System.out.println("Item not found in cart. Nothing modified.");
                          }
                      }
                
                  }
                
                  public void modifyItem(ItemToPurchase item, String itemName) //FIX!! default values for if statement
                  {
                      for (int i = 0; i < cartItems.size(); ++i)
                      {
                          item = cartItems.get(i);
                          if (itemName.equals(item.getName()))
                          {
                              cartItems.get(i).setName("");
                              cartItems.get(i).setDescription("");
                              cartItems.get(i).setPrice(20);
                              cartItems.get(i).setQuantity(5);
                          } else
                          {
                              System.out.println("Item not found in cart. Nothing modified.");
                          }
                      }
                  }
                
                  public int getNumItemsInCart()
                  {
                      int quantity = 0;
                      for (int i = 0; i < cartItems.size(); ++i)
                      {
                          quantity += cartItems.get(i).getQuantity();
                      }
                      return quantity;
                  }
                
                  public int getCostOfCart()
                  {
                      int costOfCart = 0;
                      for (int i = 0; i < cartItems.size(); ++i)
                      {
                          costOfCart += cartItems.get(i).getPrice();
                      }
                      return costOfCart;
                  }
                
                  public void printTotal() //FIX!!! Not sure if this is what is expected of method
                  {
                      for(int i = 0; i < cartItems.size(); i++)
                      {
                          cartItems.get(i).printItemCost();
                      }
                      System.out.println("Total: $" + getCostOfCart());
                  }
                
                  public void printDescription()
                  {
                      for (int i = 0; i < cartItems.size(); ++i)
                      {
                          cartItems.get(i).printItemDescription();
                      }
                  }
                
                  public static void printMenu(ShoppingCart cart) //FIX!! Having trouble with passing an object as a parameter
                  {
                      System.out.println("MENU\na - Add item to cart");
                      System.out.println("d - Remove item from cart");
                      System.out.println("c - Change item quantity");
                      System.out.println("i - Output items' descriptions");
                      System.out.println("o - Output shopping cart");
                      System.out.println("q - Quit");
                      System.out.println("\nChoose an option: ");
                
                  }
              }
              
              

              link text

              1 Reply Last reply Reply Quote 1
              • Abu Mohammad
                Abu Mohammad last edited by

                koi to iska solution post kr do plz plz

                1 Reply Last reply Reply Quote 0
                • S
                  Shaheen Computer Sciences last edited by

                  Kindly post the solution of cs506 assignment no 2 fall 2019. Thanks @mehwish
                  Anyone there ???

                  1 Reply Last reply Reply Quote 0
                  • S
                    Shaheen Computer Sciences @zareen last edited by

                    Kindly post the solution of cs506 assignment no 2 fall 2019. Thanks @zareen

                    1 Reply Last reply Reply Quote 0
                    • zareen
                      zareen Cyberian's Gold @Shaheen last edited by

                      @Shaheen Yes!

                      S 1 Reply Last reply Reply Quote 0
                      • S
                        Shaheen Computer Sciences last edited by

                        Kindly provide the idea solution of CS506 Assignment 2 Fall 2019. Tomorrow is the last day. Anbody there???

                        zareen 1 Reply Last reply Reply Quote 0
                        • First post
                          Last post

                        50% Off on Your FEE Join US!

                        Quiz 100% Result If you want to know how you can join us and get 50% Discout on your FEE ask Cyberian in Chat Room! Quiz 100% Result Quiz 100% Result
                        solution1241 discussion1194 fall 2019813 assignment 1425 assignment 2295 spring 2020265 gdb 1246 assignment 382 crw10174 spring 201955
                        | |
                        Copyright © 2021 Cyberian Inc. Pakistan | Contributors
                        Live Chat