Example #1
0
 @ManagedOperation
 public String printPreviousViews() {
   StringBuilder sb = new StringBuilder();
   for (Tuple<View, Long> tmp : prev_views)
     sb.append(new Date(tmp.getVal2())).append(": ").append(tmp.getVal1()).append("\n");
   return sb.toString();
 }
Example #2
0
  public void run() {
    try {
      Thread ct = Thread.currentThread();
      Thread.sleep(shift);

      while (monitor != null && monitor.equals(ct)) {
        long executiontime = System.currentTimeMillis();

        OnMemoryTupleSet ts = new OnMemoryTupleSet(schema);
        Tuple t = new Tuple(schema.size());
        t.setTimestamp(table[0], executiontime);
        t.setLong(0, executiontime);
        t.setString(1, command);
        t.setString(2, getCommandOutput());
        ts.appendTuple(t);
        ts.beforeFirst();

        deliverTupleSet(executiontime, table[0], ts);

        Thread.sleep(interval);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #3
0
  /** Suck up tuples from the source file. */
  private Tuple readNextTuple(DataInputStream dis, int slotId) throws NoSuchElementException {
    // if associated bit is not set, read forward to the next tuple, and
    // return null.
    if (!getSlot(slotId)) {
      for (int i = 0; i < td.getSize(); i++) {
        try {
          dis.readByte();
        } catch (IOException e) {
          throw new NoSuchElementException("error reading empty tuple");
        }
      }
      return null;
    }

    // read fields in the tuple
    Tuple t = new Tuple(td);
    RecordID rid = new RecordID(pid, slotId);
    t.setRecordID(rid);
    try {
      for (int j = 0; j < td.numFields(); j++) {
        Field f = td.getType(j).parse(dis);
        t.setField(j, f);
      }
    } catch (java.text.ParseException e) {
      // e.printStackTrace();
      throw new NoSuchElementException("parsing error!");
    }

    return t;
  }
Example #4
0
 public Tuple rdp(Tuple template) {
   for (int i = 0; i < ts.size(); i++) {
     Tuple tuple = (Tuple) ts.get(i);
     if (template.matches(tuple)) return tuple;
   }
   return null;
 }
  @Test
  public void new_fieldsTest() {
    int length = 10;
    String name = "td";
    Tuple t = new Tuple(Utility.getTupleDesc(length, name));

    Iterator<Field> fs = t.fields();

    int i = 0;
    while (fs.hasNext()) {
      i++;
      fs.next();
    }

    assertEquals(length, i);
  }
Example #6
0
 /**
  * Adds the specified tuple to the page; the tuple should be updated to reflect that it is now
  * stored on this page.
  *
  * @throws DbException if the page is full (no empty slots) or tupledesc is mismatch.
  * @param t The tuple to add.
  */
 public void insertTuple(Tuple t) throws DbException {
   // some code goes here
   // not necessary for lab1
   RecordId targetrid = t.getRecordId();
   if (getNumEmptySlots() == 0 || !td.equals(t.getTupleDesc())) {
     throw new DbException("Either page is full or tuple desc doesn't match");
   }
   for (int i = 0; i < getNumTuples(); i++) {
     if (!isSlotUsed(i)) {
       markSlotUsed(i, true);
       RecordId rid = new RecordId(pid, i);
       t.setRecordId(rid);
       tuples[i] = t;
       return;
     }
   }
 }
  /** Unit test for Tuple.getRecordId() and Tuple.setRecordId() */
  @Test
  public void modifyRecordId() {
    Tuple tup1 = new Tuple(Utility.getTupleDesc(1));
    HeapPageId pid1 = new HeapPageId(0, 0);
    RecordId rid1 = new RecordId(pid1, 0);
    tup1.setRecordId(rid1);

    try {
      assertEquals(rid1, tup1.getRecordId());
    } catch (java.lang.UnsupportedOperationException e) {
      // rethrow the exception with an explanation
      throw new UnsupportedOperationException(
          "modifyRecordId() test failed due to "
              + "RecordId.equals() not being implemented.  This is not required for Lab 1, "
              + "but should pass when you do implement the RecordId class.");
    }
  }
Example #8
0
 public Tuple getNext() throws NoSuchElementException, TransactionAbortedException {
   try {
     Tuple tuple = new Tuple(td);
     for (int i = 0; i < td.numFields(); i++) {
       IntField intf = IntField.createIntField(in.readInt());
       tuple.setField(i, intf);
     }
     return tuple;
   } catch (EOFException eof) {
     throw new NoSuchElementException(eof.getMessage());
   } catch (Exception e) {
     e.printStackTrace();
     BufferPool.Instance().abortTransaction(tid);
     closeConnection();
     throw new TransactionAbortedException(e);
   }
 }
Example #9
0
  void read_tuple(Tuple tuple, IndexDesc record) throws IOException, IndexCatalogException {
    try {
      record.relName = tuple.getStrFld(1);
      record.attrName = tuple.getStrFld(2);

      int temp;
      temp = tuple.getIntFld(3);
      if (temp == 0) record.accessType = new IndexType(IndexType.None);
      else if (temp == 1) record.accessType = new IndexType(IndexType.B_Index);
      else if (temp == 2) record.accessType = new IndexType(IndexType.Hash);
      else System.out.println("111Error in IndexCatalog::read_tuple");

      temp = tuple.getIntFld(4);
      if (temp == 0) record.order = new TupleOrder(TupleOrder.Ascending);
      else if (temp == 1) record.order = new TupleOrder(TupleOrder.Descending);
      else if (temp == 2) record.order = new TupleOrder(TupleOrder.Random);
      else System.out.println("222Error in IndexCatalog::read_tuple");

      record.clustered = tuple.getIntFld(5);
      record.distinctKeys = tuple.getIntFld(6);
      record.indexPages = tuple.getIntFld(7);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "read_tuple failed");
    }

    return;
  };
Example #10
0
 public Tuple[] rdgp(Tuple template) {
   Vector matchingTuples = new Vector();
   for (int i = 0; i < ts.size(); i++) {
     Tuple tuple = (Tuple) ts.get(i);
     if (template.matches(tuple)) matchingTuples.add(tuple);
   }
   if (matchingTuples.size() == 0) return null;
   return (Tuple[]) matchingTuples.toArray(new Tuple[0]);
 }
Example #11
0
  /**
   * constructor
   *
   * @param file_name heapfile to be opened
   * @param in1[] array showing what the attributes of the input fields are.
   * @param s1_sizes[] shows the length of the string fields.
   * @param len_in1 number of attributes in the input tuple
   * @param n_out_flds number of fields in the out tuple
   * @param proj_list shows what input fields go where in the output tuple
   * @param outFilter select expressions
   * @exception IOException some I/O fault
   * @exception FileScanException exception from this class
   * @exception TupleUtilsException exception from this class
   * @exception InvalidRelation invalid relation
   */
  public FileScan(
      String file_name,
      AttrType in1[],
      short s1_sizes[],
      short len_in1,
      int n_out_flds,
      FldSpec[] proj_list,
      CondExpr[] outFilter)
      throws IOException, FileScanException, TupleUtilsException, InvalidRelation {
    _in1 = in1;
    in1_len = len_in1;
    s_sizes = s1_sizes;

    Jtuple = new Tuple();
    AttrType[] Jtypes = new AttrType[n_out_flds];
    short[] ts_size;
    ts_size =
        TupleUtils.setup_op_tuple(Jtuple, Jtypes, in1, len_in1, s1_sizes, proj_list, n_out_flds);

    OutputFilter = outFilter;
    perm_mat = proj_list;
    nOutFlds = n_out_flds;
    tuple1 = new Tuple();

    try {
      tuple1.setHdr(in1_len, _in1, s1_sizes);
    } catch (Exception e) {
      throw new FileScanException(e, "setHdr() failed");
    }
    t1_size = tuple1.size();

    try {
      f = new Heapfile(file_name);

    } catch (Exception e) {
      throw new FileScanException(e, "Create new heapfile failed");
    }

    try {
      scan = f.openScan();
    } catch (Exception e) {
      throw new FileScanException(e, "openScan() failed");
    }
  }
Example #12
0
 /**
  * Delete the specified tuple from the page; the tuple should be updated to reflect that it is no
  * longer stored on any page.
  *
  * @throws DbException if this tuple is not on this page, or tuple slot is already empty.
  * @param t The tuple to delete
  */
 public void deleteTuple(Tuple t) throws DbException {
   // some code goes here
   // not necessary for lab1
   RecordId targetrid = t.getRecordId();
   int tslotnum = targetrid.tupleno();
   if (!targetrid.getPageId().equals(pid) || !isSlotUsed(tslotnum)) {
     throw new DbException("Either wrong page number or requested tuple didn't exist");
   }
   markSlotUsed(tslotnum, false);
   tuples[tslotnum] = null;
 }
  /** Unit test for Tuple.getField() and Tuple.setField() */
  @Test
  public void modifyFields() {
    TupleDesc td = Utility.getTupleDesc(2);

    Tuple tup = new Tuple(td);
    tup.setField(0, new IntField(-1));
    tup.setField(1, new IntField(0));

    assertEquals(new IntField(-1), tup.getField(0));
    assertEquals(new IntField(0), tup.getField(1));

    tup.setField(0, new IntField(1));
    tup.setField(1, new IntField(37));

    assertEquals(new IntField(1), tup.getField(0));
    assertEquals(new IntField(37), tup.getField(1));
  }
  @Test
  public void new_toStringTest() {
    int length = 10;
    String name = "td";
    Tuple t = new Tuple(Utility.getTupleDesc(length, name));
    for (int i = 0; i < length; i++) {
      t.setField(i, new TestField());
    }

    String tString = t.toString();

    // Last character should be \n.
    assertEquals("\n", tString.substring(tString.length() - 1));

    // Only last character is \n.
    assertFalse(tString.substring(0, tString.length() - 1).contains("\n"));

    // Split string on any white character.
    String[] tStringAr = tString.substring(0, tString.length() - 1).split("\\s+");
    assertEquals(length, tStringAr.length);
  }
Example #15
0
 public Tuple inp(Tuple template) {
   for (int i = 0; i < ts.size(); i++) {
     Tuple tuple = (Tuple) ts.get(i);
     log("INP: Comparing:\n" + template + "\nwith:\n" + tuple);
     if (template.matches(tuple)) {
       log("INP: Match!");
       ts.remove(i);
       return tuple;
     }
   }
   return null;
 }
Example #16
0
 // 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;
 }
Example #17
0
 public void add_interest() {
   if ((transaction_counter % 5) == 0) {
     for (Customer c : cust) {
       ArrayList<Tuple> accountsAddedTo = new ArrayList<>(100);
       accountsAddedTo = c.addInterestToSavings(interest_rate);
       timestamp = date.getTime();
       if (!accountsAddedTo.isEmpty()) {
         String customerID = c.returnID();
         for (Tuple tuple : accountsAddedTo) {
           String accountNumber = tuple.getFirst();
           double logAmount = tuple.getSecond();
           AdminLog newTransaction =
               new AdminLog(timestamp, transaction_counter, customerID, accountNumber, logAmount);
           adminLogs.add(newTransaction);
         }
       }
       try {
         saveFile(cust, DBfile);
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Example #18
0
  /**
   * @return the result tuple
   * @exception JoinsException some join exception
   * @exception IOException I/O errors
   * @exception InvalidTupleSizeException invalid tuple size
   * @exception InvalidTypeException tuple type not valid
   * @exception PageNotReadException exception from lower layer
   * @exception PredEvalException exception from PredEval class
   * @exception UnknowAttrType attribute type unknown
   * @exception FieldNumberOutOfBoundException array out of bounds
   * @exception WrongPermat exception for wrong FldSpec argument
   */
  public Tuple get_next()
      throws JoinsException, IOException, InvalidTupleSizeException, InvalidTypeException,
          PageNotReadException, PredEvalException, UnknowAttrType, FieldNumberOutOfBoundException,
          WrongPermat {
    RID rid = new RID();
    ;

    while (true) {
      if ((tuple1 = scan.getNext(rid)) == null) {
        return null;
      }

      tuple1.setHdr(in1_len, _in1, s_sizes);
      if (PredEval.Eval(OutputFilter, tuple1, null, _in1, null) == true) {
        Projection.Project(tuple1, _in1, Jtuple, perm_mat, nOutFlds);
        return Jtuple;
      }
    }
  }
Example #19
0
  void make_tuple(Tuple tuple, IndexDesc record) throws IOException, IndexCatalogException {
    try {
      tuple.setStrFld(1, record.relName);
      tuple.setStrFld(2, record.attrName);

      if (record.accessType.indexType == IndexType.None) tuple.setIntFld(3, 0);
      else if (record.accessType.indexType == IndexType.B_Index) tuple.setIntFld(3, 1);
      else if (record.accessType.indexType == IndexType.Hash) tuple.setIntFld(3, 2);
      else System.out.println("Invalid accessType in IndexCatalog::make_tupl");

      if (record.order.tupleOrder == TupleOrder.Ascending) tuple.setIntFld(4, 0);
      else if (record.order.tupleOrder == TupleOrder.Descending) tuple.setIntFld(4, 1);
      else if (record.order.tupleOrder == TupleOrder.Random) tuple.setIntFld(4, 2);
      else System.out.println("Invalid order in IndexCatalog::make_tuple");

      tuple.setIntFld(5, record.clustered);
      tuple.setIntFld(6, record.distinctKeys);
      tuple.setIntFld(7, record.indexPages);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "make_tuple failed");
    }

    return;
  };
Example #20
0
  // ADD INDEX TO A RELATION
  public void addIndex(String relation, String attrName, IndexType accessType, int buckets)
      throws IOException, Catalogioerror, Cataloghferror, Catalogmissparam, Catalogattrnotfound,
          Catalogbadtype, Catalognomem, Catalogindexnotfound, IndexCatalogException,
          java.lang.Exception {
    RID rid = null;
    IndexDesc indexRec = null;
    AttrDesc attrRec = null;
    int intKey = 0;
    float floatKey = (float) 0.0;
    String charKey = null;
    int attrCnt = 0;
    KeyClass key = null;
    int recSize = 0;

    Heapfile datafile = null;
    String indexName = null;
    Tuple tuple = null;
    BTreeFile btree = null;
    Scan pscan = null;
    AttrType[] typeArray = null;
    short[] sizeArray = null;

    // CHECK PARM

    if ((relation == null) || (attrName == null)) throw new Catalogmissparam(null, "MISSING_PARAM");

    // CHECK FOR EXISTING INDEX

    try {
      getInfo(relation, attrName, accessType, indexRec);
    } catch (Catalogioerror e) {
      System.err.println("Catalog I/O Error!" + e);
      throw new Catalogioerror(null, "");
    } catch (Cataloghferror e1) {
      System.err.println("Catalog Heapfile Error!" + e1);
      throw new Cataloghferror(null, "");
    } catch (Catalogmissparam e2) {
      System.err.println("Catalog Missing Param Error!" + e2);
      throw new Catalogmissparam(null, "");
    }

    // GET ATTRIBUTE INFO

    try {
      ExtendedSystemDefs.MINIBASE_ATTRCAT.getInfo(relation, attrName, attrRec);
    } catch (Exception e2) {
      throw new IndexCatalogException(e2, "getInfo() failed");
    }

    // Can only index on int's and strings currently
    if ((attrRec.attrType.attrType != AttrType.attrInteger)
        && (attrRec.attrType.attrType != AttrType.attrString))
      throw new Catalogbadtype(null, "Catalog: BAD TYPE!");

    // UPDATE ATTRIBUTE INFO

    attrRec.indexCnt++;

    try {
      ExtendedSystemDefs.MINIBASE_ATTRCAT.removeInfo(relation, attrName);
      ExtendedSystemDefs.MINIBASE_ATTRCAT.addInfo(attrRec);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "add/remove info failed");
    }

    // BUILD INDEX FILE NAME

    indexName = buildIndexName(relation, attrName, accessType);

    // ADDED BY BILL KIMMEL - DELETE LATER
    System.out.println("Index name is " + indexName);

    // IF BTREE

    if (accessType.indexType == IndexType.B_Index) {
      btree = new BTreeFile(indexName, attrRec.attrType.attrType, attrRec.attrLen, 0);
    }

    // ADD ENTRY IN INDEXCAT

    indexRec.relName = new String(relation);
    indexRec.attrName = new String(attrName);
    indexRec.accessType = accessType;

    if (accessType.indexType == IndexType.B_Index)
      indexRec.order = new TupleOrder(TupleOrder.Ascending);
    else indexRec.order = new TupleOrder(TupleOrder.Random);

    indexRec.distinctKeys = DISTINCTKEYS;
    indexRec.clustered = 0; // 0 means non-clustered!!!!

    indexRec.indexPages = INDEXPAGES;

    try {
      addInfo(indexRec);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "addInfo() failed");
    }

    // PREPARE TO SCAN DATA FILE

    try {
      datafile = new Heapfile(relation);
      if (datafile == null) throw new Catalognomem(null, "NO Enough Memory!");
    } catch (Exception e) {
      throw new IndexCatalogException(e, "create heapfile failed");
    }

    try {
      pscan = datafile.openScan();
    } catch (Exception e) {
      throw new IndexCatalogException(e, "openScan() failed");
    }

    // PREPARE TUPLE

    try {
      ExtendedSystemDefs.MINIBASE_ATTRCAT.getTupleStructure(
          relation, attrCnt, typeArray, sizeArray);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "getTupleStructure");
    }

    tuple = new Tuple(Tuple.max_size);
    if (tuple == null) throw new Catalognomem(null, "Catalog, No Enough Memory!");

    try {
      tuple.setHdr((short) attrCnt, typeArray, sizeArray);
    } catch (Exception e) {
      throw new IndexCatalogException(e, "setHdr() failed");
    }

    recSize = tuple.size();

    // NOW PROCESS THE HEAPFILE AND INSERT KEY,RID INTO INDEX

    while (true) {
      try {
        tuple = pscan.getNext(rid);
        if (tuple == null) return;
      } catch (Exception e) {
        throw new IndexCatalogException(e, "getNext() failed");
      }

      // PULL OUT THE KEY VALUE FROM HEAPFILE RECORD

      if (attrRec.attrType.attrType == AttrType.attrInteger) {
        intKey = tuple.getIntFld(attrRec.attrPos);
        key = new IntegerKey(intKey);
      } else if (attrRec.attrType.attrType == AttrType.attrReal) {
        floatKey = tuple.getFloFld(attrRec.attrPos);
        key = new IntegerKey((int) floatKey);
      } else if (attrRec.attrType.attrType == AttrType.attrString) {
        charKey = new String(tuple.getStrFld(attrRec.attrPos));
        key = new StringKey(charKey);
      }

      // NOW INSERT RECORD INTO INDEX

      if (accessType.indexType == IndexType.B_Index) {
        try {
          btree.insert(key, rid);
        } catch (Exception e) {
          throw new IndexCatalogException(e, "insert failed");
        }
      }
    }
  };
 /** Unit test for Tuple.getTupleDesc() */
 @Test
 public void getTupleDesc() {
   TupleDesc td = Utility.getTupleDesc(5);
   Tuple tup = new Tuple(td);
   assertEquals(td, tup.getTupleDesc());
 }