/** Test the correct behavior of a in-memory database. */ @Test public void inMemoryTest() { Database database = null; String path = ":memory:"; try { database = new Database(path); } catch (InvalidDriverException e) { fail(e.getMessage()); } catch (IncompatibleVersionException e) { fail(e.getMessage()); } catch (DatabaseAccessException e) { fail(e.getMessage()); } // path should be :memory: only if (database != null) { assertEquals(database.getPath(), path); } // all other tests have to work on a in-memory database as well String[] features = {"dim0", "dim1", "dim2"}; boolean[] outlierFlags = {false, false, true}; float[][] objects = {{1.1f, 1.2f, 1.3f}, {2.1f, 2.2f, 2.3f}, {3.1f, 3.2f, 3.3f}}; try { this.database.initFeatures(features, outlierFlags); this.database.pushSubspace(1, new int[] {2, 3}, "testSubspace"); this.database.pushObject(objects); this.database.updateFeaturesMinMax(); } catch (DatabaseAccessException e) { fail("In-memory database is not working correctly."); } }
public int percentage(int choiceId, int questionId) { int numAnswers = 0; int totalAnswers = 0; try { numAnswers = Integer.parseInt( database .executeQuery("SELECT COUNT(*) FROM Answers WHERE cid=" + choiceId) .get(0) .get("COUNT(*)")); totalAnswers = Integer.parseInt( database .executeQuery( "SELECT COUNT(*) FROM (Answers NATURAL JOIN Choices) WHERE qid=" + questionId) .get(0) .get("COUNT(*)")); // List <HashMap< String,String >> qrs = this.executeQuery("SELECT * FROM Questions // WHERE qid NOT IN (SELECT qid FROM Answers NATURAL JOIN Choices WHERE username=\"" + // username + "\") ORDER BY RANDOM() LIMIT 1;"); if (totalAnswers == 0) return 0; double r = numAnswers / (double) totalAnswers; return (int) (r * 100); } catch (Exception e) { return 0; } }
public void populateHistory(Database dbp) { Histrec hrec = new Histrec(); hrec.set_amount(10); byte[] arr = new byte[4]; // sizeof(int) int i; DatabaseEntry kdbt = new DatabaseEntry(arr); kdbt.setSize(arr.length); DatabaseEntry ddbt = new DatabaseEntry(hrec.data); ddbt.setSize(hrec.data.length); try { for (i = 1; i <= history; i++) { kdbt.setRecordNumber(i); hrec.set_aid(random_id(ACCOUNT)); hrec.set_bid(random_id(BRANCH)); hrec.set_tid(random_id(TELLER)); dbp.append(null, kdbt, ddbt); } } catch (DatabaseException dbe) { errExit(dbe, "Failure initializing history file"); } }
public void run() { double gtps, itps; int n, ret; long start_time, end_time; // // Open the database files. // int err; try { DatabaseConfig config = new DatabaseConfig(); config.setTransactional(true); adb = dbenv.openDatabase(null, "account", null, config); bdb = dbenv.openDatabase(null, "branch", null, config); tdb = dbenv.openDatabase(null, "teller", null, config); hdb = dbenv.openDatabase(null, "history", null, config); } catch (DatabaseException dbe) { TpcbExample.errExit(dbe, "Open of db files failed"); } catch (FileNotFoundException fnfe) { TpcbExample.errExit(fnfe, "Open of db files failed, missing file"); } start_time = (new Date()).getTime(); for (txns = n = ntxns, failed = 0; n-- > 0; ) if ((ret = txn()) != 0) failed++; end_time = (new Date()).getTime(); if (end_time == start_time) end_time++; System.out.println( getName() + ": " + (long) txns + " txns: " + failed + " failed, " + TpcbExample.showRounded((txns - failed) / (double) (end_time - start_time), 2) + " TPS"); try { adb.close(); bdb.close(); tdb.close(); hdb.close(); } catch (DatabaseException dbe2) { TpcbExample.errExit(dbe2, "Close of db files failed"); } }
public int getTotalAnswers() { try { return Integer.parseInt( database.executeQuery("SELECT COUNT(*) FROM Answers").get(0).get("COUNT(*)")); } catch (Exception e) { System.err.println("Statistics.getTotalAnswers(): " + e.getMessage()); return 0; } }
public void apply() { User user = db.emailExist(email); if (user.getEmail() != null) { Properties props = System.getProperties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.from", "*****@*****.**"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); props.setProperty("mail.debug", "true"); Session session = Session.getDefaultInstance(props); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("*****@*****.**")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("This is the Subject Line!"); String newPw = gen.nextSessionId(); user.setPassword(newPw); if (db.changePassword(user)) { message.setText( "Hi,\n \n You requested a reset of your password." + "\n \n Your new password is now: " + newPw); Transport transport = session.getTransport("smtp"); transport.connect("*****@*****.**", "catering123"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Sent message successfully...."); } FacesMessage fm = new FacesMessage("Email sent"); FacesContext.getCurrentInstance().addMessage(null, fm); } catch (MessagingException mex) { mex.printStackTrace(); // } } } else { FacesMessage fm = new FacesMessage("Email was not found"); FacesContext.getCurrentInstance().addMessage(null, fm); } }
/** * Checks to see if a valid record id has been entered. * * @param record_id the record id * @return True if the id is valid. False otherwise. */ public boolean isValidID(int record_id) { db = new Database(); db.connect(); conn = db.getConnection(); String sql = "select count(*) from radiology_record where record_id = " + record_id; int count = 0; try { stmt = conn.createStatement(); rset = stmt.executeQuery(sql); while (rset != null && rset.next()) { count = (rset.getInt(1)); } } catch (SQLException e) { response_message = e.getMessage(); } finally { db.close(conn, stmt, null, rset); } if (count == 0) { return false; } return true; }
public void populateTable(Database dbp, int start_id, int balance, int nrecs, String msg) { Defrec drec = new Defrec(); DatabaseEntry kdbt = new DatabaseEntry(drec.data); kdbt.setSize(4); // sizeof(int) DatabaseEntry ddbt = new DatabaseEntry(drec.data); ddbt.setSize(drec.data.length); // uses whole array try { for (int i = 0; i < nrecs; i++) { kdbt.setRecordNumber(start_id + (int) i); drec.set_balance(balance); dbp.putNoOverwrite(null, kdbt, ddbt); } } catch (DatabaseException dbe) { System.err.println("Failure initializing " + msg + " file: " + dbe.toString()); System.exit(1); } }
@SuppressWarnings({"unchecked", "deprecation"}) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response_message = ""; HttpSession session = request.getSession(); FileItem image_file = null; int record_id = 0; int image_id; InputStream instream = null; OutputStream full_outstream = null; OutputStream thumb_outstream = null; OutputStream regular_outstream = null; // Check if there is any input in the record id field if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) { response_message = "<p><font color=ff0000>No ID entered!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } try { // Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List<FileItem> FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator<FileItem> i = FileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("recordID")) { record_id = Integer.parseInt(item.getString()); if (!isValidID(record_id)) { response_message = "<p><font color=ff0000>Invalid record id!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } } // out.println(item.getFieldName() + ": " + // item.getString()); } else { image_file = item; if (image_file.getName().equals("")) { response_message = "<p><font color=ff0000>No file selected!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } } } // Get the image stream instream = image_file.getInputStream(); BufferedImage full_image = ImageIO.read(instream); BufferedImage thumbnail = shrink(full_image, THUMBNAIL_SHRINK); BufferedImage regular_image = shrink(full_image, REGULAR_SHRINK); // Connect to the database db = new Database(); db.connect(); conn = db.getConnection(); stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery(SQL_IMAGE_ID); rset1.next(); image_id = rset1.getInt(1); // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty // blob stmt.execute( "INSERT INTO pacs_images VALUES(" + record_id + "," + image_id + ", empty_blob(), empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB thumb = ((OracleResultSet) rset).getBLOB("thumbnail"); BLOB regular = ((OracleResultSet) rset).getBLOB("regular_size"); BLOB full = ((OracleResultSet) rset).getBLOB("full_size"); // Write the image to the blob object full_outstream = full.getBinaryOutputStream(); ImageIO.write(full_image, "jpg", full_outstream); thumb_outstream = thumb.getBinaryOutputStream(); ImageIO.write(thumbnail, "jpg", thumb_outstream); regular_outstream = regular.getBinaryOutputStream(); ImageIO.write(regular_image, "jpg", regular_outstream); stmt.executeUpdate("commit"); response_message = "<p>Upload OK!</p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } catch (Exception ex) { response_message = ex.getMessage(); } finally { if (instream != null) { instream.close(); } if (full_outstream != null) { full_outstream.close(); } if (thumb_outstream != null) { thumb_outstream.close(); } if (regular_outstream != null) { regular_outstream.close(); } db.close(conn, stmt, null, rset); } }
// // XXX Figure out the appropriate way to pick out IDs. // int txn() { Cursor acurs = null; Cursor bcurs = null; Cursor hcurs = null; Cursor tcurs = null; Transaction t = null; Defrec rec = new Defrec(); Histrec hrec = new Histrec(); int account, branch, teller; DatabaseEntry d_dbt = new DatabaseEntry(); DatabaseEntry d_histdbt = new DatabaseEntry(); DatabaseEntry k_dbt = new DatabaseEntry(); DatabaseEntry k_histdbt = new DatabaseEntry(); account = TpcbExample.this.random_id(TpcbExample.ACCOUNT); branch = TpcbExample.this.random_id(TpcbExample.BRANCH); teller = TpcbExample.this.random_id(TpcbExample.TELLER); // The history key will not actually be retrieved, // but it does need to be set to something. byte[] hist_key = new byte[4]; k_histdbt.setData(hist_key); k_histdbt.setSize(4 /* == sizeof(int)*/); byte[] key_bytes = new byte[4]; k_dbt.setData(key_bytes); k_dbt.setSize(4 /* == sizeof(int)*/); d_dbt.setData(rec.data); d_dbt.setUserBuffer(rec.length(), true); hrec.set_aid(account); hrec.set_bid(branch); hrec.set_tid(teller); hrec.set_amount(10); // Request 0 bytes since we're just positioning. d_histdbt.setPartial(0, 0, true); // START PER-TRANSACTION TIMING. // // Technically, TPCB requires a limit on response time, you only // get to count transactions that complete within 2 seconds. // That's not an issue for this sample application -- regardless, // here's where the transaction begins. try { t = dbenv.beginTransaction(null, null); acurs = adb.openCursor(t, null); bcurs = bdb.openCursor(t, null); tcurs = tdb.openCursor(t, null); hcurs = hdb.openCursor(t, null); // Account record k_dbt.setRecordNumber(account); if (acurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS) throw new Exception("acurs get failed"); rec.set_balance(rec.get_balance() + 10); acurs.putCurrent(d_dbt); // Branch record k_dbt.setRecordNumber(branch); if (bcurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS) throw new Exception("bcurs get failed"); rec.set_balance(rec.get_balance() + 10); bcurs.putCurrent(d_dbt); // Teller record k_dbt.setRecordNumber(teller); if (tcurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS) throw new Exception("ccurs get failed"); rec.set_balance(rec.get_balance() + 10); tcurs.putCurrent(d_dbt); // History record d_histdbt.setPartial(0, 0, false); d_histdbt.setData(hrec.data); d_histdbt.setUserBuffer(hrec.length(), true); if (hdb.append(t, k_histdbt, d_histdbt) != OperationStatus.SUCCESS) throw new DatabaseException("put failed"); acurs.close(); acurs = null; bcurs.close(); bcurs = null; tcurs.close(); tcurs = null; hcurs.close(); hcurs = null; // null out t in advance; if the commit fails, // we don't want to abort it in the catch clause. Transaction tmptxn = t; t = null; tmptxn.commit(); // END TIMING return (0); } catch (Exception e) { try { if (acurs != null) acurs.close(); if (bcurs != null) bcurs.close(); if (tcurs != null) tcurs.close(); if (hcurs != null) hcurs.close(); if (t != null) t.abort(); } catch (DatabaseException dbe) { // not much we can do here. } if (TpcbExample.this.verbose) { System.out.println( "Transaction A=" + String.valueOf(account) + " B=" + String.valueOf(branch) + " T=" + String.valueOf(teller) + " failed"); System.out.println("Reason: " + e.toString()); } return (-1); } }
// // Initialize the database to the number of accounts, branches, // history records, and tellers given to the constructor. // public void populate() { Database dbp = null; int err; int balance, idnum; int end_anum, end_bnum, end_tnum; int start_anum, start_bnum, start_tnum; int h_nelem; idnum = BEGID; balance = 500000; h_nelem = accounts; try { DatabaseConfig config = new DatabaseConfig(); config.setType(DatabaseType.HASH); config.setHashNumElements(h_nelem); config.setAllowCreate(true); dbp = dbenv.openDatabase(null, "account", null, config); } catch (Exception e1) { // can be DatabaseException or FileNotFoundException errExit(e1, "Open of account file failed"); } start_anum = idnum; populateTable(dbp, idnum, balance, h_nelem, "account"); idnum += h_nelem; end_anum = idnum - 1; try { dbp.close(); } catch (DatabaseException e2) { errExit(e2, "Account file close failed"); } if (verbose) System.out.println( "Populated accounts: " + String.valueOf(start_anum) + " - " + String.valueOf(end_anum)); // // Since the number of branches is very small, we want to use very // small pages and only 1 key per page. This is the poor-man's way // of getting key locking instead of page locking. // h_nelem = (int) branches; try { DatabaseConfig config = new DatabaseConfig(); config.setType(DatabaseType.HASH); config.setHashNumElements(h_nelem); config.setHashFillFactor(1); config.setPageSize(512); config.setAllowCreate(true); dbp = dbenv.openDatabase(null, "branch", null, config); } catch (Exception e3) { // can be DatabaseException or FileNotFoundException errExit(e3, "Branch file create failed"); } start_bnum = idnum; populateTable(dbp, idnum, balance, h_nelem, "branch"); idnum += h_nelem; end_bnum = idnum - 1; try { dbp.close(); } catch (DatabaseException dbe4) { errExit(dbe4, "Close of branch file failed"); } if (verbose) System.out.println( "Populated branches: " + String.valueOf(start_bnum) + " - " + String.valueOf(end_bnum)); // // In the case of tellers, we also want small pages, but we'll let // the fill factor dynamically adjust itself. // h_nelem = (int) tellers; try { DatabaseConfig config = new DatabaseConfig(); config.setType(DatabaseType.HASH); config.setHashNumElements(h_nelem); config.setHashFillFactor(0); config.setPageSize(512); config.setAllowCreate(true); dbp = dbenv.openDatabase(null, "teller", null, config); } catch (Exception e5) { // can be DatabaseException or FileNotFoundException errExit(e5, "Teller file create failed"); } start_tnum = idnum; populateTable(dbp, idnum, balance, h_nelem, "teller"); idnum += h_nelem; end_tnum = idnum - 1; try { dbp.close(); } catch (DatabaseException e6) { errExit(e6, "Close of teller file failed"); } if (verbose) System.out.println( "Populated tellers: " + String.valueOf(start_tnum) + " - " + String.valueOf(end_tnum)); try { DatabaseConfig config = new DatabaseConfig(); config.setType(DatabaseType.RECNO); config.setRecordLength(HISTORY_LEN); config.setAllowCreate(true); dbp = dbenv.openDatabase(null, "history", null, config); } catch (Exception e7) { // can be DatabaseException or FileNotFoundException errExit(e7, "Create of history file failed"); } populateHistory(dbp); try { dbp.close(); } catch (DatabaseException e8) { errExit(e8, "Close of history file failed"); } }