示例#1
0
  public CashierInterface(Database database) {

    this.db = database;
    movies = db.getMovies();
    times = db.getShowTimes(movies[0]);

    movieList = new DropdownView(movies);
    timesList = new DropdownView(times);

    movieList.addActionListener(updateTimes);
    feedback.setEditable(false);
    feedback.setLineWrap(true);
    feedback.setWrapStyleWord(true);

    Display movies = new Display(movieList, "Select Movie:", null);
    Display times = new Display(timesList, "Select Showing:", null);
    Display tix =
        new Display(
            tickets,
            "How many of each ticket " + "type would you like?(" + getTicketAnnotation() + ")",
            null);
    Display feedbk = new Display(feedback, "Info", null);

    add(movies);
    add(times);
    add(tix);
    add(new Display(new TextAreaView()));
    add(feedbk);
    add(ap);
  }
 private void DEBUGGING() {
   Database db = new Database(this);
   ArrayList<Entry> temp = Entry.sortEntries(db.getAllFromID("1"));
   String res = "";
   for (int i = 0; i < temp.size(); i++) {
     res +=
         temp.get(i).getDate() + ", " + temp.get(i).getVal() + ", " + temp.get(i).getType() + "\n";
   }
   addTextElement(res);
 }
示例#3
0
  public void action() {
    Customer cust = new Customer();

    cust.setBroker(broker.getText());
    cust.setCadd(cadd.getText());
    cust.setCname(cname.getText());
    cust.setCreq(creq.getText());
    cust.setFeatures(features.getText());
    cust.setPtype((String) ptype.getSelectedItem());
    if (!cust.getCname().equals("") && !cust.getCreq().equals("")) {
      String sql_query =
          "INSERT INTO Customer(Customer_Name,Customer_Address,Customer_Requirements,Special_Features,Broker_Name,Property_Type) Values('"
              + cust.getCname()
              + "','"
              + cust.getCadd()
              + "','"
              + cust.getCreq()
              + "','"
              + cust.getFeatures()
              + "','"
              + cust.getBroker()
              + "','"
              + cust.getPtype()
              + "')";
      System.out.println(sql_query);

      Database db = new Database();
      int i = db.insert(sql_query);
      if (i != 0) {
        broker.setText("");
        cadd.setText("");
        cname.setText("");
        creq.setText("");
        features.setText("");
        ptype.setSelectedIndex(0);

        JOptionPane.showMessageDialog(
            this,
            "Operation successfully completed",
            "Successfull",
            JOptionPane.INFORMATION_MESSAGE);
      } else
        JOptionPane.showMessageDialog(
            this,
            "Due to some connection error data could not be entered properly\nPlease contact your service provider",
            " Error ",
            JOptionPane.ERROR_MESSAGE);

    } else
      JOptionPane.showMessageDialog(
          this,
          "Please Enter Customer Name and Customer Requirement ",
          " Error ",
          JOptionPane.ERROR_MESSAGE);
  }
 public File saveInternal() {
   ContextWrapper cw = new ContextWrapper(this);
   File mediaStorageDir = cw.getDir("", Context.MODE_PRIVATE);
   File mediaFile;
   String mImageName = Tools.getFileNamePhoto();
   Database db = new Database(this);
   db.updatePicture(mImageName, String.valueOf(MainActivity.CURRENT_ID));
   mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
   Notes_Activity.takenPhoto = true;
   return mediaFile;
 }
示例#5
0
  /** @param args the command line arguments */
  public static void main(String[] args) {

    ArrayList<Moneda> mon = new ArrayList();

    Database basedato = new Database();
    basedato.connectDB();
    mon = basedato.selectTable();

    System.out.println(mon.get(0).getId() + mon.get(0).getName() + mon.get(0).getValue());
    System.out.println(mon.get(1).getId() + mon.get(1).getName() + mon.get(1).getValue());
  }
示例#6
0
  public int doStartTag() throws JspException {
    HttpSession session = pageContext.getSession();
    if (session.getAttribute("Database") != null) {
      dbConn = (Database) session.getAttribute("Database");
      if (session.getAttribute("User") != null) {
        selinasuser = (SelinasUser) session.getAttribute("User");

        if (session.getAttribute("ImmobilienOrderByTyp") != null)
          orderByTyp = (String) session.getAttribute("ImmobilienOrderByTyp");

        try {
          JspWriter out = pageContext.getOut();

          try {
            dbConn.getConnection();
            out.println(
                "<table cellspacing='0' cellpadding='0' width='100%' class="
                    + FB
                    + tableTagClass
                    + FB
                    + ">"
                    + writeDokumentHeaderToPageContext(columnHeader)
                    + writeDokumentDataToPageContext(
                        DataSetImmobilie.reade(dbConn, selinasuser.user, orderByTyp)));
            dbConn.close();
          } catch (Exception e) { // no DokumentLinks found
            out.println(
                "<table class="
                    + FB
                    + tableTagClass
                    + FB
                    + ">"
                    + writeDokumentHeaderToPageContext(columnHeader));
          } // catch
          return EVAL_BODY_INCLUDE; // Evaluate body into existing out stream, and start next with
                                    // doEndTag()

        } catch (Exception e) {
          throw new JspException(
              "Create of TableContent " + " Exception " + e.getMessage() + " is not vaild");
        } // try

      } else {
        throw new JspException(
            "User object in session " + session.getAttribute("User") + " has not the valid type");
      } // session.getAttribute("User")
    } else {
      throw new JspException(
          "Database object in session "
              + session.getAttribute("Database")
              + " has not the valid type");
    } // session.getAttribute("Database")
  } // doStartTag
示例#7
0
  public void sellTickets() {
    StringTokenizer st = new StringTokenizer(tickets.getViewState(), ",");
    ArrayList<Map.Entry<String, Integer>> disCodes = db.getDiscountsAndPrices();
    int discountCodeCount = disCodes.size();
    if (st.countTokens() == discountCodeCount) {
      ArrayList<Map.Entry<String, Integer>> order = new ArrayList<Map.Entry<String, Integer>>();
      int orderSize = 0;
      int price = 0;
      for (Map.Entry<String, Integer> codeAndPrice : disCodes) {
        int ticCount = Integer.parseInt(st.nextToken());
        orderSize = orderSize + ticCount;
        order.add(new AbstractMap.SimpleEntry<String, Integer>(codeAndPrice.getKey(), ticCount));
        price = price + (codeAndPrice.getValue() * ticCount);
      }
      try {
        Movie m = db.getMovie(movieList.getViewState(), timesList.getViewState());
        int attendance = m.getAttendance();
        int capacity = m.getTheater().getCapacity();
        if (capacity >= attendance + orderSize) {

          feedback.setViewState(
              "Please tender $"
                  + price
                  + " to the cashier and proceed to theater "
                  + m.getTheater().getID());
          for (Map.Entry<String, Integer> suborder : order) {
            m.addOrder(suborder.getKey(), suborder.getValue());
          }
        } else {
          feedback.setViewState(
              "I'm sorry, but the showing of "
                  + m.toString()
                  + " is sold out. Please select another film.");
        }
      } catch (Exception e) {
        System.out.println(e);
      }

    } else {
      String err =
          "Malformed ticket order: Input must be comma "
              + "separated, without spaces,"
              + " with the value in each postion reflecting "
              + "the number of each type of ticket you would like."
              + "e.g. If the discount codes are Adult,Child,Senior "
              + "2,1,0 would represent an order of two adults and"
              + " one child";
      System.out.println(err);
      feedback.setViewState(err);
    }
  }
 //// TODO: 11/01/16 think of a better way to incorporate values.. add values .. updt the submit
 // button to show dynamically , maybe create a view for it.
 public void insertNote() {
   TextView tv = new TextView(this);
   String edittext = "";
   edittext = note_et.getText().toString();
   edittext = "temp";
   Database db = new Database(this);
   db.updateNote(edittext, "1");
   Toast.makeText(
           this,
           "Description Size(): " + db.sizeNote(String.valueOf(MainActivity.CURRENT_ID)),
           Toast.LENGTH_SHORT)
       .show();
   addTextElement(edittext);
 }
 public void insertFlag() {
   TextView tv = new TextView(this);
   Database db = new Database(this);
   db.updateFlag(Tools.FLAG, "1");
   Toast.makeText(
           this,
           "Description Size(): " + db.sizeFlag(String.valueOf(MainActivity.CURRENT_ID)),
           Toast.LENGTH_SHORT)
       .show();
   // todo reset this with add flagelement.. which will be esentially the same as the addaudio
   // begin element..
   addFlagElement();
   scrollDown();
 }
示例#10
0
 public void getTimes() {
   times = db.getShowTimes(movieList.getViewState());
   timesList.removeAllItems();
   for (String s : times) {
     timesList.addItem(s);
   }
 }
示例#11
0
 public String getTicketAnnotation() {
   ArrayList<String> codes = db.getDiscountCodes();
   String tickets = "";
   for (String s : codes) {
     tickets = tickets + s + ",";
   }
   return tickets.substring(0, tickets.length() - 1);
 }
示例#12
0
 /**
  * Erstellt einen neuen Filter für die Anzahl der Betten. Bereits vorhandene Filter dieses Typs
  * bleiben erhalten und werden mit einem OR kombiniert.
  *
  * @param anzahlBetten Die gewünschte Anzahl der Betten.
  */
 public void addFilterAnzahlBetten(Integer anzahlBetten) {
   String[] newFilter = new String[filterAnzahlBetten.length + 1];
   for (int i = 0; i < filterAnzahlBetten.length; i++) {
     newFilter[i] = filterAnzahlBetten[i];
   }
   newFilter[newFilter.length - 1] = "AnzahlBetten = " + Database.getSqlString(anzahlBetten);
   filterAnzahlBetten = newFilter;
 }
示例#13
0
 /**
  * Erstellt einen neuen Filter für den Preis pro Nacht. Bereits vorhandene Filter dieses Typs
  * bleiben erhalten und werden mit einem OR kombiniert.
  *
  * @param preisProNacht Der gewünschte Preis pro Nacht.
  */
 public void addFilterPreisProNacht(Float preisProNacht) {
   String[] newFilter = new String[filterPreisProNacht.length + 1];
   for (int i = 0; i < filterPreisProNacht.length; i++) {
     newFilter[i] = filterPreisProNacht[i];
   }
   newFilter[newFilter.length - 1] = "PreisProNacht = " + Database.getSqlString(preisProNacht);
   filterPreisProNacht = newFilter;
 }
示例#14
0
 /**
  * Erstellt einen neuen Filter für die ZimmerNr. Bereits vorhandene Filter dieses Typs bleiben
  * erhalten und werden mit einem OR kombiniert.
  *
  * @param zimmerNr Die gewünschte Zimmernummer.
  */
 public void addFilterZimmerNr(Integer zimmerNr) {
   String[] newFilter = new String[filterZimmerNr.length + 1];
   for (int i = 0; i < filterZimmerNr.length; i++) {
     newFilter[i] = filterZimmerNr[i];
   }
   newFilter[newFilter.length - 1] = "ZimmerNr = " + Database.getSqlString(zimmerNr);
   filterZimmerNr = newFilter;
 }
 /*
  * Durchschnittswert der Sterne ermitteln
  */
 private void getAvgStars() throws SQLException {
   if (film_id != null) {
     ResultSet rs = db.showAvgStars(film_id);
     while (rs.next()) {
       avgStar = rs.getString("round");
     }
   }
 }
示例#16
0
 /**
  * Erstellt einen neuen Suchfilter für die ZimmerNr. Im Gegensatz zu normalen Filtern findet
  * dieser Filter auch dann Zimmernummern, wenn nur ein Teilstring angegeben wurde. Bereits
  * vorhandene Filter dieses Typs bleiben erhalten und werden mit einem OR kombiniert.
  *
  * @param zimmerNr Die gewünschte Zimmernummer.
  */
 public void addSearchFilterZimmerNr(String zimmerNr) {
   String[] newFilter = new String[filterZimmerNr.length + 1];
   for (int i = 0; i < filterZimmerNr.length; i++) {
     newFilter[i] = filterZimmerNr[i];
   }
   newFilter[newFilter.length - 1] =
       "CAST(ZimmerNr AS VARCHAR(10) ) LIKE " + Database.getSqlString("%" + zimmerNr + "%");
   filterZimmerNr = newFilter;
 }
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   HttpSession session = request.getSession();
   if (session.getAttribute("user") != null) {
     try {
       Group staff = Database.getInstance().getGroup(2);
       User user = (User) session.getAttribute("user");
       if (Database.getInstance().isInGroup(user, staff)) {
         String strroundid = request.getParameter("id");
         int roundid = Integer.parseInt(strroundid);
         String title = request.getParameter("title");
         String description = request.getParameter("description");
         String strenddate = request.getParameter("enddate");
         String endtime = request.getParameter("endtime");
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         java.util.Date endDate = sdf.parse(strenddate);
         java.sql.Date endSqlDate = new Date(endDate.getTime());
         java.sql.Time endSqlTime = java.sql.Time.valueOf(endtime);
         Round round = new Round(0, title, description, "Closed");
         Round dbRound = Database.getInstance().getRound(roundid);
         Countdown dbCountdown = Database.getInstance().getCountdown(dbRound);
         Countdown countdown =
             new Countdown(
                 dbCountdown.getId(),
                 round.getTitle(),
                 "Countdown of "
                     + round.getTitle()
                     + ", which is is about: "
                     + round.getDescription(),
                 endSqlDate,
                 endSqlTime);
         if (Database.getInstance().updateRound(round, countdown))
           response.sendRedirect("round.jsp?id=" + roundid);
         else response.getOutputStream().print("Error while saving the round!");
       } else {
         response.getOutputStream().print("you are not staff");
       }
     } catch (Exception e) {
       response.getOutputStream().print("Error while saving the round!");
     }
   } else {
     response.getOutputStream().print("Not logged in");
   }
 }
示例#18
0
  public String[] getDineAvtaler(int d, int m, int a) {
    String dato = datoAsString(d, m, a);
    ArrayList<String> temp = new ArrayList<String>();
    ResultSet rs =
        db.readQuery(
            "SELECT avtaleid, dato, starttid, sluttid, beskrivelse, romid, sted, kommer "
                + "FROM avtale NATURAL JOIN erinviterttil "
                + "WHERE synlig = 1 AND dato = '"
                + dato
                + "' AND brukernavn = '"
                + bruker
                + "'");
    try {
      int count = 0;
      while (rs.next()) {
        String avtaleid = Integer.toString(rs.getInt(1));
        while (avtaleid.length() < 4) {
          avtaleid = "0" + avtaleid;
        }
        temp.add(
            avtaleid
                + ": "
                + rs.getString(2).substring(0, 2)
                + "."
                + rs.getString(2).substring(2, 4)
                + "."
                + rs.getString(2).substring(4)
                + " "
                + rs.getString(3)
                + " - "
                + rs.getString(4)
                + ": "
                + rs.getString(5)
                + " i ");
        if (rs.getString(6) == null) {
          temp.set(count, temp.get(count) + rs.getString(7) + ".");
        } else {
          temp.set(count, temp.get(count) + "Rom " + rs.getInt(6) + ".");
        }
        if (rs.getString(8) == null) {
          temp.set(count, temp.get(count) + " Du har ikke svart på invitasjonen.");
        } else if (rs.getBoolean(8)) {
          temp.set(count, temp.get(count) + " Du har svart ja.");
        } else {
          temp.set(count, temp.get(count) + " Du har svart nei.");
        }
        count++;
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
    String[] dineavtaler = new String[temp.size()];
    temp.toArray(dineavtaler);
    return dineavtaler;
  }
示例#19
0
  @Before
  public void setUp() throws Exception {
    Database.setFileName("test.dat");
    dataBase.eraseFile();
    dataBase.load();
    AccountOwner newAccountOwner = new AccountOwner("Michael Powell", "P$1111");
    newAccountOwner.put();
    AccountOwner newAccountOwner2 = new AccountOwner("Ann Singh", "P$2222");
    newAccountOwner2.put();

    Account newAccount = new Account("O1001", "Checking", "50.00");
    newAccount.put();
    Account newAccount2 = new Account("O1001", "Savings", "50.00");
    newAccount2.put();
    Account newAccount3 = new Account("O1002", "Savings", "50.00");
    newAccount3.put();
    Account newAccount4 = new Account("O1002", "Checking", "250.00");
    newAccount4.put();

    Assert.assertEquals("A1004", Account.get("A1004").getId());
    Assert.assertEquals("O1002", AccountOwner.get("O1002").getId());
  }
  public AffinityCredential() {
    super(AffinityConstants.CLIENT_ID, AffinityConstants.CLIENT_SECRET);
    try {
      tokenURL = new URL("https://a1.easemob.com/affinity/affinity/token");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      tokenURL = null;
    }

    db = new Database();

    token = db.getToken();
  }
 /*
  * Filminformationen aus DB laden
  */
 private void getMovieDetails() throws SQLException {
   ResultSet rs = db.showMovieByID(film_id);
   while (rs.next()) {
     coverUrl = rs.getString("cover_url");
     titel = rs.getString("titel");
     fsk = rs.getString("fsk");
     filmstart = rs.getString("kinostart");
     inhalt = rs.getString("inhalt");
     genre = rs.getString("genre");
     laenge = rs.getString("laenge");
     jahr = rs.getString("jahr");
     land = rs.getString("land");
   }
   ResultSet rs2 = db.showRegisseurByMovieID(film_id);
   while (rs2.next()) {
     regisseur = rs2.getString("name");
   }
   ResultSet rs3 = db.showDarstellerByMovieID(film_id);
   while (rs3.next()) {
     darsteller = rs3.getString("name");
   }
 }
示例#22
0
 private Vector<? extends Databasable> DoSearch(
     Class cl, String firstName, String lastName, Database db) {
   db.connect();
   Vector<Databasable> searchresult = new Vector<Databasable>();
   if (firstName == null) {
     if (lastName == null) {
       searchresult = null;
     } else {
       database.Search s =
           new database.Search(cl, "getSurName", "%" + lastName.toUpperCase() + "%")
               .setWildCardSearch(true)
               .setCaseSensitive(false);
       searchresult = db.readAll(s);
     }
   } else {
     if (lastName == null) {
       database.Search s =
           new database.Search(cl, "getFirstName", "%" + firstName.toUpperCase() + "%")
               .setWildCardSearch(true)
               .setCaseSensitive(false);
       searchresult = db.readAll(s);
     } else {
       database.Search s =
           new database.Search(
                   cl,
                   "getFirstName;getSurName",
                   "%" + firstName.toUpperCase() + "%",
                   "%" + lastName.toUpperCase() + "%")
               .setWildCardSearch(true)
               .setCaseSensitive(false);
       searchresult = db.readAll(s);
     }
   }
   db.disconnect();
   return searchresult;
 }
  @Override
  public Token getToken() {
    if (null == token || token.isExpired()) {
      try {
        ObjectNode objectNode = factory.objectNode();
        objectNode.put("grant_type", "client_credentials");
        objectNode.put("client_id", tokenKey1);
        objectNode.put("client_secret", tokenKey2);
        List<NameValuePair> headers = new ArrayList<>();
        headers.add(new BasicNameValuePair("Content-Type", "application/json"));

        HttpPost httpPost = new HttpPost();
        httpPost.setURI(tokenURL.toURI());

        for (NameValuePair nameValuePair : headers) {
          httpPost.addHeader(nameValuePair.getName(), nameValuePair.getValue());
        }
        httpPost.setEntity(new StringEntity(objectNode.toString(), "UTF-8"));

        HttpResponse tokenResponse = client.execute(httpPost);
        HttpEntity entity = tokenResponse.getEntity();

        String results = EntityUtils.toString(entity, "UTF-8");

        if (tokenResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

          ObjectMapper mapper = new ObjectMapper();

          JsonFactory factory = mapper.getJsonFactory();
          JsonParser jp = factory.createJsonParser(results);
          JsonNode json = mapper.readTree(jp);

          String accessToken = json.get("access_token").asText();
          Long expiredAt = System.currentTimeMillis() + json.get("expires_in").asLong() * 1000;

          db.updateToken(accessToken, expiredAt);

          token = new Token(accessToken, expiredAt);
        }
      } catch (Exception e) {
        throw new RuntimeException(
            "Some errors occurred while fetching a token by username and password .");
      }
    }

    return token;
  }
示例#24
0
 public boolean harAnsattAvtale(int day, int maaned, int aar) {
   ResultSet rs =
       db.readQuery(
           "SELECT count(avtaleid) FROM avtale WHERE dato = '"
               + datoAsString(day, maaned, aar)
               + "'");
   int count = 0;
   try {
     rs.next();
     count = rs.getInt(1);
   } catch (SQLException e) {
     e.printStackTrace();
   }
   if (count > 0) {
     return true;
   }
   return false;
 }
示例#25
0
 public boolean kommerTilAvtale(int day, int maaned, int aar) {
   ResultSet rs =
       db.readQuery(
           "SELECT count(avtaleid) FROM avtale NATURAL JOIN erinviterttil"
               + " WHERE dato = '"
               + datoAsString(day, maaned, aar)
               + "' AND brukernavn = '"
               + this.bruker
               + "' "
               + "AND kommer = 1");
   int count = 0;
   try {
     rs.next();
     count = rs.getInt(1);
   } catch (SQLException e) {
     e.printStackTrace();
   }
   if (count > 0) {
     return true;
   }
   return false;
 }
示例#26
0
 @Override
 public String processRequest(RequestType type, HttpServletRequest request, Session session) {
   String response = replaceTags(template, "MASTERSERVLET", createLink(session));
   String classtype = request.getParameter("type");
   if (classtype == null) {
     response = replaceTags(response, "CALENDAR", "");
   } else {
     if (classtype.equals("student")) {
       String result = request.getParameter("searchresult");
       if (result == null) {
         // zoek op in de database met studenten
         Database db = getDB();
         Vector<Student> searchresult =
             (Vector<Student>)
                 DoSearch(
                     Student.class,
                     request.getParameter("firstname"),
                     request.getParameter("lastname"),
                     db);
         if ((searchresult == null) || (searchresult.isEmpty())) {
           response = replaceTags(response, "CALENDAR", "##search_nothingfound##");
         }
         // als er maar 1 resultaat is, toon de kalender van de persoon
         else if (searchresult.size() == 1) {
           String link =
               CalendarTools.GeneratePHPiCalendarLink(
                   searchresult.get(0), session.getAccount().getLanguage());
           response =
               replaceTags(response, "CALENDAR", replaceTags(calendarTemplate, "LINK", link));
         } else {
           response =
               replaceTags(
                   response,
                   "CALENDAR",
                   replaceTags(scriptTemplate, "LINK", createLink(session) + "&type=student"));
           response =
               replaceTags(
                   response,
                   "SEARCHRESULTS",
                   HTMLInterfaceTool.changeToDataTable("results", searchresult));
         }
       } else // Er is geklikt op een rechtstreekse student waarvan het antwoord nu getoond moet
              // worden
       {
         // zoek op in de database met studenten
         Database db = getDB();
         db.connect();
         database.Search s = new database.Search(Student.class, "getStudentNumber", result);
         String link =
             CalendarTools.GeneratePHPiCalendarLink(
                 db.<Student>read(s), session.getAccount().getLanguage());
         response = replaceTags(response, "CALENDAR", replaceTags(calendarTemplate, "LINK", link));
       }
     } else if (classtype.equals("educator")) {
       String result = request.getParameter("searchresult");
       if (result == null) {
         Database db = getDB();
         Vector<Educator> searchresult =
             (Vector<Educator>)
                 DoSearch(
                     Educator.class,
                     request.getParameter("firstname"),
                     request.getParameter("lastname"),
                     db);
         if ((searchresult == null) || (searchresult.isEmpty())) {
           response = replaceTags(response, "CALENDAR", "##search_nothingfound##");
         } else if (searchresult.size() == 1) {
           String link =
               CalendarTools.GeneratePHPiCalendarLink(
                   searchresult.get(0), session.getAccount().getLanguage());
           response =
               replaceTags(response, "CALENDAR", replaceTags(calendarTemplate, "LINK", link));
         } else {
           response =
               replaceTags(
                   response,
                   "CALENDAR",
                   replaceTags(scriptTemplate, "LINK", createLink(session) + "&type=educator"));
           response =
               replaceTags(
                   response,
                   "SEARCHRESULTS",
                   HTMLInterfaceTool.changeToDataTable("results", searchresult));
         }
       } else // Er is geklikt op een rechtstreekse student waarvan het antwoord nu getoond moet
              // worden
       {
         // zoek op in de database met studenten
         Database db = getDB();
         db.connect();
         database.Search s = new database.Search(Educator.class, "getEmployeeNumber", result);
         String link =
             CalendarTools.GeneratePHPiCalendarLink(
                 db.<Educator>read(s), session.getAccount().getLanguage());
         response = replaceTags(response, "CALENDAR", replaceTags(calendarTemplate, "LINK", link));
         db.disconnect();
       }
     } else if (classtype.equals("room")) {
       Database db = getDB();
       db.connect();
       database.Search s =
           new database.Search(Room.class, "getLocation", request.getParameter("roomnumber"));
       Room searchresult = db.read(s);
       db.disconnect();
       if (searchresult == null) {
         response = replaceTags(response, "CALENDAR", "##search_nothingfound##");
       } else {
         String link =
             CalendarTools.GeneratePHPiCalendarLink(
                 searchresult, session.getAccount().getLanguage());
         response = replaceTags(response, "CALENDAR", replaceTags(calendarTemplate, "LINK", link));
       }
     }
   }
   return response;
 }
示例#27
0
public class Query {

  static Database database = Database.getInstance();

  public static LinkedHashMap<String, AccountOwnerData> getAllOwners() {
    LinkedHashMap<String, AccountOwnerData> list = new LinkedHashMap<String, AccountOwnerData>();
    for (Entry<String, Object> entry : database.data.entrySet()) {
      String key = entry.getKey();
      Object obj = entry.getValue();
      if (obj instanceof AccountOwnerData) {
        AccountOwnerData recordOwner = (AccountOwnerData) obj;
        list.put(key, recordOwner);
      }
    }
    return (list);
  }

  public static LinkedHashMap<String, AccountData> getAllAccounts() {
    LinkedHashMap<String, AccountData> list = new LinkedHashMap<String, AccountData>();
    for (Entry<String, Object> entry : database.data.entrySet()) {
      Object obj = entry.getValue();
      String key = entry.getKey();
      if (obj instanceof AccountData) {
        AccountData recordAccount = (AccountData) obj;
        list.put(key, recordAccount);
      }
    }
    return (list);
  }

  public static LinkedHashMap<String, ArrayList<Object>> getAllTransactionsByAccount() {

    LinkedHashMap<String, ArrayList<Object>> list = new LinkedHashMap<String, ArrayList<Object>>();

    for (Entry<String, Object> entry : database.data.entrySet()) {
      Object obj = entry.getValue();
      if ((obj instanceof String)
          || (obj instanceof AccountOwnerData)
          || (obj instanceof AccountData)) {
        continue;
      }

      if (obj instanceof DepositData) {
        DepositData deposit = (DepositData) obj;
        ArrayList<Object> members =
            (list.get(deposit.accountId) == null
                ? new ArrayList<Object>()
                : list.get(deposit.accountId));
        members.add(deposit);
        list.put(deposit.accountId, members);
      }

      if (obj instanceof WithdrawalData) {
        WithdrawalData withdraw = (WithdrawalData) obj;
        ArrayList<Object> members =
            (list.get(withdraw.accountId) == null
                ? new ArrayList<Object>()
                : list.get(withdraw.accountId));
        members.add(withdraw);
        list.put(withdraw.accountId, members);
      }

      if (obj instanceof TransferData) {
        TransferData transfer = (TransferData) obj;

        ArrayList<Object> members =
            (list.get(transfer.fromAccountId) == null
                ? new ArrayList<Object>()
                : list.get(transfer.fromAccountId));
        members.add(transfer);
        list.put(transfer.fromAccountId, members);

        members =
            (list.get(transfer.toAccountId) == null
                ? new ArrayList<Object>()
                : list.get(transfer.toAccountId));
        members.add(transfer);
        list.put(transfer.toAccountId, members);
      }
    }
    return (list);
  }

  public static LinkedHashMap<String, Object> getAllTransactions() {

    LinkedHashMap<String, Object> list = new LinkedHashMap<String, Object>();

    for (Entry<String, Object> entry : database.data.entrySet()) {
      Object obj = entry.getValue();
      String key = entry.getKey();
      if ((obj instanceof String)
          || (obj instanceof AccountOwnerData)
          || (obj instanceof AccountData)) {
        continue;
      }
      list.put(key, obj);
    }
    return (list);
  }

  public void getAll() {

    System.out.println("All Owners:");
    for (Entry<String, AccountOwnerData> entry : getAllOwners().entrySet()) {
      Object obj = entry.getKey();
      System.out.println(obj + " = " + entry.getValue());
    }

    System.out.println("All Accounts:");
    for (Entry<String, AccountData> entry : getAllAccounts().entrySet()) {
      Object obj = entry.getKey();
      System.out.println(obj + " = " + entry.getValue());
    }
    System.out.println("All Transactions by Account:");
    for (Entry<String, ArrayList<Object>> entry : getAllTransactionsByAccount().entrySet()) {
      Object obj = entry.getKey();
      System.out.println(obj + " = " + entry.getValue());
    }
  }
}
  public void go() {
    List<String> categories = db.getCategoryNames();
    view.makeCategoryCombo(categories);
    ActionListener keyWordActionListener =
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent arg0) {
            int totalComponents = view.getAddPanel().getComponentCount();
            JPanel anotherAddKeyWordsPane = new JPanel();
            final JLabel removeLabel = new JLabel("remove");
            removeLabel.setForeground(Color.blue);
            removeLabel.addMouseListener(
                new MouseListener() {
                  @Override
                  public void mouseClicked(MouseEvent arg0) {
                    view.getAddPanel().remove(removeLabel.getParent());
                    view.getAddPanel().revalidate();
                  }

                  @Override
                  public void mouseEntered(MouseEvent arg0) {
                    removeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
                  }

                  @Override
                  public void mouseExited(MouseEvent arg0) {
                    removeLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                  }

                  @Override
                  public void mousePressed(MouseEvent arg0) {}

                  @Override
                  public void mouseReleased(MouseEvent arg0) {}
                });
            JLabel tfAnotherAddKeyWords = new JLabel(view.getKeyWordsTextFeild().getText());
            view.getKeyWordsTextFeild().setText("");
            anotherAddKeyWordsPane.setLayout(new GridLayout(0, 2));
            anotherAddKeyWordsPane.add(removeLabel);
            anotherAddKeyWordsPane.add(tfAnotherAddKeyWords);
            view.getAddPanel().add(anotherAddKeyWordsPane, totalComponents - 5);
            view.getAddPanel().revalidate();
          }
        };

    view.getKeyWordsTextFeild().addActionListener(keyWordActionListener);

    view.getCancelButton()
        .addActionListener(
            new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent arg0) {
                splitController.addCancelButtonPressed();
              }
            });

    view.getSaveButton()
        .addActionListener(
            new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent arg0) {
                List<String> dummy = new ArrayList<String>();
                dummy.add(view.getComboAddCategory().getSelectedItem().toString());
                if (db.addCodeExample(
                        view.getAddTitle().getText(),
                        view.getTfAddDescription().getText(),
                        view.getAddCode().getText(),
                        view.getAddProgrammingLanguage().getSelectedItem().toString(),
                        dummy,
                        view.getAddPublic().isSelected())
                    == 2) {
                  view.addNameNotUnique();
                } else {
                  splitController.addSaveButtonPressed(view.getAddTitle().getText());
                }
              }
            });
  }
  /**
   * build the {@link Transaction} list and filter also for {@link #acc}, {@link
   * #paymentReason},{@link #from} and {@link #until}
   *
   * @return the filtered {@link Transaction} list
   */
  public List<Transaction> calculateTransactions() {
    List<Account> accounts = accountController.getAccounts();
    if (accounts == null) return null;

    Account fromAcc = null;
    for (Account account : accounts) {
      if (account.toString().equals(acc)) {
        fromAcc = account;
        break;
      }
    }

    List<Transaction> result = new ArrayList<Transaction>();
    List<Transaction> transactions;
    try {
      transactions = Database.getInstance().getTransactions(fromAcc);
    } catch (Throwable e) {
      return null;
    }

    if (transactions == null) return null;

    Pattern payment = null;
    if (paymentReason != null) {
      payment = Pattern.compile(".*" + Pattern.quote(paymentReason.toLowerCase()) + ".*");
    }

    if (from == null && until == null) result = transactions;

    if (from != null && until == null)
      for (Transaction transaction : transactions)
        if (transaction.getDate().after(from)) result.add(transaction);

    if (from != null && until != null)
      for (Transaction transaction : transactions)
        if (transaction.getDate().after(from) && transaction.getDate().before(until))
          result.add(transaction);

    if (from == null && until != null)
      for (Transaction transaction : transactions)
        if (transaction.getDate().before(until)) result.add(transaction);

    List<Transaction> endResult = new LinkedList<Transaction>();
    if (paymentReason == null) {
      endResult = result;
    } else {
      for (Transaction transaction : result) {
        if (payment.matcher(transaction.getPaymentReason().toLowerCase()).matches()) {
          endResult.add(transaction);
        }
      }
    }

    //		for (Transaction transaction : endResult) {
    //			if(transaction.getFromAccount().getAccountID() == fromAcc.getAccountID()){
    //				if(transaction.getAmount().floatValue() > 0)
    //					transaction.setAmount(transaction.getAmount().negate());
    //			}
    //		}
    return endResult;
  }
示例#30
0
public class WithdrawalTest {

  Database dataBase = Database.getInstance();

  @Before
  public void setUp() throws Exception {
    Database.setFileName("test.dat");
    dataBase.eraseFile();
    dataBase.load();
    AccountOwner newAccountOwner = new AccountOwner("Michael Powell", "P$1111");
    newAccountOwner.put();
    AccountOwner newAccountOwner2 = new AccountOwner("Ann Singh", "P$2222");
    newAccountOwner2.put();

    Account newAccount = new Account("O1001", "Checking", "50.00");
    newAccount.put();
    Account newAccount2 = new Account("O1001", "Savings", "50.00");
    newAccount2.put();
    Account newAccount3 = new Account("O1002", "Savings", "50.00");
    newAccount3.put();
    Account newAccount4 = new Account("O1002", "Checking", "250.00");
    newAccount4.put();

    Assert.assertEquals("A1004", Account.get("A1004").getId());
    Assert.assertEquals("O1002", AccountOwner.get("O1002").getId());
  }

  @After
  public void tearDown() throws Exception {}

  @Test
  public void UpdateWithdrawal() {
    // Testing proper password and withdrawal amount updates account to correct new balance. UAT
    // 5.1, 5.3 & 5.4

    Withdrawal newWithdrawal = new Withdrawal("O1002", "A1004", "50.00");
    Assert.assertEquals("Invalid Password", newWithdrawal.updateBalance("P@1234"));
    Assert.assertEquals("valid", newWithdrawal.updateBalance("P$2222"));
    Account newAccount4 = Account.get(newWithdrawal.getAccountId());
    Assert.assertEquals("200.00", newAccount4.getBalance());
    newWithdrawal.put();

    newWithdrawal = new Withdrawal("O1002", "A1004", "100.00");
    Assert.assertEquals("valid", newWithdrawal.updateBalance("P$2222"));
    newAccount4 = Account.get(newWithdrawal.getAccountId());
    Assert.assertEquals("100.00", newAccount4.getBalance());

    newWithdrawal = new Withdrawal("O1002", "A1004", "50.25");
    Assert.assertEquals("valid", newWithdrawal.updateBalance("P$2222"));
    newAccount4 = Account.get(newWithdrawal.getAccountId());
    Assert.assertEquals("49.75", newAccount4.getBalance());
  }

  /*
   @Test
   public void WithdrawalNotNegative() {
  	 //Testing withdrawals do not contain a negative amount. UAT 5.2
  	 Withdrawal withdrawal = new Withdrawal("01002", "A1004", "-100");
  	 //Assert.assertEquals("valid", withdrawal.validateWithdrawalAmount("-100"));
  	 Assert.assertEquals("Withdrawal amount cannot be negative", withdrawal.validateWithdrawalAmount(withdrawal.getWithdrawalAmount()));
   }


   @Test
   public void amountNotGreaterThanBalance() {
  	//Testing withdrawal amounts are not greater than balances, so there cannot be negative balances after withdrawing. UAT 5.5

  	 Withdrawal newWithdrawal = new Withdrawal("O1002", "A1004", "350.00");
  	 Assert.assertEquals("Withdrawal amount cannot be greater than balance", newWithdrawal.validateWithdrawalAmount(newWithdrawal.getWithdrawalAmount()));
   }


   @Test
   public void notEmpty() {
  	 //Testing withdrawals do not contain empty values. UAT 5.6
   	 Withdrawal newWithdrawal = new Withdrawal("O1001","A1001","");
  	 Assert.assertEquals("Withdrawal amount cannot be empty", newWithdrawal.validateWithdrawalAmount(newWithdrawal.getWithdrawalAmount()));
   }

   @Test
   public void testWithdrawalAmountIsNumeric() {
  	//Testing withdrawals do not contain any char or string data. UAT 5.7
  	 Withdrawal withdrawal1 = new Withdrawal ("O1002","A1004","23w");
  	 Assert.assertEquals("Withdrawal amount must be numeric",  withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","23.00");
  	 Assert.assertEquals("valid", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  }

   @Test
   public void testwithdrawalAmountMustBeDollarsAndCents () {
  	//Testing withdrawals do not contain more than two decimal places. UAT 5.8
  	 Withdrawal withdrawal1 = new Withdrawal ("O1002","A1004","1.234");
  	 Assert.assertEquals("Amount must be dollars and cents", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","1.23");
  	 Assert.assertEquals("valid", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  }

   @Test
   public void TestWithdrawalAmountCannotBeBlank() {
  	 //Testing withdrawals do not contain spaces (blanks). UAT 5.9
  	 Withdrawal withdrawal1 = new Withdrawal ("O1002","A1004"," ");
  	 Assert.assertEquals("Withdrawal amount cannot be blank", withdrawal1.validateWithdrawalAmount(" "));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","      ");
  	 Assert.assertEquals("Withdrawal amount cannot be blank", withdrawal1.validateWithdrawalAmount(" "));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","50.00");
  	 Assert.assertEquals("valid", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  }

   @Test
   public void TestWithdrawalAmountCannotBeZero() {
  	 //Testing withdrawals do not contain a zero amount. UAT 5.10
  	 Withdrawal withdrawal1 = new Withdrawal ("O1002","A1004","0.00");
  	 Assert.assertEquals("Withdrawal amount cannot be zero", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","0.0");
  	 Assert.assertEquals("Withdrawal amount cannot be zero", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","0");
  	 Assert.assertEquals("Withdrawal amount cannot be zero", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004",".00");
  	 Assert.assertEquals("Withdrawal amount cannot be zero", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  	 withdrawal1 = new Withdrawal ("O1002","A1004","1.00");
  	 Assert.assertEquals("valid", withdrawal1.validateWithdrawalAmount(withdrawal1.getWithdrawalAmount()));
  }

   */
} // End DepositTest