コード例 #1
0
ファイル: STSTest2.java プロジェクト: anirudhgali/Minibase
  /** Constructor */
  public STSDriver2() {
    System.out.print("Started STS tests2" + "\n");

    // build ColaMarkets table
    colamarkets = new Vector();

    double[] v = new double[] {1.0, 1.0, 2.0, 3.0};

    colamarkets.addElement(new ColaMarkets(1, "cola_a", new Sdo_geometry(Sdo_gtype.RECTANGLE, v)));

    v = new double[] {2.5, 3.5, 3.5, 4.5};

    colamarkets.addElement(new ColaMarkets(2, "cola_b", new Sdo_geometry(Sdo_gtype.RECTANGLE, v)));

    boolean status = OK;
    int numMarkets = 2;
    int numMarkets_attrs = 3;

    String dbpath = "/tmp/" + System.getProperty("user.name") + ".minibase.ststest2db";
    String logpath = "/tmp/" + System.getProperty("user.name") + ".sts2log";

    String remove_cmd = "/bin/rm -rf ";
    String remove_logcmd = remove_cmd + logpath;
    String remove_dbcmd = remove_cmd + dbpath;
    String remove_sts2cmd = remove_cmd + dbpath;

    try {
      Runtime.getRuntime().exec(remove_logcmd);
      Runtime.getRuntime().exec(remove_dbcmd);
      Runtime.getRuntime().exec(remove_sts2cmd);
    } catch (IOException e) {
      System.err.println("" + e);
    }

    /*
    ExtendedSystemDefs extSysDef =
      new ExtendedSystemDefs( "/tmp/minibase.jointestdb", "/tmp/joinlog",
         1000,500,200,"Clock");
    */

    SystemDefs sysdef = new SystemDefs(dbpath, 1000, NUMBUF, "Clock");

    // creating the sailors relation
    AttrType[] Mtypes = new AttrType[3];
    Mtypes[0] = new AttrType(AttrType.attrInteger);
    Mtypes[1] = new AttrType(AttrType.attrString);
    Mtypes[2] = new AttrType(AttrType.attrSdogeometry);

    // SOS
    short[] Msizes = new short[1];
    Msizes[0] = 30; // first elt. is 30

    Tuple t = new Tuple();
    try {
      t.setHdr((short) 3, Mtypes, Msizes);
    } catch (Exception e) {
      System.err.println("*** error in Tuple.setHdr() ***");
      status = FAIL;
      e.printStackTrace();
    }

    int size = t.size();
    System.out.println("Size:" + size);

    // selecting the tuple into file "colamarkets"
    RID rid;
    Heapfile f = null;
    try {
      f = new Heapfile("colamarkets.in");
    } catch (Exception e) {
      System.err.println("*** error in Heapfile constructor ***");
      status = FAIL;
      e.printStackTrace();
    }

    t = new Tuple(size);
    try {
      t.setHdr((short) 3, Mtypes, Msizes);
    } catch (Exception e) {
      System.err.println("*** error in Tuple.setHdr() ***");
      status = FAIL;
      e.printStackTrace();
    }

    for (int i = 0; i < numMarkets; i++) {
      try {
        t.setIntFld(1, ((ColaMarkets) colamarkets.elementAt(i)).marketId);
        t.setStrFld(2, ((ColaMarkets) colamarkets.elementAt(i)).name);
        t.setSdogeometryFld(3, ((ColaMarkets) colamarkets.elementAt(i)).shape);
      } catch (Exception e) {
        System.err.println("*** Heapfile error in Tuple.setStrFld() ***");
        status = FAIL;
        e.printStackTrace();
      }

      try {
        rid = f.insertRecord(t.returnTupleByteArray());
      } catch (Exception e) {
        System.err.println("*** error in Heapfile.selectRecord() ***");
        status = FAIL;
        e.printStackTrace();
      }
    }

    if (status != OK) {
      // bail out
      System.err.println("*** Error creation relation for colamarkets");
      Runtime.getRuntime().exit(1);
    }
  }
コード例 #2
0
ファイル: OSMRouting.java プロジェクト: usunyu/ClearPath
  /**
   * routing using A* algorithm with fibonacci heap basically same as routingAStar function
   *
   * @param startNode
   * @param endNode
   * @param startTime
   * @param pathNodeList return path
   * @return
   */
  public static double routingAStarFibonacci(
      long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) {
    System.out.println("start finding the path...");
    int debug = 0;
    double totalCost = -1;
    try {
      // test store transversal nodes
      // HashSet<Long> transversalSet = new HashSet<Long>();

      if (!OSMData.nodeHashMap.containsKey(startNode)
          || !OSMData.nodeHashMap.containsKey(endNode)) {
        System.err.println("cannot find start or end node!");
        return -1;
      }

      if (startNode == endNode) {
        System.out.println("start node is the same as end node.");
        return 0;
      }

      HashSet<Long> closedSet = new HashSet<Long>();
      HashMap<Long, FibonacciHeapNode<NodeInfoHelper>> nodeHelperCache =
          new HashMap<Long, FibonacciHeapNode<NodeInfoHelper>>();

      FibonacciHeap<NodeInfoHelper> openSet = initialStartSet(startNode, endNode, nodeHelperCache);
      HashSet<Long> endSet = initialEndSet(endNode);
      NodeInfoHelper current = null;
      FibonacciHeapNode<NodeInfoHelper> fCurrent = null;

      while (!openSet.isEmpty()) {
        // remove current from openset
        fCurrent = openSet.min();
        openSet.removeMin();
        current = fCurrent.getData();

        // if(!transversalSet.contains(current.getNodeId()))
        //	transversalSet.add(current.getNodeId());

        long nodeId = current.getNodeId();
        // add current to closedset
        closedSet.add(nodeId);
        if (endSet.contains(nodeId)) { // find the destination
          current = current.getEndNodeHelper(endNode);
          totalCost = current.getCost();
          break;
        }
        // for time dependent routing
        int timeIndex =
            startTime
                + (int)
                    (current.getCost() / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL);
        if (timeIndex
            > OSMRouteParam.TIME_RANGE
                - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights
        timeIndex = OSMRouteParam.TIME_RANGE - 1;
        LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId);
        if (adjNodeList == null) continue; // this node cannot go anywhere
        double arriveTime = current.getCost();
        // for each neighbor in neighbor_nodes(current)
        for (ToNodeInfo toNode : adjNodeList) {
          debug++;
          long toNodeId = toNode.getNodeId();
          int travelTime;
          if (toNode.isFix()) // fix time
          travelTime = toNode.getTravelTime();
          else // fetch from time array
          travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex);
          // tentative_g_score := g_score[current] + dist_between(current,neighbor)
          double costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND;
          // tentative_f_score := tentative_g_score + heuristic_cost_estimate(neighbor, goal)
          double heuristicTime = estimateHeuristic(toNodeId, endNode);
          double totalCostTime = costTime + heuristicTime;
          // if neighbor in closedset and tentative_f_score >= f_score[neighbor]
          if (closedSet.contains(toNodeId)
              && nodeHelperCache.get(toNodeId).getData().getTotalCost() <= totalCostTime) {
            continue;
          }
          NodeInfoHelper node = null;
          FibonacciHeapNode<NodeInfoHelper> fNode = null;
          // if neighbor not in openset or tentative_f_score < f_score[neighbor]
          if (!nodeHelperCache.containsKey(toNodeId)) { // neighbor not in openset
            // create new one
            node = new NodeInfoHelper(toNodeId);
            node.setCost(costTime);
            node.setHeuristic(heuristicTime);
            node.setParentId(nodeId);
            fNode = new FibonacciHeapNode<NodeInfoHelper>(node);
            openSet.insert(fNode, node.getTotalCost());
            nodeHelperCache.put(node.getNodeId(), fNode);
          } else if (nodeHelperCache.get(toNodeId).getData().getTotalCost()
              > totalCostTime) { // neighbor in openset
            fNode = nodeHelperCache.get(toNodeId);
            node = fNode.getData();
            // update information
            node.setCost(costTime);
            node.setHeuristic(heuristicTime);
            node.setParentId(nodeId);
            if (closedSet.contains(toNodeId)) { // neighbor in closeset
              closedSet.remove(toNodeId); // remove neighbor form colseset
              openSet.insert(fNode, node.getTotalCost());
            } else { // neighbor in openset, decreaseKey
              openSet.decreaseKey(fNode, node.getTotalCost());
            }
          }
        }
      }
      if (totalCost != -1) {
        long traceNodeId = current.getNodeId();
        pathNodeList.add(traceNodeId); // add end node
        traceNodeId = current.getParentId();
        while (traceNodeId != 0) {
          pathNodeList.add(traceNodeId); // add node
          fCurrent = nodeHelperCache.get(traceNodeId);
          current = fCurrent.getData();
          traceNodeId = current.getParentId();
        }
        Collections.reverse(pathNodeList); // reverse the path list
        System.out.println("find the path successful!");
      } else {
        System.out.println("can not find the path!");
      }
      // OSMOutput.generateTransversalNodeKML(transversalSet, nodeHashMap);
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println(
          "tdsp: debug code " + debug + ", start node " + startNode + ", end node " + endNode);
    }
    return totalCost;
  }
コード例 #3
0
ファイル: STSTest2.java プロジェクト: anirudhgali/Minibase
  public void Query1() {

    System.out.print("**********************Query1 strating *********************\n");
    boolean status = OK;

    System.out.print(
        "Query: Find the intersection of cola market cola_a and cola market cola_b"
            + "SELECT c.name, SDO_GEOM.SDO_AREA(c.shape, 0.005)"
            + " FROM cola_markets c_a, cola_markets c_b"
            + " WHERE c_a.name = 'cola_a' and c_b.name = 'cola_b'\n");

    System.out.print("\n(Tests2 FileScan, Projection)\n");

    CondExpr[] outFilter = new CondExpr[3];
    outFilter[0] = new CondExpr();
    outFilter[1] = new CondExpr();
    outFilter[2] = new CondExpr();

    Query1_CondExpr(outFilter);

    Tuple t = new Tuple();
    t = null;

    AttrType[] Mtypes = new AttrType[3];
    Mtypes[0] = new AttrType(AttrType.attrInteger);
    Mtypes[1] = new AttrType(AttrType.attrString);
    Mtypes[2] = new AttrType(AttrType.attrSdogeometry);

    // SOS
    short[] Msizes = new short[1];
    Msizes[0] = 30; // first elt. is 30

    FldSpec[] Mprojection = new FldSpec[2];
    Mprojection[0] = new FldSpec(new RelSpec(RelSpec.outer), 2);
    Mprojection[1] = new FldSpec(new RelSpec(RelSpec.outer), 3);

    AttrType[] jtype = new AttrType[2];
    jtype[0] = new AttrType(AttrType.attrString);
    jtype[1] = new AttrType(AttrType.attrSdogeometry);

    CondExpr[] selects = new CondExpr[1];
    selects = null;

    FileScan am = null;
    try {
      am = new FileScan("colamarkets.in", Mtypes, Msizes, (short) 3, (short) 2, Mprojection, null);
    } catch (Exception e) {
      status = FAIL;
      System.err.println("" + e);
      e.printStackTrace();
    }

    if (status != OK) {
      // bail out
      System.err.println("*** Error setting up scan for sailors");
      Runtime.getRuntime().exit(1);
    }
    System.out.println("done");
    Sdo_geometry x[] = new Sdo_geometry[2];

    try {
      int i = 0;
      while ((t = am.get_next()) != null) {
        t.print(jtype);
        x[i++] = t.getSdogeometryFld(2);
      }

      Sdo_geometry sdoval = x[0].intersection(x[1]);
      if (sdoval != null) {
        String output = "SDO_GEOMETRY(" + (int) sdoval.shapeType.ordinal() + ",[ ";
        for (double d : sdoval.coordinatesOfShape) output += d + " ";
        System.out.print(output + "])");
      }

    } catch (Exception e) {
      System.err.println("" + e);
      e.printStackTrace();
      Runtime.getRuntime().exit(1);
    }
  }
コード例 #4
0
ファイル: OSMRouting.java プロジェクト: usunyu/ClearPath
  // TODO : if start or end is already in the highway, will occur the problem, need to fix
  public static double routingHierarchy(
      long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) {
    // System.out.println("start finding the path...");
    int debug = 0;
    try {
      if (!OSMData.nodeHashMap.containsKey(startNode)
          || !OSMData.nodeHashMap.containsKey(endNode)) {
        System.err.println("cannot find start or end node!");
        return -1;
      }

      if (startNode == endNode) {
        System.out.println("start node is the same as end node.");
        return 0;
      }

      NodeInfo start = OSMData.nodeHashMap.get(startNode);
      NodeInfo end = OSMData.nodeHashMap.get(endNode);
      double minDistance = Geometry.calculateDistance(start.getLocation(), end.getLocation());
      if (minDistance < 5) { // use normal A* algorithm to calculate small distance
        return routingAStar(
            start.getNodeId(),
            end.getNodeId(),
            OSMRouteParam.START_TIME,
            OSMRouteParam.DAY_INDEX,
            pathNodeList);
      }

      SearchingSharing sharingData = new SearchingSharing();
      HashMap<Long, NodeInfoHelper> nodeForwardCache = new HashMap<Long, NodeInfoHelper>();
      HashMap<Long, NodeInfoHelper> nodeReverseCache = new HashMap<Long, NodeInfoHelper>();
      ForwardSearching forwardSearching =
          new ForwardSearching(
              startNode, endNode, startTime, dayIndex, sharingData, nodeForwardCache);
      ReverseSearching reverseSearching =
          new ReverseSearching(endNode, startNode, sharingData, nodeReverseCache);
      // two thread run simultaneously
      Thread forwardThread = new Thread(forwardSearching);
      Thread reverseThread = new Thread(reverseSearching);
      // search forward
      forwardThread.start();
      // let forward searching for a while
      // Thread.sleep(100);
      // search reverse
      reverseThread.start();
      // waiting for thread finish
      forwardThread.join();
      reverseThread.join();
      // get the searching intersects
      ArrayList<Long> intersectList = sharingData.getIntersectList();
      // pick the least cost one according to time-dependent
      double minCost = Double.MAX_VALUE;
      ArrayList<Long> minCostPath = new ArrayList<Long>();
      for (long intersect : intersectList) {
        NodeInfoHelper current = nodeForwardCache.get(intersect);
        // cost from source to intersect
        double cost = current.getCost();
        current = nodeReverseCache.get(intersect);
        // update the reverse cost as forward cost
        current.setCost(cost);
        ArrayList<Long> reversePath = new ArrayList<Long>();
        double totalCost = Double.MAX_VALUE;
        // recalculate from intersect to destination
        while (true) {
          long nodeId = current.getNodeId();
          int timeIndex =
              startTime
                  + (int)
                      (current.getCost()
                          / OSMParam.SECOND_PER_MINUTE
                          / OSMRouteParam.TIME_INTERVAL);
          if (timeIndex
              > OSMRouteParam.TIME_RANGE
                  - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights
          timeIndex = OSMRouteParam.TIME_RANGE - 1;
          long nextNodeId = current.getParentId();
          double arriveTime = current.getCost();
          // arrive end
          if (nextNodeId == 0) {
            totalCost = arriveTime;
            break;
          }
          // add node
          reversePath.add(nextNodeId);
          // calculate cost according adjlist
          LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId);
          double costTime = 0;
          for (ToNodeInfo toNode : adjNodeList) {
            if (toNode.getNodeId() == nextNodeId) {
              int travelTime;
              // forward searching is time dependent
              if (toNode.isFix()) // fix time
              travelTime = toNode.getTravelTime();
              else // fetch from time array
              travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex);
              costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND;
              break;
            }
          }
          current = nodeReverseCache.get(nextNodeId);
          if (costTime == 0) System.err.println("cost time cannot be zero!");
          else current.setCost(costTime);
        }

        // process the left nodes to real destination
        long lastNode = reversePath.get(reversePath.size() - 1);
        if (lastNode != endNode) {
          NodeInfo last = OSMData.nodeHashMap.get(lastNode);
          NodeInfo dest = OSMData.nodeHashMap.get(endNode);
          EdgeInfo onEdge = last.getEdgeFromNodes(dest);
          current = nodeReverseCache.get(lastNode);
          int totalDistance = onEdge.getDistance();
          int distance;
          long toNodeId;
          if (onEdge.getStartNode() == lastNode) { // from start to middle
            distance = onEdge.getStartDistance(endNode);
            toNodeId = onEdge.getEndNode();
          } else { // from end to middle
            distance = onEdge.getEndDistance(endNode);
            toNodeId = onEdge.getStartNode();
          }
          LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(lastNode);
          double costTime = 0;
          int timeIndex =
              startTime
                  + (int) (totalCost / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL);
          if (timeIndex
              > OSMRouteParam.TIME_RANGE
                  - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights
          timeIndex = OSMRouteParam.TIME_RANGE - 1;
          for (ToNodeInfo toNode : adjNodeList) {
            if (toNode.getNodeId() == toNodeId) {
              int travelTime;
              // forward searching is time dependent
              if (toNode.isFix()) // fix time
              travelTime = toNode.getTravelTime();
              else // fetch from time array
              travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex);
              costTime = (double) travelTime / OSMParam.MILLI_PER_SECOND;
              break;
            }
          }
          if (costTime != 0) {
            costTime *= (double) distance / totalDistance;
          }
          totalCost += costTime; // add cost
          reversePath.add(endNode); // add dest
        }

        // if found less cost path, build forward path
        if (totalCost < minCost) {
          ArrayList<Long> forwardPath = new ArrayList<Long>();
          minCost = totalCost;
          current = nodeForwardCache.get(intersect);
          long traceNodeId = current.getParentId();
          while (traceNodeId != 0) {
            forwardPath.add(traceNodeId); // add node
            current = nodeForwardCache.get(traceNodeId);
            traceNodeId = current.getParentId();
          }
          Collections.reverse(forwardPath); // reverse the path list
          // record min-cost path, combine forward path and reverse path
          minCostPath = new ArrayList<Long>();
          minCostPath.addAll(forwardPath);
          minCostPath.add(intersect);
          minCostPath.addAll(reversePath);
          // output kml
          // OSMOutput.generatePathKML(nodeHashMap, pathNodeList, "path_" + intersect);
          // ArrayList<Long> intersectNode = new ArrayList<Long>();
          // intersectNode.add(intersect);
          // OSMOutput.generatePathNodeKML(nodeHashMap, intersectNode, "intersect_" + intersect);
        }
      }
      pathNodeList.addAll(minCostPath);
      return minCost;
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("routingHierarchy: debug code " + debug);
    }
    return 0;
  }
コード例 #5
0
ファイル: BMTest.java プロジェクト: umairsajid/Projects-1
  /**
   * overrides the test4 function in TestDriver
   *
   * @return whether test4 has passed
   */
  protected boolean test4() {
    System.out.print("\n  Test 4 exercises some of the internals " + "of the buffer manager\n");

    int index;
    int numPages = NUMBUF + 10;
    Page pg = new Page();
    PageId pid = new PageId();
    PageId[] pids = new PageId[numPages];
    boolean status = OK;

    System.out.print("  - Allocate bunch of pages together \n");

    for (int i = 0; i < numPages / NUMBUF; i++) {
      for (index = i * NUMBUF; status == OK && index < (i + 1) * NUMBUF; ++index) {
        pg = new Page();
        try {
          pid = SystemDefs.JavabaseBM.newPage(pg, 1);
        } catch (Exception e) {
          status = FAIL;
          System.err.print("*** Could not allocate new page number " + index + 1 + "\n");
          e.printStackTrace();
        }

        if (status == OK) {
          pids[index] = pid;
        }

        if (status == OK) {

          // Copy the page number + 99999 onto each page.  It seems
          // unlikely that this bit pattern would show up there by
          // coincidence.
          int data = pid.pid + 99999;

          try {
            Convert.setIntValue(data, 0, pg.getpage());
          } catch (IOException e) {
            System.err.print("*** Convert value failed\n");
            status = FAIL;
            e.printStackTrace();
          }
        }
      }
      for (index = i * NUMBUF; status == OK && index < (i + 1) * NUMBUF; ++index) {
        try {
          SystemDefs.JavabaseBM.unpinPage(pids[index], true);
        } catch (Exception e) {
          status = FAIL;
          System.err.print("*** Could not unpin page " + pids[index].pid + "\n");
          e.printStackTrace();
        }
      }
    }

    if (status == OK) {
      System.out.print("  - Read the pages\n");

      for (int i = 0; i < numPages / NUMBUF; i++) {
        for (index = i * NUMBUF; status == OK && index < (i + 1) * NUMBUF; ++index) {
          pg = new Page();
          pid = pids[index];
          try {
            SystemDefs.JavabaseBM.pinPage(pid, pg, false);
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not pin page " + pid.pid + "\n");
            e.printStackTrace();
          }

          if (status == OK) {

            int data = 0;

            try {
              data = Convert.getIntValue(0, pg.getpage());
            } catch (IOException e) {
              System.err.print("*** Convert value failed \n");
              status = FAIL;
            }

            if (data != pid.pid + 99999) {
              status = FAIL;
              System.err.print("*** Read wrong data back from page " + pid.pid + "\n");
            }
          }
        }
        for (index = i * NUMBUF; status == OK && index < (i + 1) * NUMBUF; ++index) {
          try {
            SystemDefs.JavabaseBM.unpinPage(pids[index], true);
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not unpin page " + pids[index].pid + "\n");
            e.printStackTrace();
          }
        }
      }
    }

    if (status == OK) {
      System.out.print("  Test 4 completed successfully.\n");
    }

    return status;
  }
コード例 #6
0
ファイル: BMTest.java プロジェクト: umairsajid/Projects-1
  /**
   * overrides the test3 function in TestDriver. It exercises some of the internal of the buffer
   * manager
   *
   * @return whether test3 has passed
   */
  protected boolean test3() {

    System.out.print("\n  Test 3 exercises some of the internals " + "of the buffer manager\n");

    int index;
    int numPages = NUMBUF + 10;
    Page pg = new Page();
    PageId pid = new PageId();
    PageId[] pids = new PageId[numPages];
    boolean status = OK;

    System.out.print(
        "  - Allocate and dirty some new pages, one at " + "a time, and leave some pinned\n");

    for (index = 0; status == OK && index < numPages; ++index) {
      try {
        pid = SystemDefs.JavabaseBM.newPage(pg, 1);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Could not allocate new page number " + index + 1 + "\n");
        e.printStackTrace();
      }

      if (status == OK) pids[index] = pid;

      if (status == OK) {

        // Copy the page number + 99999 onto each page.  It seems
        // unlikely that this bit pattern would show up there by
        // coincidence.
        int data = pid.pid + 99999;

        try {
          Convert.setIntValue(data, 0, pg.getpage());
        } catch (IOException e) {
          System.err.print("*** Convert value failed\n");
          status = FAIL;
          e.printStackTrace();
        }

        // Leave the page pinned if it equals 12 mod 20.  This is a
        // random number based loosely on a bug report.
        if (status == OK) {
          if (pid.pid % 20 != 12) {
            try {
              SystemDefs.JavabaseBM.unpinPage(pid, /*dirty:*/ true);
            } catch (Exception e) {
              status = FAIL;
              System.err.print("*** Could not unpin dirty page " + pid.pid + "\n");
            }
          }
        }
      }
    }

    if (status == OK) {
      System.out.print("  - Read the pages\n");

      for (index = 0; status == OK && index < numPages; ++index) {
        pid = pids[index];
        try {
          SystemDefs.JavabaseBM.pinPage(pid, pg, false);
        } catch (Exception e) {
          status = FAIL;
          System.err.print("*** Could not pin page " + pid.pid + "\n");
          e.printStackTrace();
        }

        if (status == OK) {

          int data = 0;

          try {
            data = Convert.getIntValue(0, pg.getpage());
          } catch (IOException e) {
            System.err.print("*** Convert value failed \n");
            status = FAIL;
          }

          if (data != pid.pid + 99999) {
            status = FAIL;
            System.err.print("*** Read wrong data back from page " + pid.pid + "\n");
          }
        }

        if (status == OK) {
          try {
            SystemDefs.JavabaseBM.unpinPage(pid, true); // might not be dirty
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not unpin page " + pid.pid + "\n");
            e.printStackTrace();
          }
        }

        if (status == OK && (pid.pid % 20 == 12)) {
          try {
            SystemDefs.JavabaseBM.unpinPage(pid, /*dirty:*/ true);
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not unpin page " + pid.pid + "\n");
            e.printStackTrace();
          }
        }
      }
    }

    if (status == OK) System.out.print("  Test 3 completed successfully.\n");

    return status;
  }
コード例 #7
0
ファイル: BMTest.java プロジェクト: umairsajid/Projects-1
  /**
   * overrides the test2 function in TestDriver. It tests whether illeagal operation can be caught.
   *
   * @return whether test2 has passed
   */
  protected boolean test2() {

    System.out.print("\n  Test 2 exercises some illegal buffer " + "manager operations:\n");

    // We choose this number to ensure that pinning this number of buffers
    // should fail.
    int numPages = SystemDefs.JavabaseBM.getNumUnpinnedBuffers() + 1;
    Page pg = new Page();
    PageId pid, lastPid;
    PageId firstPid = new PageId();
    boolean status = OK;

    System.out.print("  - Try to pin more pages than there are frames\n");
    try {
      firstPid = SystemDefs.JavabaseBM.newPage(pg, numPages);
    } catch (Exception e) {
      System.err.print("*** Could not allocate " + numPages);
      System.err.print(" new pages in the database.\n");
      e.printStackTrace();
      return false;
    }

    pid = new PageId();
    lastPid = new PageId();

    // First pin enough pages that there is no more room.
    for (pid.pid = firstPid.pid + 1, lastPid.pid = firstPid.pid + numPages - 1;
        status == OK && pid.pid < lastPid.pid;
        pid.pid = pid.pid + 1) {

      try {
        SystemDefs.JavabaseBM.pinPage(pid, pg, /*emptyPage:*/ true);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Could not pin new page " + pid.pid + "\n");
        e.printStackTrace();
      }
    }

    // Make sure the buffer manager thinks there's no more room.
    if (status == OK && SystemDefs.JavabaseBM.getNumUnpinnedBuffers() != 0) {
      status = FAIL;
      System.err.print(
          "*** The buffer manager thinks it has "
              + SystemDefs.JavabaseBM.getNumUnpinnedBuffers()
              + " available frames,\n"
              + "    but it should have none.\n");
    }

    // Now pin that last page, and make sure it fails.
    if (status == OK) {
      try {
        SystemDefs.JavabaseBM.pinPage(lastPid, pg, /*emptyPage:*/ true);
      } catch (ChainException e) {
        status = checkException(e, "bufmgr.BufferPoolExceededException");
        if (status == FAIL) {
          System.err.print("*** Pinning too many pages\n");
          System.out.println("  --> Failed as expected \n");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      if (status == OK) {
        status = FAIL;
        System.err.print("The expected exception was not thrown\n");
      } else {
        status = OK;
      }
    }

    if (status == OK) {
      try {
        SystemDefs.JavabaseBM.pinPage(firstPid, pg, /*emptyPage:*/ true);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Could not acquire a second pin on a page\n");
        e.printStackTrace();
      }

      if (status == OK) {
        System.out.print("  - Try to free a doubly-pinned page\n");
        try {
          SystemDefs.JavabaseBM.freePage(firstPid);
        } catch (ChainException e) {
          status = checkException(e, "bufmgr.PagePinnedException");

          if (status == FAIL) {
            System.err.print("*** Freeing a pinned page\n");
            System.out.println("  --> Failed as expected \n");
          }
        } catch (Exception e) {
          e.printStackTrace();
        }

        if (status == OK) {
          status = FAIL;
          System.err.print("The expected exception was not thrown\n");
        } else {
          status = OK;
        }
      }

      if (status == OK) {
        try {
          SystemDefs.JavabaseBM.unpinPage(firstPid, false);
        } catch (Exception e) {
          status = FAIL;
          e.printStackTrace();
        }
      }
    }

    if (status == OK) {
      System.out.print("  - Try to unpin a page not in the buffer pool\n");
      try {
        SystemDefs.JavabaseBM.unpinPage(lastPid, false);
      } catch (ChainException e) {
        status = checkException(e, "bufmgr.HashEntryNotFoundException");

        if (status == FAIL) {
          System.err.print("*** Unpinning a page not in the buffer pool\n");
          System.out.println("  --> Failed as expected \n");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      if (status == OK) {
        status = FAIL;
        System.err.print("The expected exception was not thrown\n");
      } else {
        status = OK;
      }
    }

    for (pid.pid = firstPid.pid; pid.pid <= lastPid.pid; pid.pid = pid.pid + 1) {
      try {
        SystemDefs.JavabaseBM.freePage(pid);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Error freeing page " + pid.pid + "\n");
        e.printStackTrace();
      }
    }

    if (status == OK) System.out.print("  Test 2 completed successfully.\n");

    return status;
  }
コード例 #8
0
ファイル: BMTest.java プロジェクト: umairsajid/Projects-1
  /**
   * overrides the test1 function in TestDriver. It tests some simple normal buffer manager
   * operations.
   *
   * @return whether test1 has passed
   */
  protected boolean test1() {

    System.out.print("\n  Test 1 does a simple test of normal buffer ");
    System.out.print("manager operations:\n");

    // We choose this number to ensure that at least one page will have to be
    // written during this test.
    boolean status = OK;
    int numPages = SystemDefs.JavabaseBM.getNumUnpinnedBuffers() + 1;
    Page pg = new Page();
    PageId pid;
    PageId lastPid;
    PageId firstPid = new PageId();

    System.out.print("  - Allocate a bunch of new pages\n");

    try {
      firstPid = SystemDefs.JavabaseBM.newPage(pg, numPages);
    } catch (Exception e) {
      System.err.print("*** Could not allocate " + numPages);
      System.err.print(" new pages in the database.\n");
      e.printStackTrace();
      return false;
    }

    // Unpin that first page... to simplify our loop.
    try {
      SystemDefs.JavabaseBM.unpinPage(firstPid, false /*not dirty*/);
    } catch (Exception e) {
      System.err.print("*** Could not unpin the first new page.\n");
      e.printStackTrace();
      status = FAIL;
    }

    System.out.print("  - Write something on each one\n");

    pid = new PageId();
    lastPid = new PageId();

    for (pid.pid = firstPid.pid, lastPid.pid = pid.pid + numPages;
        status == OK && pid.pid < lastPid.pid;
        pid.pid = pid.pid + 1) {

      try {
        SystemDefs.JavabaseBM.pinPage(pid, pg, /*emptyPage:*/ true);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Could not pin new page " + pid.pid + "\n");
        e.printStackTrace();
      }

      if (status == OK) {

        // Copy the page number + 99999 onto each page.  It seems
        // unlikely that this bit pattern would show up there by
        // coincidence.
        int data = pid.pid + 99999;

        try {
          Convert.setIntValue(data, 0, pg.getpage());
        } catch (IOException e) {
          System.err.print("*** Convert value failed\n");
          status = FAIL;
        }

        if (status == OK) {
          try {
            SystemDefs.JavabaseBM.unpinPage(pid, /*dirty:*/ true);
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not unpin dirty page " + pid.pid + "\n");
            e.printStackTrace();
          }
        }
      }
    }

    if (status == OK)
      System.out.print(
          "  - Read that something back from each one\n"
              + "   (because we're buffering, this is where "
              + "most of the writes happen)\n");

    for (pid.pid = firstPid.pid; status == OK && pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

      try {
        SystemDefs.JavabaseBM.pinPage(pid, pg, /*emptyPage:*/ false);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Could not pin page " + pid.pid + "\n");
        e.printStackTrace();
      }

      if (status == OK) {

        int data = 0;

        try {
          data = Convert.getIntValue(0, pg.getpage());
        } catch (IOException e) {
          System.err.print("*** Convert value failed \n");
          status = FAIL;
        }

        if (status == OK) {
          if (data != (pid.pid) + 99999) {
            status = FAIL;
            System.err.print("*** Read wrong data back from page " + pid.pid + "\n");
          }
        }

        if (status == OK) {
          try {
            SystemDefs.JavabaseBM.unpinPage(pid, /*dirty:*/ true);
          } catch (Exception e) {
            status = FAIL;
            System.err.print("*** Could not unpin page " + pid.pid + "\n");
            e.printStackTrace();
          }
        }
      }
    }

    if (status == OK) System.out.print("  - Free the pages again\n");

    for (pid.pid = firstPid.pid; pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

      try {
        SystemDefs.JavabaseBM.freePage(pid);
      } catch (Exception e) {
        status = FAIL;
        System.err.print("*** Error freeing page " + pid.pid + "\n");
        e.printStackTrace();
      }
    }

    if (status == OK) System.out.print("  Test 1 completed successfully.\n");

    return status;
  }