public static boolean changeDatabase(String DBname) { File dir = new File(PropertyManager.getInstance().getPathProperty("path_database")); Database rollbackDB = selectedDB; try { selectedDB.setDefaultDB(false); selectedDB.saveToFile(new File(dir.getAbsolutePath() + selectedDB.getName() + ".properties")); HibernateUtil.shutdown(); HibernateUtil.selectDatabase(DBname); selectedDB.setDefaultDB(true); selectedDB.saveToFile(new File(dir.getAbsolutePath() + selectedDB.getName() + ".properties")); HibernateUtil.initSessionFactory(); AlbumPane.getInstance().refresh(); BottomBarPane.getInstance().refreshStats(); } catch (Exception ex) { MessagePaneManager.showExceptionPane(ex, true); try { selectedDB.setDefaultDB(false); selectedDB.saveToFile( new File(dir.getAbsolutePath() + selectedDB.getName() + ".properties")); HibernateUtil.shutdown(); HibernateUtil.selectDatabase(rollbackDB.getName()); selectedDB.setDefaultDB(true); selectedDB.saveToFile( new File(dir.getAbsolutePath() + selectedDB.getName() + ".properties")); } catch (Exception e) { logger.error("Error during the rollback", e); } return false; } return true; }
public static void main(String args[]) { Database database; database = Database.getInstance("products"); System.out.println("This is the " + database.getName() + " databse."); database = Database.getInstance("employees"); System.out.println("This is the " + database.getName() + " databse."); }
/** Immediately refreshes all globals using the backing database. */ public synchronized void refreshGlobals() { bootstrapOnce.ensure(); Database database = getDatabase(); LOGGER.info("Loading globals from [{}]", database.getName()); Query<Object> globalsQuery = Query.from(Object.class).where("_id = ?", GLOBALS_ID).using(database).noCache(); State newGlobals = State.getInstance(globalsQuery.first()); if (newGlobals == null) { newGlobals = State.getInstance(globalsQuery.master().first()); } if (newGlobals == null) { newGlobals = new State(); newGlobals.setDatabase(database); newGlobals.setId(GLOBALS_ID); newGlobals.save(); } globals = newGlobals; lastGlobalsUpdate = new Date(); fieldsCache.reset(); metricFieldsCache.reset(); indexesCache.reset(); }
private void testAll(ArrayList<Database> dbs, ArrayList<Bench> tests, int size) throws Exception { for (int i = 0; i < dbs.size(); i++) { if (i > 0) { Thread.sleep(1000); } // calls garbage collection TestBase.getMemoryUsed(); Database db = dbs.get(i); System.out.println("Testing the performance of " + db.getName()); db.startServer(); Connection conn = db.openNewConnection(); DatabaseMetaData meta = conn.getMetaData(); System.out.println( " " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion()); runDatabase(db, tests, 1); runDatabase(db, tests, 1); collect = true; runDatabase(db, tests, size); conn.close(); db.log("Executed statements", "#", db.getExecutedStatements()); db.log("Total time", "ms", db.getTotalTime()); int statPerSec = db.getExecutedStatements() * 1000 / db.getTotalTime(); db.log("Statements per second", "#", statPerSec); System.out.println("Statements per second: " + statPerSec); collect = false; db.stopServer(); } }
public static List<String> getListForCombo(String[] selected) throws FileNotFoundException, IOException { List<String> res = new ArrayList<String>(); File dir = new File(PropertyManager.getInstance().getPathProperty("path_database")); File files[] = dir.listFiles( new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".properties"); } }); for (int i = 0; i < files.length; i++) { File file = files[i]; Database db = Database.loadFromFile(file); if (db.isDefaultDB()) { selected[0] = db.getName(); } res.add(db.getName()); } return res; }
/** * opens the chosen file, reads in the file, and prints out a receipt * * @param chosenFile */ private void readSource(File chosenFile) { String chosenFileName = chosenFile.getName(); TextFileInput inFile = new TextFileInput(chosenFileName); Container myContentPane = jframe.getContentPane(); // chosenFile TextArea myTextArea = new TextArea(); myContentPane.add(myTextArea); int count = 0; float priceTotal = 0.0f; Database db = new Database("database2.txt"); String[] transaction = new String[100]; String line = inFile.readLine(); DecimalFormat df = new DecimalFormat("#00.00"); while (line != null) { StringTokenizer tokenized = new StringTokenizer(line, ","); String code = tokenized.nextToken(); float weight = Float.parseFloat(tokenized.nextToken()); String name; float price; try { name = db.getName(code); } catch (ItemNotFoundException e) { name = JOptionPane.showInputDialog(null, "Item " + code + " not found. Enter Name: "); } try { price = db.getPrice(code); } catch (ItemNotFoundException e) { price = Float.valueOf( JOptionPane.showInputDialog( null, "Price for " + name + " not found. Enter price: ")); } float itemTotal = weight * price; priceTotal += itemTotal; transaction[count] = name + "\t" + price + "\t" + df.format(weight) + "\t $" + df.format(itemTotal); count++; line = inFile.readLine(); } // while myTextArea.setText("ITEM: \t PRICE\\LB: \t POUNDS: \t TOTAL:"); myTextArea.append("\n"); for (int i = 0; i < count; i++) { myTextArea.append(transaction[i]); myTextArea.append("\n"); } myTextArea.append("\t\t TOTAL: $" + df.format(priceTotal)); jframe.setVisible(true); } // openFile
/** * Write the database settings to ./config/db.cfg. * * @param database the database to write */ public static void writeDatabaseConfig(Database database, String location) { try { FileWriter fw = new FileWriter(location + "/db.cfg"); PrintWriter pw = new PrintWriter(fw); pw.println("[Databaseconfig]"); pw.println("name:" + database.getName()); pw.println("host:" + database.getHost()); pw.println("port:" + database.getPort()); pw.println("username:"******"password:" + database.getPassword()); pw.close(); fw.close(); } catch (IOException ioe) { } }
static Document createDocumentWithProperties(Database db, Map<String, Object> properties) { Document doc = db.createDocument(); try { doc.putProperties(properties); } catch (Exception e) { Log.e(TAG, "Error creating document", e); assertTrue( "can't create new document in db:" + db.getName() + " with properties:" + properties.toString(), false); } return doc; }
private static String getDefaultDatabase() throws FileNotFoundException, IOException { File dir = new File(PropertyManager.getInstance().getPathProperty("path_database")); File files[] = dir.listFiles( new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".properties"); } }); for (int i = 0; i < files.length; i++) { File file = files[i]; Database db = Database.loadFromFile(file); if (db.isDefaultDB()) { return db.getName(); } } return null; }
private static void setDatabaseToDefault(Database dbToExcept, boolean defaultDB) throws FileNotFoundException, IOException { String filePathToExcept = dbToExcept.getName() + ".properties"; File dir = new File(PropertyManager.getInstance().getPathProperty("path_database")); File files[] = dir.listFiles( new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".properties"); } }); for (int i = 0; i < files.length; i++) { File file = files[i]; if (!file.getName().equals(filePathToExcept)) { Properties props = new Properties(); props.load(new FileInputStream(file)); props.setProperty("default", String.valueOf(defaultDB)); } } }
/** Immediately refreshes all types using the backing database. */ public synchronized void refreshTypes() { bootstrapOnce.ensure(); Database database = getDatabase(); try { TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } List<ObjectType> types = Query.from(ObjectType.class).using(database).selectAll(); int typesSize = types.size(); LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName()); // Load all types from the database first. for (ObjectType type : types) { type.getFields().size(); // Pre-fetch. temporaryTypes.add(type); } if (initializeClasses) { // Make sure that the root type exists. ObjectType rootType = getRootType(); State rootTypeState; if (rootType != null) { rootTypeState = rootType.getState(); } else { rootType = new ObjectType(); rootTypeState = rootType.getState(); rootTypeState.setDatabase(database); } Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues(); UUID rootTypeId = rootTypeState.getId(); rootTypeState.setTypeId(rootTypeId); rootTypeState.clear(); rootType.setObjectClassName(ObjectType.class.getName()); rootType.initialize(); temporaryTypes.add(rootType); try { database.beginWrites(); // Make the new root type available to other types. temporaryTypes.add(rootType); if (rootTypeState.isNew()) { State globals = getGlobals(); globals.put(ROOT_TYPE_FIELD, rootType); globals.save(); } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) { temporaryTypes.changed.add(rootTypeId); } Set<Class<? extends Recordable>> objectClasses = ClassFinder.findClasses(Recordable.class); for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) { Class<? extends Recordable> objectClass = i.next(); try { if (objectClass.isAnonymousClass() || Substitution.class.isAssignableFrom(objectClass)) { i.remove(); } } catch (IncompatibleClassChangeError error) { i.remove(); } } Set<Class<?>> globalModifications = new HashSet<Class<?>>(); Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>(); // Make sure all types are accessible to the rest of the // system as soon as possible, so that references can be // resolved properly later. for (Class<?> objectClass : objectClasses) { ObjectType type = getTypeByClass(objectClass); if (type == null) { type = new ObjectType(); type.getState().setDatabase(database); } else { type.getState().clear(); } type.setObjectClassName(objectClass.getName()); typeModifications.put(type, new ArrayList<Class<?>>()); temporaryTypes.add(type); } // Separate out all modifications from regular types. for (Class<?> objectClass : objectClasses) { if (!Modification.class.isAssignableFrom(objectClass)) { continue; } @SuppressWarnings("unchecked") Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses( (Class<? extends Modification<?>>) objectClass); if (modifiedClasses.contains(Object.class)) { globalModifications.add(objectClass); continue; } for (Class<?> modifiedClass : modifiedClasses) { List<Class<?>> assignableClasses = new ArrayList<Class<?>>(); for (Class<?> c : objectClasses) { if (modifiedClass.isAssignableFrom(c)) { assignableClasses.add(c); } } for (Class<?> assignableClass : assignableClasses) { ObjectType type = getTypeByClass(assignableClass); if (type != null) { List<Class<?>> modifications = typeModifications.get(type); if (modifications == null) { modifications = new ArrayList<Class<?>>(); typeModifications.put(type, modifications); } modifications.add(objectClass); } } } } // Apply global modifications. for (Class<?> modification : globalModifications) { ObjectType.modifyAll(database, modification); } // Initialize all types. List<Class<?>> rootTypeModifications = typeModifications.remove(rootType); initializeAndModify(temporaryTypes, rootType, rootTypeModifications); if (rootTypeModifications != null) { for (Class<?> modification : rootTypeModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } ObjectType fieldType = getTypeByClass(ObjectField.class); List<Class<?>> fieldModifications = typeModifications.remove(fieldType); initializeAndModify(temporaryTypes, fieldType, fieldModifications); if (fieldModifications != null) { for (Class<?> modification : fieldModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) { initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue()); } database.commitWrites(); } finally { database.endWrites(); } } // Merge temporary types into new permanent types. TypesCache newPermanentTypes = new TypesCache(); for (ObjectType type : permanentTypes.byId.values()) { newPermanentTypes.add(type); } for (ObjectType type : temporaryTypes.byId.values()) { newPermanentTypes.add(type); } newPermanentTypes.changed.addAll(temporaryTypes.changed); newPermanentTypes.changed.addAll(permanentTypes.changed); // If any types changed, clear all types' extras. if (!temporaryTypes.changed.isEmpty()) { for (ObjectType type : newPermanentTypes.byId.values()) { type.getState().getExtras().clear(); } } permanentTypes = newPermanentTypes; lastTypesUpdate = new Date(); } finally { temporaryTypesLocal.remove(); } ObjectType singletonType = getTypeByClass(Singleton.class); if (singletonType != null) { for (ObjectType type : singletonType.findConcreteTypes()) { if (!Query.fromType(type).where("_type = ?", type).master().noCache().hasMoreThan(0)) { try { State.getInstance(type.createObject(null)).saveImmediately(); } catch (Exception error) { LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error); } } } } for (ObjectType type : getTypes()) { Class<?> objectClass = type.getObjectClass(); if (objectClass != null) { TypePostProcessorClasses tppcAnnotation = objectClass.getAnnotation(TypePostProcessorClasses.class); if (tppcAnnotation != null) { for (Class<? extends ObjectType.PostProcessor> processorClass : tppcAnnotation.value()) { ObjectType.PostProcessor processor = (ObjectType.PostProcessor) TYPE_POST_PROCESSORS.getUnchecked(processorClass); processor.process(type); } } } } }
private void test(String... args) throws Exception { int dbId = -1; boolean exit = false; String out = "benchmark.html"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-db".equals(arg)) { dbId = Integer.parseInt(args[++i]); } else if ("-init".equals(arg)) { FileUtils.deleteRecursive("data", true); } else if ("-out".equals(arg)) { out = args[++i]; } else if ("-trace".equals(arg)) { trace = true; } else if ("-exit".equals(arg)) { exit = true; } } Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("test.properties"); prop.load(in); in.close(); int size = Integer.parseInt(prop.getProperty("size")); ArrayList<Database> dbs = new ArrayList<Database>(); for (int i = 0; i < 100; i++) { if (dbId != -1 && i != dbId) { continue; } String dbString = prop.getProperty("db" + i); if (dbString != null) { Database db = Database.parse(this, i, dbString); if (db != null) { db.setTranslations(prop); dbs.add(db); } } } ArrayList<Bench> tests = new ArrayList<Bench>(); for (int i = 0; i < 100; i++) { String testString = prop.getProperty("test" + i); if (testString != null) { Bench bench = (Bench) Class.forName(testString).newInstance(); tests.add(bench); } } testAll(dbs, tests, size); collect = false; if (dbs.size() == 0) { return; } ArrayList<Object[]> results = dbs.get(0).getResults(); Connection conn = null; PreparedStatement prep = null; Statement stat = null; PrintWriter writer = null; try { openResults(); conn = getResultConnection(); stat = conn.createStatement(); prep = conn.prepareStatement( "INSERT INTO RESULTS(TESTID, TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)"); for (int i = 0; i < results.size(); i++) { Object[] res = results.get(i); prep.setInt(1, i); prep.setString(2, res[0].toString()); prep.setString(3, res[1].toString()); for (Database db : dbs) { prep.setInt(4, db.getId()); prep.setString(5, db.getName()); Object[] v = db.getResults().get(i); prep.setString(6, v[2].toString()); prep.execute(); } } writer = new PrintWriter(new FileWriter(out)); ResultSet rs = stat.executeQuery( "CALL '<table><tr><th>Test Case</th><th>Unit</th>' " + "|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' ORDER BY DBID SEPARATOR '') FROM " + "(SELECT DISTINCT DBID, DB FROM RESULTS)" + "|| '</tr>' || CHAR(10) " + "|| SELECT GROUP_CONCAT('<tr><td>' || TEST || '</td><td>' || UNIT || '</td>' || ( " + "SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE " + "R2.TESTID = R1.TESTID) || '</tr>' ORDER BY TESTID SEPARATOR CHAR(10)) FROM " + "(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1" + "|| '</table>'"); rs.next(); String result = rs.getString(1); writer.println(result); } finally { JdbcUtils.closeSilently(prep); JdbcUtils.closeSilently(stat); JdbcUtils.closeSilently(conn); IOUtils.closeSilently(writer); } // ResultSet rsDbs = conn.createStatement().executeQuery( // "SELECT DB RESULTS GROUP BY DBID, DB ORDER BY DBID"); // while(rsDbs.next()) { // writer.println("<th>" + rsDbs.getString(1) + "</th>"); // } // ResultSet rs = conn.createStatement().executeQuery( // "SELECT TEST, UNIT FROM RESULTS " + // "GROUP BY TESTID, TEST, UNIT ORDER BY TESTID"); // while(rs.next()) { // writer.println("<tr><td>" + rs.getString(1) + "</td>"); // writer.println("<td>" + rs.getString(2) + "</td>"); // ResultSet rsRes = conn.createStatement().executeQuery( // "SELECT RESULT FROM RESULTS WHERE TESTID=? ORDER BY DBID"); // // // } // PrintWriter writer = // new PrintWriter(new FileWriter("benchmark.html")); // writer.println("<table><tr><th>Test Case</th><th>Unit</th>"); // for(int j=0; j<dbs.size(); j++) { // Database db = (Database)dbs.get(j); // writer.println("<th>" + db.getName() + "</th>"); // } // writer.println("</tr>"); // for(int i=0; i<results.size(); i++) { // Object[] res = (Object[])results.get(i); // writer.println("<tr><td>" + res[0] + "</td>"); // writer.println("<td>" + res[1] + "</td>"); // for(int j=0; j<dbs.size(); j++) { // Database db = (Database)dbs.get(j); // ArrayList r = db.getResults(); // Object[] v = (Object[])r.get(i); // writer.println( // "<td style=\"text-align: right\">" + v[2] + "</td>"); // } // writer.println("</tr>"); // } // writer.println("</table>"); if (exit) { System.exit(0); } }
/** Get the current Database name */ public static String getCurrentDatabase() { return selectedDB.getName(); }
public Connector getConnector(LockEngine lockEngine, Database database) throws MappingException, PersistenceException { if (_connectors.containsKey(lockEngine)) return (Connector) _connectors.get(lockEngine); try { if (database.getDriver() != null) { // JDO configuration file specifies a driver, use the driver // properties to create a new registry object. Properties props; Enumeration params; Param param; if (database.getDriver().getClassName() != null) { try { Class.forName(database.getDriver().getClassName()).newInstance(); } catch (Exception except) { throw new MappingException(except); } } if (DriverManager.getDriver(database.getDriver().getUrl()) == null) throw new MappingException("jdo.missingDriver", database.getDriver().getUrl()); props = new Properties(); params = database.getDriver().enumerateParam(); while (params.hasMoreElements()) { param = (Param) params.nextElement(); props.put(param.getName(), param.getValue()); } Connector c = new SQLConnector(database.getName(), database.getDriver().getUrl(), props); _connectors.put(lockEngine, c); return c; } else if (database.getDataSource() != null) { // JDO configuration file specifies a DataSource object, use the // DataSource which was configured from the JDO configuration file // to create a new registry object. DataSource ds; ds = (DataSource) database.getDataSource().getParams(); if (ds == null) throw new MappingException("jdo.missingDataSource", database.getName()); Connector c = new SQLConnector(database.getName(), ds); _connectors.put(lockEngine, c); return c; } else if (database.getJndi() != null) { // JDO configuration file specifies a DataSource lookup through JNDI, // locate the DataSource object frome the JNDI namespace and use it. Object ds; try { ds = new InitialContext().lookup(database.getJndi().getName()); } catch (NameNotFoundException except) { throw new MappingException("jdo.jndiNameNotFound", database.getJndi().getName()); } catch (NamingException except) { throw new MappingException(except); } if (!(ds instanceof DataSource)) throw new MappingException("jdo.jndiNameNotFound", database.getJndi().getName()); Connector c = new SQLConnector(database.getName(), (DataSource) ds); _connectors.put(lockEngine, c); return c; } else { throw new MappingException("jdo.missingDataSource", database.getName()); } } catch (SQLException e) { throw new PersistenceException("Exception occurs while obtaining SQL connection", e); } }