示例#1
0
  public static void main(String[] args) throws Exception {
    System.out.println("hello from Customer.java");

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("customerPU");
    EntityManager manager = factory.createEntityManager();
    Query q1 = manager.createQuery("SELECT COUNT(c) FROM Customer c");
    Long count = (Long) q1.getSingleResult();
    if (count == 0) {
      // record is empty, read from data.txst
      System.out.println("record empty, read from data.txt...");
      // try {
      FileReader fr = new FileReader("data.txt");
      BufferedReader br = new BufferedReader(fr);
      String s;
      while ((s = br.readLine()) != null) {

        // System.out.println(s);
        // split the string s
        Object[] items = s.split("\\|");
        // store in string list
        // List<String> itemList= new ArrayList<String>(Arrays.asList(items));
        // string list converted to array

        // Object[] itemArray = itemList.toArray();
        // insert data into database table
        manager.getTransaction().begin();
        Customer c = new Customer();

        // add email
        c.setEmail((String) items[0]);

        // add pass
        c.setPass((String) items[1]);

        // add name
        c.setName((String) items[2]);

        // add address
        c.setAddress((String) items[3]);

        // add yob
        c.setYob((String) items[4]);

        // change to managed state
        manager.persist(c);
        manager.getTransaction().commit();
      }
      fr.close();
    }

    // display the records
    Query q2 = manager.createNamedQuery("Customer.findAll");
    List<Customer> customers = q2.getResultList();
    for (Customer c : customers) {
      System.out.println(c.getName() + ", " + c.getEmail());
    }

    manager.close();
    factory.close();
  }
  /**
   * Rate a restaurant and give a feedback Rate uses SQL INSERT INTO
   *
   * @param stars number of stars
   * @param feedback user's feedback
   * @param customer a customer
   * @return true if rate works fine, false otherwise
   * @throws SQLException
   */
  public boolean rate(int stars, String feedback, Customer customer) throws SQLException {
    boolean success = false;
    PreparedStatement insertStatement = null;
    int customerID = getCID(customer.getEmail());
    String query =
        "INSERT INTO Rating (cid, stars, feedback) VALUES (?,?,?) "
            + "ON DUPLICATE KEY UPDATE stars=?, feedback=?";

    try {
      connection.setAutoCommit(false);
      insertStatement = (PreparedStatement) connection.prepareStatement(query);
      insertStatement.setInt(1, customerID);
      insertStatement.setInt(2, stars);
      insertStatement.setString(3, feedback);
      insertStatement.setInt(4, stars);
      insertStatement.setString(5, feedback);
      insertStatement.execute();

      connection.commit();
      success = true;

    } catch (SQLException e) {
      e.printStackTrace();
      success = false;
    } finally {
      if (insertStatement != null) {
        insertStatement.close();
      }

      connection.setAutoCommit(true);
      return success;
    }
  }
  /**
   * Reserve a table
   *
   * @param partySize number of people in a party
   * @param d reservation date
   * @param tID table id
   * @param c a customer
   * @return true if succeed, false otherwise
   */
  public boolean reserveTable(int partySize, Date d, int tID, Customer c) {
    PreparedStatement statement = null;
    int customerid = getCID(c.getEmail());
    String sql_reserve =
        "INSERT INTO Restaurant.Reservation (reservationDate,partySize,cID,tID) values(?, ?, ?,?)";

    try {
      connection.setAutoCommit(false);
      statement = (PreparedStatement) connection.prepareStatement(sql_reserve);
      statement.setDate(1, d);
      statement.setInt(2, partySize);
      statement.setInt(3, customerid);
      statement.setInt(4, tID);
      statement.executeUpdate();
      connection.commit();

      if (statement != null) {
        statement.close();
      }

      connection.setAutoCommit(true);

      return true;

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.out.println("Failed: " + e.getMessage());
      return false;
    }
  }
 public void setCustomerID(int customerID) {
   CustomerID = customerID;
   lblAddCustomer.setText("Edit Customer");
   Customer customer = CustomerBL.GetCustomer(GetPU(), customerID);
   if (customer != null) {
     txtFirstName.setText(customer.getFirstName());
     txtLastName.setText(customer.getLastName());
     txtUsername.setText(customer.getUsername());
     txtUsername.setEditable(false);
     txtPassword.setText("");
     txtEmail.setText(customer.getEmail());
     txtPhone.setText(customer.getPhone());
     txtStreet1.setText(customer.getAddr_Street1());
     txtStreet2.setText(customer.getAddr_Street2());
     txtCity.setText(customer.getAddr_City());
     txtState.setText(customer.getAddr_State());
     txtZipcode.setText(customer.getAddr_Zipcode());
     txtCountry.setText(customer.getAddr_Country());
     chkActive.setSelected(customer.isIsActive());
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_edit_customer);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    String[] data = {"owner", "rent"};
    String status;
    spinner = (Spinner) findViewById(R.id.spinner);
    toDayDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner = (Spinner) findViewById(R.id.spinner);
    spinner.setAdapter(adapter);
    spinner.setPrompt("Title");
    spinner.setSelection(0);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0) {
              mPosition = 0;
            }
            if (position == 1) {
              mPosition = 1;
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> arg0) {}
        });

    mApartmentNumberEditText = (EditText) findViewById(R.id.ApartmentNumberEditText);
    mFirstNameEditText = (EditText) findViewById(R.id.FirstNameEditText);
    mLastNameEditText = (EditText) findViewById(R.id.LastNameEditText);
    mEmailEditText = (EditText) findViewById(R.id.EmailEditText);
    mPhoneHomeEditText = (EditText) findViewById(R.id.PhoneHomeEditText);
    mPhoneMobileEditText = (EditText) findViewById(R.id.PhoneMobileEditText);
    mMonthlyPaymentNumberEditText = (EditText) findViewById(R.id.MonthlyPaymentNumberEditText);
    mPreviousBalanceEditText = (EditText) findViewById(R.id.PreviousBalanceEditText);
    mDateEditText = (EditText) findViewById(R.id.DateEditText);

    Intent intent = getIntent();
    mDbOpenHelperCustomer = new DbOpenHelperCustomer(this);

    int customerId = intent.getIntExtra("ID", -1);
    if (customerId > -1) {
      mCustomer = mDbOpenHelperCustomer.getCustomerById(customerId);
      if (mCustomer != null) {
        Log.d("MyLog", "som");
        edit = true;
        mApartmentNumberEditText.setText(mCustomer.getApartmentNumber());
        mFirstNameEditText.setText(mCustomer.getFirstName());
        mLastNameEditText.setText(mCustomer.getLastName());
        mEmailEditText.setText(mCustomer.getEmail());
        mPhoneHomeEditText.setText(mCustomer.getPhoneHome());
        mPhoneMobileEditText.setText(mCustomer.getPhoneMobil());
        mMonthlyPaymentNumberEditText.setText(mCustomer.getMonthlyPayment());
        mPreviousBalanceEditText.setText(mCustomer.getPreviousBalance());
        spinner.setSelection(mCustomer.getCustomerStatus());
        mPosition = mCustomer.getCustomerStatus();
        mDateEditText.setText(mCustomer.getDate());
      }
    }

    Button actionButton = (Button) findViewById(R.id.actionButton);
    if (edit) {
      actionButton.setText("Update");
      apartment = mCustomer.getApartmentNumber();
    } else {
      actionButton.setText("Create");
      mDateEditText.setText(toDayDate);
    }
    actionButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {

            if (!edit) {
              if (!mDbOpenHelperCustomer.idExist(mApartmentNumberEditText.getText().toString())) {
                Toast.makeText(getApplication(), "Already taken ", Toast.LENGTH_SHORT).show();
                return;
              }
            }

            if (edit) {
              if (!apartment.equals(mApartmentNumberEditText.getText().toString())) {
                List<Customer> customers = mDbOpenHelperCustomer.getCustomers();
                for (Customer customer : customers) {
                  if (customer
                      .getApartmentNumber()
                      .equals(mApartmentNumberEditText.getText().toString())) {

                    Toast.makeText(getApplication(), "Already taken ", Toast.LENGTH_SHORT).show();
                    return;
                  }
                }
              }
            }

            if (TextUtils.isEmpty(mApartmentNumberEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mFirstNameEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mLastNameEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mEmailEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mPhoneHomeEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mPhoneMobileEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mMonthlyPaymentNumberEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            if (TextUtils.isEmpty(mPreviousBalanceEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            //                if (TextUtils.isEmpty(mCustomerStatusEditText.getText().toString())) {
            //                    Toast.makeText(getApplication(), "All fields must be complete ",
            // Toast.LENGTH_SHORT).show();
            //                    return;
            //                }
            if (TextUtils.isEmpty(mDateEditText.getText().toString())) {
              Toast.makeText(getApplication(), "All fields must be complete ", Toast.LENGTH_SHORT)
                  .show();
              return;
            }

            if (!edit) {
              Log.d("MyLog", "new");
              mCustomer =
                  new Customer(
                      mApartmentNumberEditText.getText().toString(),
                      mFirstNameEditText.getText().toString(),
                      mLastNameEditText.getText().toString(),
                      mEmailEditText.getText().toString(),
                      mPhoneHomeEditText.getText().toString(),
                      mPhoneMobileEditText.getText().toString(),
                      mMonthlyPaymentNumberEditText.getText().toString(),
                      mPreviousBalanceEditText.getText().toString(),
                      mPosition,
                      mDateEditText.getText().toString());
              mDbOpenHelperCustomer.saveCustomer(mCustomer);
            } else {
              Log.d("MyLog", "Back");
              mCustomer.setApartmentNumber(mApartmentNumberEditText.getText().toString());
              mCustomer.setFirstName(mFirstNameEditText.getText().toString());
              mCustomer.setLastName(mLastNameEditText.getText().toString());
              mCustomer.setEmail(mEmailEditText.getText().toString());
              mCustomer.setPhoneHome(mPhoneHomeEditText.getText().toString());
              mCustomer.setPhoneMobil(mPhoneMobileEditText.getText().toString());
              mCustomer.setMonthlyPayment(mMonthlyPaymentNumberEditText.getText().toString());
              mCustomer.setPreviousBalance(mPreviousBalanceEditText.getText().toString());
              mCustomer.setCustomerStatus(mPosition);
              mCustomer.setDate(mDateEditText.getText().toString());
              mDbOpenHelperCustomer.updateCustomer(mCustomer);
            }
            finish();
          }
        });
  }
示例#6
0
文件: Main.java 项目: atolat/PIKFLIX
  private static void mainMenu() {
    System.out.println("\n\nWhat do you want to do?");
    System.out.println("1. Search movies by actor");
    System.out.println("2. Add a star");
    System.out.println("3. Add a customer");
    System.out.println("4. Delete a customer");
    System.out.println("5. Provide metadata");
    System.out.println("6. Run custom SQL query");
    System.out.println("7. Logout");
    System.out.println("\nPlease make a choice");
    choice = inp.nextInt();
    switch (choice) {
      case 1:
        System.out.println(" Please enter a name: ");
        String a = inp.nextLine();
        searchmovies(a);
        break;

      case 2: // Insert a new star to database
        BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding Star...");
        System.out.println(" Please enter the id: ");
        int id1;
        try {
          id1 = inp.nextInt();
        } catch (InputMismatchException e1) {
          System.out.println("You did not enter a number!!");
          System.out.println("Try again");
          id1 = inp.nextInt();
        }

        String[] prompts1 = {
          "Please enter a first name: ",
          "Please enter a last name: ",
          "Please enter a dob: ",
          "Please enter an photo url: ",
        };
        ArrayList<String> ar1 = new ArrayList<String>();
        for (String prompt : prompts1) {
          System.out.println(prompt);
          try {
            ar1.add(br1.readLine());
          } catch (IOException e) {
            System.out.println(e);
          }
        }

        Star star = new Star(id1, ar1.get(0), ar1.get(1), ar1.get(2), ar1.get(3));
        try {
          addstar(
              star.getId(),
              star.getFirst_name(),
              star.getLast_name(),
              star.getDob(),
              star.getPhotoURL());
        } catch (SQLException e) {
          System.out.println("Could not add star");
        }
        break;

      case 3:
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding Customer...");
        System.out.println(" Please enter the id: ");
        int id;
        try {
          id = inp.nextInt();
        } catch (InputMismatchException e1) {
          System.out.println("You did not enter a number!!");
          System.out.println("Try again");
          id = inp.nextInt();
        }
        String[] prompts = {
          "Please enter a first name: ",
          "Please enter a last name: ",
          "Please enter a credit card number: ",
          "Please enter an address: ",
          "Please enter an email id: ",
          "Please enter the customer's password: "******"Could not add customer");
        }
        break;

      case 4:
        break;

      case 5:
        break;

      case 6:
        break;

      case 7:
        break;

      default:
        System.out.println("INVALID OPTION...");
        break;
    }
  }