/** * This method stores an xml document given as an org.w3c.dom.Document to the database giving it * an indentifier. If the identifier provided is null, then the database generates a unique * identifier on its own. * * @param doc The dom represntation of the document to be stored as an org.w3c.dom.Document. * @param resourceId The resourceId to give to the document as a unique identifier within the * database. If null a unique identifier is automatically generated. * @param collection The name of the collection to store the document under. If it does not exist, * it is created. * @param username The identifier of the user calling the method used for authentication. * @param password The password of the user calling the method used for authentication. */ public void storeDomDocument( Document doc, String resourceId, String collection, String username, String password) { try { // initialize driver Class cl = Class.forName(_driver); Database database = (Database) cl.newInstance(); DatabaseManager.registerDatabase(database); // try to get collection Collection col = DatabaseManager.getCollection(_URI + collection, username, password); if (col == null) { // collection does not exist: get root collection and create // for simplicity, we assume that the new collection is a // direct child of the root collection, e.g. /db/test. // the example will fail otherwise. Collection root = DatabaseManager.getCollection(_URI + "/db"); CollectionManagementService mgtService = (CollectionManagementService) root.getService("CollectionManagementService", "1.0"); col = mgtService.createCollection(collection.substring("/db".length())); } // create new XMLResource; an id will be assigned to the new resource XMLResource document = (XMLResource) col.createResource(resourceId, "XMLResource"); document.setContentAsDOM(doc.getDocumentElement()); col.storeResource(document); } catch (Exception e) { e.printStackTrace(); } }
/** * This method retrieves an xml document from the database based on its resource identifier. The * document is returned as an org.w3c.dom.Document. * * @param collection The name of the collection to look for the document. * @param resourceId The resource identifier of the document to be retrieved. * @param username The identifier of the user calling the method used for authentication. * @param password The password of the user calling the method used for authentication. * @return The xml document retrieved as an org.w3c.dom.Document. */ public Document retrieveDocument( String collection, String resourceId, String username, String password) { Document doc = null; try { // initialize database driver Class cl = Class.forName(_driver); Database database = (Database) cl.newInstance(); DatabaseManager.registerDatabase(database); // get the collection Collection col = DatabaseManager.getCollection(_URI + collection, username, password); col.setProperty(OutputKeys.INDENT, "no"); XMLResource res = (XMLResource) col.getResource(resourceId); if (res == null) System.out.println("document not found!"); else { doc = (Document) (res.getContentAsDOM()).getOwnerDocument(); } } catch (Exception e) { e.printStackTrace(); } return doc; }
private void writeAllContacts(List<Contact> contacts) { mDatabaseManager.deleteAllContacts(); contacts = mContactUtil.sortContacts(contacts, Calendar.getInstance()); for (Contact contact : contacts) { mDatabaseManager.addContact(contact); } }
public void initialFill(String month) { try { ResultSet query = dbm.query("SELECT * FROM prcr_margin_dates WHERE month LIKE '" + month + "'"); row = 0; while (query.next()) { division = query.getString("division"); margin = query.getShort("margin"); workingdays = query.getShort("total"); table.setValueAt(division, row, 0); table.setValueAt(margin, row, 2); table.setValueAt(workingdays, row, 1); row++; } if (row == 0) { query = dbm.query("SELECT * FROM division_details"); while (query.next()) { division = query.getString("code"); table.setValueAt(division, row, 0); row++; } } query.close(); } catch (SQLException ex) { Logger.getLogger(PRCR_change_margin_dates.class.getName()).log(Level.SEVERE, null, ex); } }
// test new player registration public void testRegisterPlayer() { assertTrue(DatabaseManager.getInstance().registerPlayer("hello")); DBPlayer player = DatabaseManager.getInstance().getPlayer((playerId) + ""); assertEquals(playerId, player.getPlayerId()); assertEquals("hello", player.getPassword()); assertEquals(1, player.getLoggedIn()); assertEquals((playerId) + "", player.getName()); assertEquals(0, player.getWins()); assertEquals(0, player.getLosses()); assertEquals(0, player.getRating()); }
// try and clean up after ourselves a little bit protected void tearDown() throws Exception { super.tearDown(); try { DatabaseManager.getInstance().unregisterPlayer(playerId + "", "hello"); } catch (Exception e) { } try { DatabaseManager.getInstance().unregisterPlayer(playerId + "", "goodbye"); } catch (Exception e) { } }
// test changing player info public void testChangePlayerInfo() { System.out.println(playerId + ""); DBPlayer player = DatabaseManager.getInstance().getPlayer((playerId) + ""); System.out.println(player.getPlayerId() + " ; " + player.getPassword()); assertTrue( DatabaseManager.getInstance().changePlayerInfo(playerId + "", "hello", "test", "goodbye")); assertFalse( DatabaseManager.getInstance() .changePlayerInfo(playerId + "", "The wrong password", "test", "goodbye")); player = DatabaseManager.getInstance().getPlayer((playerId) + ""); assertEquals("goodbye", player.getPassword()); assertEquals("test", player.getName()); }
// test logging in and out public void testLoginAndLogout() { String s = "<request version=\"1.0\" id=\"589a39591271844e3fbe32bbb9281ad9\"><login player=\"" + playerId + "\" password=\"goodbye\" self-register=\"false\"/></request>"; Document d = Message.construct(s); Message m1 = new Message(d); m1.setOriginator(playerId + ""); assertFalse(DatabaseManager.getInstance().loginPlayer(playerId + "", "hello")); assertTrue(DatabaseManager.getInstance().logoutPlayer(m1)); assertFalse(DatabaseManager.getInstance().loginPlayer(playerId + "", "wrong password")); assertTrue(DatabaseManager.getInstance().loginPlayer(playerId + "", "hello")); }
public static void main(String[] args) { DatabaseManager dbm = DatabaseManager.getInstance(); List<Field> fields = generateFields(); Table table = new Table(TABLE_NAME, fields); dbm.createIfDoesntExist(table); Entry entry = generateEntry(fields); dbm.updateEntry(table, entry); dbm.getFullEntrySet(table); }
public boolean fillDatabase( String table_name, String table_column_giving1, Object row_element1, String table_column_giving2, Object row_element2, String table_column_need, Object update_element) { // if (checkDataAvailability("prcr_margin_dates", "month", st, "division", division, // "margin")) { // updateDatabase("prcr_margin_dates", "month", st, "division", division, // "total", workingdays); // updateDatabase("prcr_margin_dates", "month", st, "division", division, // "margin", Math.floor(workingdays * 0.75)); // } else { // dbm.insert("INSERT INTO prcr_margin_dates(month,division,margin,total) // VALUES('" + st + "','" + division + "','" + Math.floor(workingdays * 0.75) + "','" + // workingdays + "')"); // } // // // DatabaseManager dbm = DatabaseManager.getDbCon(); try { dbm.insert( "UPDATE " + table_name + " SET " + table_column_need + " ='" + update_element + "' where " + table_column_giving1 + " LIKE '" + row_element1 + "' AND " + table_column_giving2 + " LIKE '" + row_element2 + "'"); } catch (SQLException ex) { MessageBox.showMessage(ex.getMessage(), "SQL ERROR", "error"); return false; } return true; }
@Override public List<DamageItem> findAll() throws Exception { try { con = db.getConnect(); String sql = "select * from damaged"; PreparedStatement statement = (PreparedStatement) con.prepareStatement(sql); ResultSet result = statement.executeQuery(); List<DamageItem> dl = new ArrayList<>(); while (result.next()) { DamageItem di = new DamageItem(); di.setId(result.getInt("id")); di.setItem(result.getString("item")); di.setQty(result.getInt("qty")); di.setReason(result.getString("reason")); di.setDate(result.getString("date")); di.setStaffstamp(result.getString("staffStamp")); dl.add(di); } return dl; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; }
@Override public boolean update(DamageItem d) throws Exception { String sql = "update damaged set item = ?, qty = ?, reason = ? , date = ? , staffStamp = ? where id = " + d.getId(); try { con = db.getConnect(); PreparedStatement statement = (PreparedStatement) con.prepareStatement(sql); statement.setString(1, d.getItem()); statement.setInt(2, d.getQty()); statement.setString(3, d.getReason()); statement.setString(4, d.getDate()); statement.setString(5, d.getStaffstamp()); statement.executeUpdate(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
public Long saveTrack(TrackDob trackDob) { long insertId = -1; try { ContentValues values = new ContentValues(); values.put(COL_TAG, trackDob.getTag()); values.put(COL_START_TIME, trackDob.getStartTime()); values.put(COL_FIRST_LAT, trackDob.getFirstLat()); values.put(COL_FIRST_LON, trackDob.getFirstLon()); values.put(COL_FIRST_ADDRESS, trackDob.getFirstAddress()); values.put(COL_FINISH_TIME, trackDob.getFinishTime()); values.put(COL_LAST_LAT, trackDob.getLastLat()); values.put(COL_LAST_LON, trackDob.getLastLon()); values.put(COL_LAST_ADDRESS, trackDob.getLastAddress()); values.put(COL_DISTANCE, trackDob.getDistance()); values.put(COL_MAX_SPEED, trackDob.getMaxSpeed()); values.put(COL_AVE_SPEED, trackDob.getAveSpeed()); values.put(COL_MAX_ALT, trackDob.getMaxAlt()); values.put(COL_MIN_ALT, trackDob.getMinAlt()); values.put(COL_ELEV_DIFF_UP, trackDob.getElevDiffUp()); values.put(COL_ELEV_DIFF_DOWN, trackDob.getElevDiffDown()); values.put(COL_NOTE, trackDob.getNote()); insertId = DatabaseManager.getDb().insert(TABLE_NAME, null, values); if (Const.LOG_ENHANCED) Log.i(TAG, "Track successfully saved with id = " + insertId); } catch (Exception e) { Log.e(TAG, "Cannot save track", e); } return insertId; }
public void deleteTrack(Long value) { try { DatabaseManager.getDb().delete(TABLE_NAME, COL_ID + "=" + value, null); } catch (Exception e) { Log.e(TAG, "Can't delete row", e); } }
/** * Executes a generic CompiledStatement. Execution includes first building any subquery result * dependencies and clearing them after the main result is built. * * @return the result of executing the statement * @param cs any valid CompiledStatement */ Result execute(CompiledStatement cs) { Result result = null; DatabaseManager.gc(); try { cs.materializeSubQueries(session); result = executeImpl(cs); } catch (Throwable t) { // t.printStackTrace(); result = new Result(t, cs.sql); } // clear redundant data cs.dematerializeSubQueries(); if (result == null) { result = emptyResult; } return result; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); mydb = new DatabaseManager(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list); // adding it to the list view. obj = (ListView) findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent( getApplicationContext(), com.example.junghyeonkim.androidproject.MainScreen.class); intent.putExtras(dataBundle); startActivity(intent); } }); }
public static boolean checkIfEntryExistsByToken(String token) { PreparedStatement preparedStatement = null; ResultSet results = null; connect = DatabaseManager.getConnectionToDatabase(); try { preparedStatement = connect.prepareStatement("SELECT token " + "FROM Devices " + "WHERE token = ?"); preparedStatement.setString(1, token); results = preparedStatement.executeQuery(); if (results.next()) { return true; } } catch (SQLException ex) { ex.printStackTrace(); } return false; }
public static String getGcmIdByToken(String token) { PreparedStatement preparedStatement = null; ResultSet results = null; connect = DatabaseManager.getConnectionToDatabase(); try { preparedStatement = connect.prepareStatement("SELECT gcmId " + "FROM Devices " + "WHERE token = ?"); preparedStatement.setString(1, token); results = preparedStatement.executeQuery(); if (results.next()) { return results.getString("gcmId"); } } catch (SQLException ex) { ex.printStackTrace(); } return null; }
public Contact getContact(long userId) { final Cursor cursor = mDatabaseManager.getContact(userId); cursor.moveToNext(); final Contact contact = createContact(cursor); cursor.close(); return contact; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); if (DatabaseManager.getInstance(this).getActualGame() != null) findViewById(R.id.button_continue).setVisibility(View.VISIBLE); }
/** * Opens this database. The database should be opened after construction. or reopened by the * close(int closemode) method during a "shutdown compact". Closes the log if there is an error. */ void reopen() { boolean isNew = false; setState(DATABASE_OPENING); try { nameManager = new HsqlNameManager(this); granteeManager = new GranteeManager(this); userManager = new UserManager(this); schemaManager = new SchemaManager(this); persistentStoreCollection = new PersistentStoreCollectionDatabase(this); isReferentialIntegrity = true; sessionManager = new SessionManager(this); collation = collation.newDatabaseInstance(); dbInfo = DatabaseInformation.newDatabaseInformation(this); txManager = new TransactionManager2PL(this); lobManager.createSchema(); sessionManager.getSysLobSession().setSchema(SqlInvariants.LOBS_SCHEMA); schemaManager.setSchemaChangeTimestamp(); schemaManager.createSystemTables(); // completed metadata logger.open(); isNew = logger.isNewDatabase; if (isNew) { String username = urlProperties.getProperty("user", "SA"); String password = urlProperties.getProperty("password", ""); userManager.createFirstUser(username, password); schemaManager.createPublicSchema(); logger.checkpoint(false); } lobManager.open(); dbInfo.setWithContent(true); checkpointRunner = new CheckpointRunner(); timeoutRunner = new TimeoutRunner(); } catch (Throwable e) { logger.close(Database.CLOSEMODE_IMMEDIATELY); logger.releaseLock(); setState(DATABASE_SHUTDOWN); clearStructures(); DatabaseManager.removeDatabase(this); if (!(e instanceof HsqlException)) { e = Error.error(ErrorCode.GENERAL_ERROR, e); } logger.logSevereEvent("could not reopen database", e); throw (HsqlException) e; } setState(DATABASE_ONLINE); }
public boolean updateDatabase( String table_name, String table_column_giving, Object row_element, String table_column_giving2, Object row_element2, String table_column_need, Object update_element) { // DatabaseManager dbm = DatabaseManager.getDbCon(); try { dbm.insert( "UPDATE " + table_name + " SET " + table_column_need + " ='" + update_element + "' WHERE " + table_column_giving + "='" + row_element + "' AND " + table_column_giving2 + "='" + row_element2 + "'"); } catch (SQLException ex) { MessageBox.showMessage(ex.getMessage(), "SQL ERROR", "error"); return false; } return true; }
public boolean checkDataAvailability( String table_name, String table_column_giving1, String row_element1, String table_column_giving2, String row_element2, String table_column_need) { // DatabaseManager dbm = DatabaseManager.getDbCon(); try { ResultSet query = dbm.query( "SELECT * FROM " + table_name + " where " + table_column_giving1 + " LIKE '" + row_element1 + "' AND " + table_column_giving2 + " LIKE '" + row_element2 + "'"); while (query.next()) { // s = query.getString(table_column_need); return true; } query.close(); } catch (SQLException ex) { return false; } return false; }
public static boolean insertHack(String[] values) { boolean retVal = false; Connection con = null; Statement st = null; try { try { con = DatabaseManager.getConnection(); st = con.createStatement(); st.executeUpdate( "INSERT INTO hacklist(header, context, target, datatype, relation, contribution, motive, malwaretype, malwarename, systemtype, malwaresource, browsertype, hdate, notes, cio, sources) " + "VALUES ('" + values[0] + "','" + values[1] + "','" + values[2] + "','" + values[3] + "','" + values[4] + "','" + values[5] + "','" + values[6] + "','" + values[7] + "','" + values[8] + "','" + values[9] + "','" + values[10] + "','" + values[11] + "','" + values[12] + "','" + values[13] + "','" + values[14] + "','" + values[15] + "')"); retVal = true; } finally { if (st != null) { st.close(); con.close(); } } } catch (Exception e) { retVal = false; System.out.println("Database Error !!" + e.getMessage()); } return retVal; }
/** * Opens this database. The database should be opened after construction. or reopened by the * close(int closemode) method during a "shutdown compact". Closes the log if there is an error. */ void reopen() throws HsqlException { boolean isNew; setState(DATABASE_OPENING); try { databaseProperties = new HsqlDatabaseProperties(this); isNew = !DatabaseURL.isFileBasedDatabaseType(sType) || !databaseProperties.checkFileExists(); if (isNew && urlProperties.isPropertyTrue("ifexists")) { throw Trace.error(Trace.DATABASE_NOT_EXISTS, sName); } databaseProperties.load(); databaseProperties.setURLProperties(urlProperties); compiledStatementManager.reset(); nameManager = new HsqlNameManager(); granteeManager = new GranteeManager(this); userManager = new UserManager(this); hAlias = Library.getAliasMap(); schemaManager = new SchemaManager(this); bReferentialIntegrity = true; sessionManager = new SessionManager(this); txManager = new TransactionManager(this); collation = new Collation(); dbInfo = DatabaseInformation.newDatabaseInformation(this); databaseProperties.setDatabaseVariables(); if (DatabaseURL.isFileBasedDatabaseType(sType)) { logger.openLog(this); } if (isNew) { sessionManager .getSysSession() .sqlExecuteDirectNoPreChecks("CREATE USER SA PASSWORD \"\" ADMIN"); logger.synchLogForce(); } dbInfo.setWithContent(true); } catch (Throwable e) { logger.closeLog(Database.CLOSEMODE_IMMEDIATELY); logger.releaseLock(); setState(DATABASE_SHUTDOWN); clearStructures(); DatabaseManager.removeDatabase(this); if (!(e instanceof HsqlException)) { e = Trace.error(Trace.GENERAL_ERROR, e.toString()); } throw (HsqlException) e; } setState(DATABASE_ONLINE); }
/** * Main method of the example class. * * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception { System.out.println("=== XMLDBInsert ==="); // Collection instance Collection col = null; try { // Register the database Class<?> c = Class.forName(DRIVER); Database db = (Database) c.newInstance(); DatabaseManager.registerDatabase(db); System.out.println("\n* Get collection."); // Receive the collection col = DatabaseManager.getCollection(DBNAME); // ID for the new document String id = "world"; // Content of the new document String doc = "<xml>Hello World!</xml>"; System.out.println("\n* Create new resource."); // Create a new XML resource with the specified ID XMLResource res = (XMLResource) col.createResource(id, XMLResource.RESOURCE_TYPE); // Set the content of the XML resource as the document res.setContent(doc); System.out.println("\n* Store new resource."); // Store the resource into the database col.storeResource(res); } catch (final XMLDBException ex) { // Handle exceptions System.err.println("XML:DB Exception occurred " + ex.errorCode); ex.printStackTrace(); } finally { // Close the collection if (col != null) col.close(); } }
public List<Contact> getContacts() { final Cursor cursor = mDatabaseManager.getAllContacts(); List<Contact> contacts = new ArrayList<Contact>(); while (cursor.moveToNext()) { contacts.add(createContact(cursor)); } cursor.close(); return contacts; }
@Override public boolean prepare() { if (databaseManager == null) { return true; } log.info("Loading species " + name); try { databaseManager.pullGenes(this); databaseManager.pullInteractions(this); log.info("Loading " + name + " complete."); databaseManager = null; /* Stop reloading. */ return true; } catch (SQLException e) { log.fatal("Failed to load species " + name, e); return false; } }
public Collection<Section> getSections(int cid) { try { Collection<Section> sections = new ArrayList<Section>(); String qry = "select SectId from SECTION where CourseId = ?"; PreparedStatement pstmt = conn.prepareStatement(qry); pstmt.setInt(1, cid); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int sectid = rs.getInt("SectId"); sections.add(dbm.findSection(sectid)); } rs.close(); return sections; } catch (SQLException e) { dbm.cleanup(); throw new RuntimeException("error getting course sections", e); } }
@WorkerThread public void getSpecificSection( Context context, int sectionPos, OnSectionDetailReadyListener listener) { SectionModel section = mTopSections.get(sectionPos); String sectionName = section.getName(); if (CommonUtil.isEmpty(mDetailSections) || !mDetailSections.containsKey(sectionName)) { if (CommonUtil.checkInternetConnection(context)) { // try downloading data from web RawViaplayModel detail = null; try { detail = getSectionFromWeb(section.getUrl()); populateSectionDetailCache(section, detail); returnSectionDetailToListener(sectionName, listener); DatabaseManager.getInstance() .saveDataToDb(SectionDetailModel.generateFrom(detail, section)); } catch (IOException e) { Log.e(TAG, "Error while downloading section"); } } else { // try retrieving data from db SectionDetailModel detail = DatabaseManager.getInstance().getSectionDetailFromDb(section); populateSectionDetailCache(section, detail); returnSectionDetailToListener(sectionName, listener); } } else { Log.d(TAG, "Retrieving data from cache"); returnSectionDetailToListener(sectionName, listener); } }