📄 driverrdb.java
字号:
private void removeSpecializedGraph(SpecializedGraph graph) {
graph.clear();
}
/**
* Method setDatabaseProperties.
*
* Sets the current properties for the database.
*
* @param databaseProperties is a Graph containing a full set of database properties
*/
public void setDatabaseProperties(Graph databaseProperties) {
SpecializedGraph toGraph = getSystemSpecializedGraph(true);
// really need to start a transaction here
// Here add code to check if the database has been used - if so,
// it's too late to change the properties, so throw an exception
toGraph.clear();
SpecializedGraph.CompletionFlag complete = new SpecializedGraph.CompletionFlag();
toGraph.add(databaseProperties, complete);
// Now test the properties to see if it's a valid set - if not,
// throw an exception - it's okay to check some things later (there's
// no guarantee that every error will be caught here).
// end transaction here.
}
/**
* Method getDefaultModelProperties
*
* Return the default properties for a new model stored in this database.
* If none are stored, then load default properties into the database.
* @return Graph containg the default properties for a new model
*/
public DBPropGraph getDefaultModelProperties() {
SpecializedGraph sg = getSystemSpecializedGraph(true);
DBPropGraph result = DBPropGraph.findPropGraphByName(sg, DEFAULT_PROPS);
if (result == null) {
logger.error("No default Model Properties found");
// Construct the parameters that will be the
// default settings for any graph added to this database
//new DBPropGraph( m_sysProperties, "default", "generic");
//result = DBPropGraph.findPropGraph(sg, "default");
}
return result;
}
/**
* Test if the database has previously been formatted.
*
* @return boolean true if database is correctly formatted, false on any error.
*/
public boolean isDBFormatOK() throws RDFRDBException {
boolean result = true;
boolean[] found = new boolean[SYSTEM_TABLE_CNT];
int i = 0;
for (i = 0; i < SYSTEM_TABLE_CNT; i++) found[i] = false;
try {
for ( Iterator iter = getAllTables().iterator() ; iter.hasNext(); )
{
String tblName = (String)iter.next();
for (i = 0; i < SYSTEM_TABLE_CNT; i++)
if (SYSTEM_TABLE_NAME[i].equals(tblName))
found[i] = true;
}
for (i = 0; i < SYSTEM_TABLE_CNT; i++) {
if (!found[i]) {
// mutex table is not required
if (SYSTEM_TABLE_NAME[i].equals(MUTEX_TABLE))
continue;
result = false;
}
}
} catch (Exception e1) {
// An exception might be an unformatted or corrupt
// db or a connection problem.
throw new RDFRDBException("Exception while checking db format - " + e1, e1);
}
return result;
}
/**
* Converts string to form accepted by database.
*/
public String stringToDBname(String aName) {
String result = (DB_NAMES_TO_UPPER) ? aName.toUpperCase() : aName;
return(result);
}
private static final int lockTryMax = 5; // max attempts to acquire/release lock
/**
* return true if the mutex is acquired, else false
*/
public boolean tryLockDB() {
boolean res = true;
try {
m_sql.runSQLGroup("lockDatabase", MUTEX_TABLE);
} catch (SQLException e) {
res = false;
}
return res;
}
public void lockDB() throws RDFRDBException {
String err = "";
int cnt = 0;
while ( cnt++ < lockTryMax ) {
if ( tryLockDB() )
break;
try {
Thread.sleep((long)5000);
} catch (InterruptedException e) {
err = err + " lockDB sleep interrupted" + e;
}
}
if ( cnt >= lockTryMax ) {
err = "Failed to lock database after "+ lockTryMax + " attempts.\n"
+ err + "\n"
+ "Try later or else call DriverRDB.unlockDB() after ensuring\n" +
"that no other Jena applications are using the database.";
throw new RDFRDBException(err);
}
}
/**
* Release the mutex lock in the database.
*/
public void unlockDB() throws RDFRDBException {
String err;
int cnt = 0;
while ( cnt++ < lockTryMax ) {
try {
m_sql.runSQLGroup("unlockDatabase", MUTEX_TABLE);
break;
} catch (SQLException e) {
err = "Failed to unlock database after "+ lockTryMax + " attempts - " + e;
try {
Thread.sleep((long)5000);
} catch (InterruptedException e1) {
err = err + " sleep failed" + e;
}
}
if ( cnt >= lockTryMax )
throw new RDFRDBException(err);
}
}
/* return true if the mutex is held. */
public boolean DBisLocked() throws RDFRDBException {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
String prefixMatch = stringToDBname(TABLE_NAME_PREFIX + "%");
ResultSet iter = dbmd.getTables(null, null, MUTEX_TABLE, tableTypes);
try { return iter.next(); } finally { iter.close(); }
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver" + e1);
}
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.graphRDB.IRDBDriver#cleanDB()
*/
public void cleanDB() {
// assumes database lock is not held.
try {
lockDB();
} catch (RDFRDBException e) {
throw new RDFRDBException(
"DriverRDB.cleanDB() failed to acquire database lock:\n"
+ "("
+ e
+ ")\n."
+ "Try again or call DriverRDB.unlockDB() if necessary.");
}
// now clean the database
doCleanDB(true);
}
/*
* internal routine that does the actual work for cleanDB().
* it assumes that the mutex is held and throws and exception
* if not. it will optionally remove the mutex if dropMutex
* is true.
*/
protected void doCleanDB( boolean dropMutex ) throws RDFRDBException {
try {
if ( !DBisLocked() ) {
throw new RDFRDBException(
"Internal error in driver - database not locked for cleaning.\n");
}
} catch ( RDFRDBException e ) {
throw new RDFRDBException(
"Exception when checking for database lock - \n"
+ e);
}
//ResultSet alltables=null;
try {
List tablesPresent = getAllTables() ;
Iterator it = tablesPresent.iterator();
// Do the MUTEX clean after all other tables.
while (it.hasNext()) {
String tblName = (String) it.next();
if ( tblName.equals(MUTEX_TABLE) )
continue;
m_sql.runSQLGroup("dropTable", tblName);
}
// Mutex to be removed as well?
if ( dropMutex && tablesPresent.contains(MUTEX_TABLE) )
m_sql.runSQLGroup("dropTable", MUTEX_TABLE);
if (PRE_ALLOCATE_ID)
clearSequences();
} catch (SQLException e1) {
throw new RDFRDBException("Internal error in driver while cleaning database\n"
+ "(" + e1 + ").\n"
+ "Database may be corrupted. Try cleanDB() again.");
}
m_sysProperties = null;
if ( prefixCache != null ) prefixCache.clear();
prefixCache = null;
}
protected List getAllTables() {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
String prefixMatch = stringToDBname(TABLE_NAME_PREFIX + "%");
ResultSet rs = dbmd.getTables(null, null, prefixMatch, tableTypes);
List tables = new ArrayList() ;
while(rs.next())
tables.add(rs.getString("TABLE_NAME"));
rs.close() ;
return tables ;
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver - " + e1);
}
}
/**
* Drop all Jena-related sequences from database, if necessary.
* Override in subclass if sequences must be explicitly deleted.
*/
public void clearSequences() {
}
/**
* Removes named sequence from the database, if it exists.
* @param seqName
*/
public void removeSequence(String seqName) {
if (sequenceExists(seqName)) {
try {
m_sql.runSQLGroup("DropSequence",seqName);
} catch (Exception e) {
logger.warn("Unable to drop sequence " + seqName, e);
}
}
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public boolean sequenceExists(String seqName) {
Object[] args = {seqName};
ResultSet rs = null;
boolean result = false;
PreparedStatement ps=null;
try {
String op = "SelectSequenceName";
ps = m_sql.getPreparedSQLStatement(op);
ps.setString(1,seqName);
rs = ps.executeQuery();
result = rs.next();
} catch (Exception e) {
logger.error("Unable to select sequence " + seqName, e);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException e1) {
throw new RDFRDBException("Failed to get last inserted ID: " + e1);
}
if(ps!=null)m_sql.returnPreparedSQLStatement(ps);
}
return result;
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public List getSequences() {
List results = new ArrayList(10);
Object[] args = {};
ResultSet rs = null;
PreparedStatement ps = null;
try {
String opname = "SelectJenaSequences";
ps = m_sql.getPreparedSQLStatement(opname, TABLE_NAME_PREFIX);
rs = ps.executeQuery();
while (rs.next()) results.add( rs.getString(1) );
//rs.close(); //Removed after jena 2.4.
} catch (Exception e) {
logger.error("Unable to select Jena sequences: ", e);
} finally {
if(rs != null)
try {
rs.close();
} catch (SQLException e1) {
throw new RDFRDBException("Failed to get last inserted ID: " + e1);
}
if(ps!=null)m_sql.returnPreparedSQLStatement(ps);
}
return results;
}
/**
* Initialise a database ready to store RDF tables.
* @throws RDFDBException if the is a problem opening the connection or an internal SQL error.
* @deprecated Since Jena 2.0 this call is no longer needed - formatting
* happens automatically as a side effect of creating Models - there should
* be no need for an application to interact directly with the driver.
*/
public void formatDB() throws RDFRDBException {
}
/**
* Create a table for storing asserted or reified statements.
*
* @param graphId the graph which the table is created.
* @param isReif true if table stores reified statements.
* @return the name of the new table
*
*/
public String createTable( int graphId, boolean isReif) {
String opname = isReif ? "createReifStatementTable" : "createStatementTable";
int i = 0;
String params[];
while ( true ) {
params = getCreateTableParams(graphId, isReif);
try {
m_sql.runSQLGroup(opname, params);
break;
} catch (SQLException e) {
i++;
if ( i > 5 ) {
logger.warn("Problem creating table", e);
throw new RDFRDBException("Failed to create table: " + params[0], e);
}
}
}
return params[0];
}
/**
* Delete a table.
*
* @param tableName the name of the table to delete. *
*/
public void deleteTable( String tableName ) {
String opname = "dropTable";
PreparedStatement ps = null;
try {
ps = m_sql.getPreparedSQLStatement(opname, tableName);
ps.executeUpdate();
return;
} catch (Exception e1) {
throw new RDFRDBException("Failed to delete table ", e1);
}finally {
if(ps!=null)m_sql.returnPreparedSQLStatement(ps);
}
}
/**
* Throws an UnsupportedOperation exception.
*
* @param opName name of the operation that's not supported.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -