/** Method declaration */ public void run() { Channel c = init(); if (c != null) { try { while (true) { String sql = mInput.readUTF(); mServer.trace(mThread + ":" + sql); if (sql == null) { break; } write(mDatabase.execute(sql, c).getBytes()); } } catch (Exception e) { } } try { mSocket.close(); } catch (IOException e) { } if (mDatabase.isShutdown()) { System.out.println("The database is shutdown"); System.exit(0); } }
/* Method: addNewEntry - user interface Purpose: word menu, interacts with user and calls database methods to add new entries, prints out results Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void addNewEntry(Database currentThesaurus) { System.out.println("\nPlease type the word you would like to add"); System.out.print(">>"); // Will accept spaces in words // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // the wood the user wants to add String newUserWord = inputScanner.nextLine(); // checks whether the word was added successfully boolean successCheck = currentThesaurus.addEntryFromMenu(newUserWord); if (successCheck == true) { System.out.println("\n" + newUserWord + " has been " + "added to the thesaurus"); System.out.println("Would you like to add a synonym for it?"); System.out.print("type (yes/no) >>"); // does the user want to add a synonym String userResponse = inputScanner.next(); if (userResponse.equalsIgnoreCase("yes")) { // calls the same method that addNewSynonym calls currentThesaurus.addSynonymFromMenu(newUserWord); } else { System.out.println("\nGoing back to the main menu"); } } else { System.out.println("\nSorry, that word is already in the thesaurus\n"); System.out.println("Going back to the main menu"); // returns to the main menu } }
public static void computeStatistics() { Iterator<Integer> tableIt = Database.getCatalog().tableIdIterator(); System.out.println("Computing table stats."); while (tableIt.hasNext()) { int tableid = tableIt.next(); TableStats s = new TableStats(tableid, IOCOSTPERPAGE); setTableStats(Database.getCatalog().getTableName(tableid), s); } System.out.println("Done."); }
public View getView() { Database database = FrameworkUtils.getDatabase(server_, filePath_); View view = database.getView(viewName_); view.setAutoUpdate(false); view.setEnableNoteIDsForCategories(true); if (category_ == null) { if (getResortColumn() != null) { view.resortView(getResortColumn(), isAscending()); } else { view.resortView(); } } return view; }
/** * Statically analyze a query for various properties. * * @param query the query to analyze * @param params parameters for the query; if necessary parameters are left out they will be * listed as required variables in the analysis * @return a query analysis facet */ public QueryAnalysis analyze(String query, Object... params) { if (presub) query = presub(query, params); long t1 = System.currentTimeMillis(), t2 = 0, t3 = 0; DBBroker broker = null; try { broker = db.acquireBroker(); prepareContext(broker); final org.exist.source.Source source = buildQuerySource(query, params, "analyze"); final XQuery xquery = broker.getXQueryService(); final XQueryPool pool = xquery.getXQueryPool(); CompiledXQuery compiledQuery = pool.borrowCompiledXQuery(broker, source); try { AnalysisXQueryContext context; if (compiledQuery == null) { context = new AnalysisXQueryContext(broker, AccessContext.INTERNAL_PREFIX_LOOKUP); buildXQueryStaticContext(context, false); buildXQueryDynamicContext(context, params, null, false); t2 = System.currentTimeMillis(); compiledQuery = xquery.compile(context, source); t3 = System.currentTimeMillis(); } else { context = (AnalysisXQueryContext) compiledQuery.getContext(); t2 = System.currentTimeMillis(); } return new QueryAnalysis( compiledQuery, Collections.unmodifiableSet(context.requiredVariables), Collections.unmodifiableSet(context.requiredFunctions)); } finally { if (compiledQuery != null) pool.returnCompiledXQuery(source, compiledQuery); } } catch (XPathException e) { LOG.warn( "query compilation failed -- " + query + " -- " + (params == null ? "" : " with params " + Arrays.asList(params)) + (bindings.isEmpty() ? "" : " and bindings " + bindings)); throw new DatabaseException("failed to compile query", e); } catch (IOException e) { throw new DatabaseException("unexpected exception", e); } catch (PermissionDeniedException e) { throw new DatabaseException("permission denied", e); } finally { db.releaseBroker(broker); STATS.update(query, t1, t2, t3, 0, System.currentTimeMillis()); } }
public DominoModelList( final Database database, final String viewName, final String category, final Class<E> clazz) { super(clazz); server_ = database.getServer(); filePath_ = database.getFilePath(); viewName_ = viewName; category_ = category; // Gather the view info now View view = database.getView(viewName_); invalid_ = view == null; columnInfo_ = invalid_ ? null : DominoColumnInfo.fromView(view); }
/** * Constructor declaration * * @param db * @param system * @param name * @exception SQLException Description of the Exception */ Log(Database db, Session system, String name) throws SQLException { dDatabase = db; sysSession = system; sName = name; pProperties = db.getProperties(); tRunner = new Thread(this); // boucherb@users - FIXME: // standard VM behaviour is to shut down only after all // non-daemon threads exit. Therefor, tRunner shuld be // daemon. Consider the case of: /* public void main(String[] args) { ... try { // fails due to bad user/password...must then connect with valid combo // again to *really* shutdown database, or explicitly call System.exit(...) DriverManager.getConnection("jdbc:hsqldb:filespec,"user","password"); ... } catch (...) { } ... } */ // the VM will not exit, since tRunner is still running and // no shutdown is issued to close the database. // // - setDaemon(false) may require flush in finalization // CB // tRunner.setDaemon(false); tRunner.start(); }
/** * Method declaration * * @throws SQLException */ void checkpoint(boolean defrag) throws SQLException { if (defrag) { ArrayList rootsArray = cCache.defrag(); for (int i = 0; i < rootsArray.size(); i++) { int[] roots = (int[]) rootsArray.get(i); if (roots != null) { Trace.printSystemOut(org.hsqldb.lib.StringUtil.getList(roots, " ", "")); } } DataFileDefrag2.updateTableIndexRoots(dDatabase.getTables(), rootsArray); } close(false); pProperties.setProperty("modified", "yes"); pProperties.save(); if (cCache != null) { cCache.open(false); } reopenAllTextCaches(); openScript(); }
// see DbFile.java for javadocs public ArrayList<Page> insertTuple(TransactionId tid, Tuple t) throws DbException, IOException, TransactionAbortedException { // some code goes here BufferPool bp = Database.getBufferPool(); int id = getId(), i, slots; ArrayList<Page> retlist = new ArrayList<Page>(); PageId pid = null; HeapPage p = null; for (i = 0; i < numPages(); i++) { pid = new HeapPageId(id, i); p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE); slots = p.getNumEmptySlots(); if (slots > 0) { p.insertTuple(t); retlist.add(p); return retlist; } } // create new page and add tuple to it pid = new HeapPageId(id, i); raf.setLength(raf.length() + BufferPool.PAGE_SIZE); p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE); p.insertTuple(t); retlist.add(p); return retlist; }
public static void main(String[] args) { CloudantClient client = new CloudantClient("http://username.cloudant.com", "username", "password"); Database db = client.database("java-searchindex", false); Map<String, Object> animals = new HashMap<>(); animals.put("index", "function(doc){ index(\"default\", doc._id); }"); Map<String, Object> indexes = new HashMap<>(); indexes.put("animals", animals); Map<String, Object> ddoc = new HashMap<>(); ddoc.put("_id", "_design/searchindex"); ddoc.put("indexes", indexes); db.save(ddoc); }
/** * @param db * @return a db transformed in a database of events ??? */ public Database preProcessing(Database db) { Vector<Element> alphabet = m_tdm.m_contentC.m_taxonomy.getAlphabet(m_tdm.m_contentC.m_level); Database preprocDB = new Database(); for (int i = 0; i < db.getSize(); i++) { EventSequence s = db.elementAt(i); Vector<Event> events = new Vector<Event>(0); for (int k = 0; k < s.length(); k++) { Event e = s.elementAtIndex(k); if (m_tdm.m_temporalC.accepts(e)) { Vector<Element> v = getParents(e.getSet(), alphabet, m_tdm.m_contentC.m_taxonomy); if (null != v) events.addElement(new Event(new ItemSet(v), e.getInstant())); } } if (0 != events.size()) preprocDB.addElement(new EventSequence(events)); } preprocDB.setAlphabet(alphabet); return preprocDB; }
@After public void tearDown() throws Exception { // Roll back transaction so changes to database are undone db.endTransaction(false); db = null; dbProjects = null; }
private Page readPage(int pageNumber) throws DbException, TransactionAbortedException, IOException { // File == table because we do one file per table // System.out.println("readpage:"+_file.id()+" page:"+pageNumber); int tableId = _file.id(); int pageId = pageNumber; // System.out.println("Page is now "+pageNumber); HeapPageId pid = new HeapPageId(tableId, pageId); return Database.getBufferPool().getPage(_transactionId, pid, Permissions.READ_ONLY); }
/** * Returns the TupleDesc with field names from the underlying HeapFile, prefixed with the * tableAlias string from the constructor. This prefix becomes useful when joining tables * containing a field(s) with the same name. * * @return the TupleDesc with field names from the underlying HeapFile, prefixed with the * tableAlias string from the constructor. */ public TupleDesc getTupleDesc() { TupleDesc tup = Database.getCatalog().getTupleDesc(id); int length = tup.numFields(); String[] field = new String[length]; Type[] types = new Type[length]; for (int i = 0; i < length; i++) { types[i] = tup.getFieldType(i); field[i] = alias + "." + tup.getFieldName(i); } return new TupleDesc(types, field); }
/* Method: removeSynonymFromEntry - basic user interface Purpose: word menu, interacts with user and calls database methods to remove synonyms real work is done in database Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void removeSynonymFromEntry(Database currentThesaurus) { System.out.println("\nPlease type the word you would like to update"); System.out.print(">>"); // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // WHat word does the user want to update? String word = inputScanner.nextLine(); // calls the method where the real work is done currentThesaurus.removeSynonymFromMenu(word); }
public void open() throws DbException, TransactionAbortedException { // some code goes here if (i_pos != null) { i = i_pos; } else { Catalog gc = Database.getCatalog(); HeapFile file = (HeapFile) gc.getDbFile(tableid); i = file.iterator(tid); } i.open(); }
/* Method: addNewSynonym - basic user interface Purpose: word menu, interacts with user and calls database methods to add new synonyms real work is done in database Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void addNewSynonymToEntry(Database currentThesaurus) { System.out.println("\nPlease type the word you would like to update"); System.out.print(">>"); // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // What word does the user want to update? String word = inputScanner.nextLine(); // calls the method where the real work is done currentThesaurus.addSynonymFromMenu(word); // written that way so code is usable by addNewEntry }
// see DbFile.java for javadocs public Page deleteTuple(TransactionId tid, Tuple t) throws DbException, TransactionAbortedException { // some code goes here BufferPool bp = Database.getBufferPool(); RecordId rid = t.getRecordId(); if (rid == null) { throw new DbException("Tuple is not a member of this file"); } HeapPage p = (HeapPage) bp.getPage(tid, rid.getPageId(), Permissions.READ_WRITE); p.deleteTuple(t); return p; }
/** * Create a new TableStats object, that keeps track of statistics on each column of a table * * @param tableid The table over which to compute statistics * @param ioCostPerPage The cost per page of IO. This doesn't differentiate between * sequential-scan IO and disk seeks. */ public TableStats(int tableid, int ioCostPerPage) { // For this function, we use the DbFile for the table in question, // then scan through its tuples and calculate the values that you // to build the histograms. // TODO: Fill out the rest of the constructor. // Feel free to change anything already written, it's only a guideline this.ioCostPerPage = ioCostPerPage; DbFile file = Database.getCatalog().getDbFile(tableid); tupleDesc = file.getTupleDesc(); numPages = ((HeapFile) file).numPages(); numTuples = 0; int numFields = tupleDesc.numFields(); // TODO: what goes here? statistics = new ArrayList<Object>(); for (int i = 0; i < numFields; i++) { if (Type.INT_TYPE.equals(tupleDesc.getFieldType(i))) { statistics.add(new IntStatistics(NUM_HIST_BINS)); } else { statistics.add(new StringHistogram(NUM_HIST_BINS)); } } final DbFileIterator iter = file.iterator(null); try { iter.open(); while (iter.hasNext()) { Tuple t = iter.next(); numTuples++; // TODO: and here? for (int i = 0; i < numFields; i++) { if (Type.INT_TYPE.equals(tupleDesc.getFieldType(i))) { ((IntStatistics) statistics.get(i)).addValue(((IntField) t.getField(i)).getValue()); } else { ((StringHistogram) statistics.get(i)) .addValue(((StringField) t.getField(i)).getValue()); } } } iter.close(); } catch (DbException e) { e.printStackTrace(); } catch (TransactionAbortedException e) { e.printStackTrace(); } }
private void jbInit() throws Exception { dbAlias = com.limosys.dbaccess.Connection.getAddress(dbAlias); dbAlias.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); dbAlias.setUseStatementCaching(false); pRowSelect.addColumn("ID", Variant.INT); colId.setColumnName("ID"); colId.setServerColumnName("ID"); colId.setTableName("T_6467063785"); colId.setRowId(true); colId.setDataType(Variant.INT); colId.setSqlType(4); colName.setColumnName("NAME"); colName.setServerColumnName("NAME"); colName.setTableName("T_6467063785"); colName.setDataType(Variant.STRING); colName.setPrecision(255); colName.setSqlType(12); colCompanyName.setColumnName("COMPANY_NAME"); colCompanyName.setServerColumnName("COMPANY_NAME"); colCompanyName.setTableName("T_6467063785"); colCompanyName.setDataType(Variant.STRING); colCompanyName.setPrecision(255); colCompanyName.setSqlType(12); prT_6467063785.setDatabase(dbAlias); // prT_6467063785.setInsertProcedure(new ProcedureDescriptor(dbAlias, "exec // lsp_T_6467063785_INotNull_v2 :ID, :NAME, :COMPANY_NAME", pdsT_6467063785, true, Load.ALL)); prT_6467063785.setDeleteProcedure( new ProcedureDescriptor( dbAlias, "exec lsp_T_6467063785_D_v2 :ID", pdsT_6467063785, true, Load.ALL)); pdsT_6467063785.setMetaDataUpdate(MetaDataUpdate.NONE); pdsT_6467063785.setResolver(prT_6467063785); pdsT_6467063785.setSchemaName(""); pdsT_6467063785.setProcedure( new ProcedureDescriptor( dbAlias, "exec lsp_T_6467063785_SRow_v2 :ID", pRowSelect, true, Load.ALL)); pdsT_6467063785.setColumns(new Column[] {colId, colName, colCompanyName}); }
public static void put(String id, String msg) { try { DBCollection message = Database.gardensharing().getCollection("message"); BasicDBObject document = new BasicDBObject(); document.put("id", id); document.put("msg", msg); message.insert(document); } catch (MongoException e) { e.printStackTrace(); } // messages.put(id, msg); }
/* Method: wordSearchMenu - user interface Purpose: word menu, interacts with user and calls database methods to search for user input, prints out search results Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void wordSearchMenu(Database currentThesaurus) { // basic menu for simple text input // should work for any normal circumstances System.out.println("\nPlease type the word to be searched for"); System.out.print(">> "); // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // the word being searched for String userInput = inputScanner.nextLine(); // searches the database for a word String returnString = currentThesaurus.searchForWord(userInput); // the results of the search System.out.println(returnString + "\n"); }
/* Method: synonymSearchMenu - user interface Purpose: word menu, interacts with user and calls database methods to search for user input, prints out search results Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void synonymSearchMenu(Database currentThesaurus) { // basic menu for simple text input // should work for any normal circumstances // because it stores user input into a string System.out.println("\nPlease type the synonym to be searched for"); System.out.print(">> "); // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // Synonym being searched for String userInput = inputScanner.nextLine(); // searches each entry for a matching synonym String returnString = currentThesaurus.searchForSynonym(userInput); // the results of the search System.out.println(returnString + "\n"); }
private void createAliasedTd() { Catalog gc = Database.getCatalog(); TupleDesc old_td = gc.getTupleDesc(tableid); String[] newFieldAr = new String[old_td.numFields()]; Type[] typeAr = new Type[old_td.numFields()]; String field = null; for (int i = 0; i < newFieldAr.length; i++) { field = old_td.getFieldName(i); if (alias == null) { alias = "null"; } else if (field == null) { field = "null"; } newFieldAr[i] = alias + "." + field; typeAr[i] = old_td.getFieldType(i); } td = new TupleDesc(typeAr, newFieldAr); }
/* Method: removeEntry - basic user interface Purpose: word menu, interacts with user and calls database methods to remove entries real work is done in database Parameters: Database currentThesaurus the database parsed from the text file Returns: none */ public static void removeEntry(Database currentThesaurus) { System.out.println("\nPlease type the word you would like to remove"); System.out.print(">>"); // Will accept spaces in words // Scanner to take user input Scanner inputScanner = new Scanner(System.in); // the wood the user wants to add String newUserWord = inputScanner.nextLine(); // checks whether the word was added successfully boolean successCheck = currentThesaurus.removeEntryFromMenu(newUserWord); if (successCheck) { System.out.println("\n" + newUserWord + " has been " + "removed from the thesaurus"); System.out.println("\nGoing back to the main menu"); } else { System.out.println("Going back to the main menu"); // returns to the main menu } }
/** * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set * of header bytes indicating the slots of the page that are in use, some number of tuple slots. * Specifically, the number of tuples is equal to: * * <p>floor((BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1)) * * <p>where tuple size is the size of tuples in this database table, which can be determined via * {@link Catalog#getTupleDesc}. The number of 8-bit header words is equal to: * * <p>ceiling(no. tuple slots / 8) * * <p> * * @see Database#getCatalog * @see Catalog#getTupleDesc * @see BufferPool#PAGE_SIZE */ public HeapPage(HeapPageId id, byte[] data) throws IOException { this.pid = id; this.td = Database.getCatalog().getTupleDesc(id.getTableId()); this.numSlots = getNumTuples(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); // allocate and read the header slots of this page header = new byte[getHeaderSize()]; for (int i = 0; i < header.length; i++) header[i] = dis.readByte(); try { // allocate and read the actual records of this page tuples = new Tuple[numSlots]; for (int i = 0; i < tuples.length; i++) tuples[i] = readNextTuple(dis, i); } catch (NoSuchElementException e) { e.printStackTrace(); } dis.close(); setBeforeImage(); }
public static String get(String id) { // Since 2.10.0, uses MongoClient try { DBCollection message = Database.gardensharing().getCollection("message"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", id); DBCursor cursor = message.find(searchQuery); if (cursor.hasNext()) { DBObject object = cursor.next(); return object.toString(); } else { return null; } } catch (MongoException e) { e.printStackTrace(); } return null; }
/** * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set * of 32-bit header words indicating the slots of the page that are in use, plus * (BufferPool.PAGE_SIZE/tuple size) tuple slots, where tuple size is the size of tuples in this * database table, which can be determined via {@link Catalog#getTupleDesc}. * * <p>The number of 32-bit header words is equal to: * * <p>(no. tuple slots / 32) + 1 * * <p> * * @see Database#getCatalog * @see Catalog#getTupleDesc * @see BufferPool#PAGE_SIZE */ public HeapPage(HeapPageId id, byte[] data) throws IOException { this.pid = id; this.td = Database.getCatalog().getTupleDesc(id.tableid()); // this.numSlots = (BufferPool.PAGE_SIZE) / (td.getSize()); this.numSlots = (BufferPool.PAGE_SIZE * 8) / ((td.getSize() * 8) + 1); // System.out.println(this.numSlots); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); // allocate and read the header slots of this page header = new Header(dis); try { // allocate and read the actual records of this page tuples = new Tuple[numSlots]; for (int i = 0; i < numSlots; i++) { tuples[i] = readNextTuple(dis, i); } } catch (NoSuchElementException e) { // e.printStackTrace(); } dis.close(); }
/** * Returns the TupleDesc with field names from the underlying HeapFile, prefixed with the * tableAlias string from the constructor. This prefix becomes useful when joining tables * containing a field(s) with the same name. * * @return the TupleDesc with field names from the underlying HeapFile, prefixed with the * tableAlias string from the constructor. */ public TupleDesc getTupleDesc() { // some code goes here TupleDesc td = Database.getCatalog().getTupleDesc(tableid); Iterator<TDItem> tdIter = td.iterator(); int size = td.numFields(); Type[] typeAr = new Type[size]; String[] fieldAr = new String[size]; String aliasString = this.tableAlias; TDItem item; Type fieldType; String fieldName; int count = 0; if (aliasString == null) { aliasString = "null"; } // for (int i = 0; i < size; i++){ // item = tdIter.next(); // fieldType = item.fieldType; // fieldName = item.fieldName; while (tdIter.hasNext()) { item = tdIter.next(); fieldType = item.fieldType; fieldName = item.fieldName; if (fieldName == null) { fieldName = "null"; } typeAr[count] = fieldType; fieldAr[count] = aliasString + "." + fieldName; // "null.null case may occur" count++; } return new TupleDesc(typeAr, fieldAr); }
/** * Method declaration * * @return */ private Channel init() { try { mSocket.setTcpNoDelay(true); mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream())); mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream())); String user = mInput.readUTF(); String password = mInput.readUTF(); Channel c; try { mServer.trace(mThread + ":trying to connect user " + user); return mDatabase.connect(user, password); } catch (SQLException e) { write(new Result(e.getMessage()).getBytes()); } } catch (Exception e) { } return null; }