Example #1
0
  @Test
  public void testParamsAndStatic() throws Exception {

    final TestHandler h1 = new TestHandler("h1");
    final TestHandler h2 = new TestHandler("h2");
    final TestHandler h3 = new TestHandler("h3");

    final Router service =
        new Router() //
            .add("/{id}/{param}", h1) //
            .add("/{id}/reallylongstatic", h2) //
            .add("/{id}/static", h3); //

    final Router root = new Router().add("/service", service);

    root.handle(new TestRequest("/service/1/2", "/service/1/2", "user"));

    assertEquals(1, h1.requests);
    assertEquals(0, h2.requests);
    assertEquals(0, h3.requests);

    root.handle(
        new TestRequest("/service/1/reallylongstatic", "/service/1/reallylongstatic", "user"));

    assertEquals(1, h1.requests);
    assertEquals(1, h2.requests);
    assertEquals(0, h3.requests);

    root.handle(new TestRequest("/service/1/static", "/service/1/static", "user"));

    assertEquals(1, h1.requests);
    assertEquals(1, h2.requests);
    assertEquals(1, h3.requests);
  }
Example #2
0
  static Route addCollectionRoutes(
      final Router router,
      final RoutingMode mode,
      final String uriTemplate,
      final CollectionResourceProvider provider) {
    if (uriTemplate.contains("{id}")) {
      throw new IllegalArgumentException("uriTemplate contains the variable {id}");
    }

    // Create a route for the instances within the collection.
    final StringBuilder builder = new StringBuilder();
    builder.append(uriTemplate);
    if (!uriTemplate.endsWith("/")) {
      builder.append('/');
    }
    builder.append("{id}");
    final RequestHandler instanceHandler = new CollectionInstance(provider);
    final Route instanceRoute = new Route(mode, builder.toString(), instanceHandler, null);

    // Create a route for the collection.
    final RequestHandler collectionHandler = new CollectionHandler(provider);
    final Route collectionRoute = new Route(EQUALS, uriTemplate, collectionHandler, instanceRoute);

    // Register the two routes - the instance route is a subroute of the
    // collection so it will be removed when the collection is removed.
    router.addRoute(collectionRoute);
    router.addRoute(instanceRoute);
    return collectionRoute;
  }
Example #3
0
  /**
   * Initialize the message history according to the router's configuration. Call this whenever the
   * router identity changes.
   */
  public synchronized void initialize(boolean forceReinitialize) {
    if (!forceReinitialize) return;
    Router router = _context.router();
    if (router == null) {
      // unit testing, presumably
      return;
    }

    if (router.getRouterInfo() == null) {
      _reinitializeJob.getTiming().setStartAfter(_context.clock().now() + 15 * 1000);
      _context.jobQueue().addJob(_reinitializeJob);
    } else {
      _localIdent = getName(_context.routerHash());
      // _unwrittenEntries = new ArrayList(64);
      updateSettings();
      // clear the history file on startup
      if (_firstPass) {
        File f = new File(_historyFile);
        if (!f.isAbsolute()) f = new File(_context.getLogDir(), _historyFile);
        f.delete();
        _writeJob.getTiming().setStartAfter(_context.clock().now() + WRITE_DELAY);
        _context.jobQueue().addJob(_writeJob);
        _firstPass = false;
      }
      if (_doLog)
        addEntry(getPrefix() + "** Router initialized (started up or changed identities)");
      // _submitMessageHistoryJob.getTiming().setStartAfter(_context.clock().now() + 2*60*1000);
      // _context.jobQueue().addJob(_submitMessageHistoryJob);
    }
  }
  @Test
  public void testTime() {
    int connections = 5;
    List<Integer> opIds = new ArrayList<>();
    // Build a router
    for (int i = 0; i < connections; i++) {
      opIds.add(i);
    }
    Router r = RouterFactory.buildRouterFor(opIds, false);

    // Try router
    // Try router
    int iter = 10000000;
    long start = System.nanoTime();
    for (int i = 0; i < iter; i++) {
      int opId = r.route();
    }
    long stop = System.nanoTime();
    long totalMillis = (stop - start) / 1000000;
    System.out.println(
        "Time to route: "
            + iter
            + " to "
            + connections
            + " downstreams is: "
            + totalMillis
            + " ms");
    assert (true);
  }
Example #5
0
 public void run() {
   long start = System.currentTimeMillis() / 1000;
   while (true) {
     long end = System.currentTimeMillis() / 1000;
     while (end - start < routerUpdateInterval * 2) {
       end = System.currentTimeMillis() / 1000;
     }
     router.sendAll(router.constructVector());
     start = end;
   }
 }
Example #6
0
  @Test
  public void testNested() throws Exception {

    final TestHandler account = new TestHandler("account");
    final Router accounts = new Router().add("/{id}", account);

    final Router root = new Router().add("/accounts", accounts);

    assertEquals(accounts, root.route(new TestRequest(null, "/accounts/1234", null)).handler);
    assertEquals(account, accounts.route(new TestRequest(null, "/1234", null)).handler);
  }
Example #7
0
  @Test
  public void testSoloParamPrefix() throws Exception {

    final TestHandler h1 = new TestHandler("h1");
    final Router service = new Router().add("/{id}", h1);
    final Router root = new Router().add("/service", service);

    root.handle(new TestRequest("/service/xyz/sub", "/service/xyz/sub", "user"));

    assertEquals(1, h1.requests);
  }
Example #8
0
  @Test
  public void testRequest() throws Exception {

    final TestHandler account = new TestHandler("account");
    final Router accounts = new Router().add("/{id}", account);

    final Router root = new Router().add("/accounts", accounts);

    root.handle(new TestRequest("/accounts/1234", "/accounts/1234", "1234"));

    assertEquals(1, account.requests);
    assertEquals(0, account.exceptions);
  }
Example #9
0
  @Test
  public void testFlat() throws Exception {

    final TestHandler root = new TestHandler("root");
    final TestHandler account = new TestHandler("account");
    final TestHandler permissions = new TestHandler("permissions");
    final TestHandler prefix = new TestHandler("prefix");
    final TestHandler permission = new TestHandler("permission");

    final Router router =
        new Router()
            .add("/", root) //
            .add("/{id}", account) //
            .add("/{id}/permissions", permissions) //
            .add("/{id}/permissions/{prefix}", prefix) //
            .add("/{id}/permission/{token}", permission);

    assertEquals(root, router.route(new TestRequest(null, "/", null)).handler);
    assertEquals(account, router.route(new TestRequest(null, "/1234", null)).handler);
    assertEquals(account, router.route(new TestRequest(null, "/acds", null)).handler);
    assertEquals(account, router.route(new TestRequest(null, "/acds/", null)).handler);
    assertEquals(account, router.route(new TestRequest(null, "/acds/x", null)).handler);
    assertEquals(
        permissions, router.route(new TestRequest(null, "/1234/permissions", null)).handler);
    assertEquals(
        prefix,
        router.route(new TestRequest(null, "/1234/permissions/com.barchart.feed", null)).handler);
    assertEquals(
        permission,
        router.route(
                new TestRequest(null, "/1234/permission/com.barchart.feed.stream.symbols", null))
            .handler);
  }
  @Override
  public void init(FilterConfig fc) throws ServletException {
    log.info("DispatcherFilter starting ...");
    log.info("java.version = {}", JdkUtils.JAVA_VERSION);
    log.info("webmvc.version = {}", WebConfig.VERSION);
    log.info("user.dir = {}", System.getProperty("user.dir"));
    log.info("java.io.tmpdir = {}", System.getProperty("java.io.tmpdir"));
    log.info("user.timezone = {}", System.getProperty("user.timezone"));
    log.info("file.encoding = {}", System.getProperty("file.encoding"));

    try {
      long ts = System.currentTimeMillis();

      ServletContext sc = fc.getServletContext();
      String configLocation = fc.getInitParameter("configLocation");
      WebInitializer.initialize(sc, configLocation);

      httpEncoding = WebConfig.getHttpEncoding();
      httpCache = WebConfig.isHttpCache();
      router = WebConfig.getRouter();
      bypassRequestUrls = WebConfig.getBypassRequestUrls();
      corsRequestProcessor = WebConfig.getCORSRequestProcessor();
      resultHandlerResolver = WebConfig.getResultHandlerResolver();
      fileUploadResolver = WebConfig.getFileUploadResolver();
      exceptionHandler = WebConfig.getExceptionHandler();

      log.info("web.root = {}", WebConfig.getWebroot());
      log.info("web.development = {}", WebConfig.isDevelopment());
      log.info("web.upload.dir = {}", WebConfig.getUploaddir());
      log.info("web.urls.router = {}", router.getClass().getName());
      log.info(
          "web.urls.bypass = {}",
          (bypassRequestUrls == null) ? null : bypassRequestUrls.getClass().getName());
      log.info(
          "web.urls.cors = {}",
          (corsRequestProcessor == null) ? null : corsRequestProcessor.getClass().getName());

      for (Plugin plugin : WebConfig.getPlugins()) {
        log.info("load plugin: {}", plugin.getClass().getName());
        plugin.initialize();
      }

      for (Interceptor interceptor : WebConfig.getInterceptors()) {
        log.info("load interceptor: {}", interceptor.getClass().getName());
        interceptor.initialize();
      }

      log.info(
          "DispatcherFilter initialize successfully, Time elapsed: {} ms.",
          System.currentTimeMillis() - ts);

    } catch (Exception e) {
      log.error("Failed to initialize DispatcherFilter", e);
      log.error("*************************************");
      log.error("          System.exit(1)             ");
      log.error("*************************************");
      System.exit(1);
    }
  }
Example #11
0
  @Test
  public void testParams() throws Exception {

    final TestHandler account = new TestHandler("account");
    final Router accounts = new Router().add("/{id}", account);

    final Router root = new Router().add("/accounts", accounts);

    root.handle(new TestRequest("/accounts/1234", "/accounts/1234", "1234"));

    assertEquals(1, account.requests);
    assertEquals(0, account.exceptions);
    assertEquals(1, account.params.size());
    assertNotNull(account.params.get("id"));
    assertEquals(1, account.params.get("id").size());
    assertEquals("1234", account.params.get("id").get(0));
  }
 public Connection getRandomConnection() throws IOException {
   checkLive();
   final Address address = router.next();
   if (address == null) {
     throw new IOException("LoadBalancer '" + router + "' could not find a address to route to");
   }
   return getConnection(address);
 }
Example #13
0
 /** Tie in the router's config as properties, as well as whatever the I2PAppContext says. */
 @Override
 public String getProperty(String propName, String defaultVal) {
   if (_router != null) {
     String val = _router.getConfigSetting(propName);
     if (val != null) return val;
   }
   return super.getProperty(propName, defaultVal);
 }
Example #14
0
  private int execute(Prepared p) {
    beginTransaction(p);

    boolean isTopTransaction = false;
    boolean isNestedTransaction = false;
    Session session = p.getSession();

    try {
      if (!p.isLocal() && p.isBatch()) {
        if (session.isAutoCommit()) {
          session.setAutoCommit(false);
          isTopTransaction = true;
        } else {
          isNestedTransaction = true;
          session.addSavepoint(TransactionCommand.INTERNAL_SAVEPOINT);
        }
      }
      int updateCount = 0;
      switch (p.getType()) {
        case CommandInterface.INSERT:
          updateCount = nestedRouter.executeInsert((Insert) p);
          break;
        case CommandInterface.UPDATE:
          updateCount = nestedRouter.executeUpdate((Update) p);
          break;
        case CommandInterface.DELETE:
          updateCount = nestedRouter.executeDelete((Delete) p);
          break;
        case CommandInterface.MERGE:
          updateCount = nestedRouter.executeMerge((Merge) p);
          break;
      }
      if (isTopTransaction) session.commit(false);
      return updateCount;
    } catch (Exception e) {
      if (isTopTransaction) session.rollback();

      // 嵌套事务出错时提前rollback
      if (isNestedTransaction) session.rollbackToSavepoint(TransactionCommand.INTERNAL_SAVEPOINT);

      throw DbException.convert(e);
    } finally {
      if (isTopTransaction) session.setAutoCommit(true);
    }
  }
  @Test
  public void test() {
    int connections = 100;
    List<Integer> opIds = new ArrayList<>();
    // Build a router
    for (int i = 0; i < connections; i++) {
      opIds.add(i);
    }
    Router r = RouterFactory.buildRouterFor(opIds, false);

    // Try router
    int iter = 1000;
    for (int i = 0; i < iter; i++) {
      int opId = r.route();
      System.out.println("route-to: " + opId);
    }
    assert (true);
  }
  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    request.setCharacterEncoding(httpEncoding);
    response.setCharacterEncoding(httpEncoding);

    String path = RequestUtils.getPathInfo(request);

    if (httpCache == false) {
      ResponseUtils.setBufferOff(response);
    }

    if (bypassRequestUrls != null && bypassRequestUrls.accept(request, path)) {
      chain.doFilter(request, response);
      return;
    }

    HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());

    if (corsRequestProcessor != null) {
      corsRequestProcessor.setHeaders(request, response);
      if (httpMethod == HttpMethod.OPTIONS) {
        response.setStatus(HttpServletResponse.SC_OK);
        return;
      }
    }

    RouteInfo route = router.lookup(request, path, httpMethod);
    request = fileUploadResolver.transform(request);
    RequestContext ctx = new RequestContext(request, response, path, httpMethod, route);

    try {
      if (route == null || route == RouteInfo.NOT_FOUND) {
        throw new ActionNotFoundException(path);
      }

      InterceptorChainImpl interceptorChain =
          new InterceptorChainImpl(WebConfig.getInterceptors(), ctx);
      interceptorChain.invoke();

      ResultInfo result = interceptorChain.getResult();
      if (result != null) {
        ResultHandler<Object> handler = resultHandlerResolver.lookup(result.getResultClass());
        handler.handle(ctx, result.getResultObject());
      }
    } catch (Exception e) {
      handleError(ctx, e);
    } finally {
      if (ctx != null) {
        ctx.destory();
      }
    }
  }
    /// Pass user's interaction with list to appropriate handler
    public void valueChanged(ListSelectionEvent e) {
      if (e.getSource() == sourceList) {
        if (!e.getValueIsAdjusting()) {
          int indexS = sourceList.getSelectedIndex();
          srcID = indexS + 1;
          drawTest.repaint();
        }
      }

      if (e.getSource() == destList) {
        if (!e.getValueIsAdjusting()) {
          int indexD = destList.getSelectedIndex();
          dstID = indexD + 17;
          drawTest.repaint();
        }
      }

      if (e.getSource() == routerList) {
        if (!e.getValueIsAdjusting()) {
          indexR = routerList.getSelectedIndex();

          Router temp = statMux.getRouter(indexR);
          int[] pList = temp.getPriorityList();
          audioVal.setText(String.valueOf(pList[0]));
          videoVal.setText(String.valueOf(pList[1]));
          textVal.setText(String.valueOf(pList[2]));
        }
      }

      if (e.getSource() == packTypeList) {
        if (!e.getValueIsAdjusting()) {
          int temp = packTypeList.getSelectedIndex();
          if (temp == 0) {
            type = PacketType.AUDIO;
          } else if (temp == 1) {
            type = PacketType.VIDEO;
          } else {
            type = PacketType.TEXT;
          }
          drawTest.repaint();
        }
      }
    }
Example #18
0
  /**
   * Test method for {@link
   * de.highbyte_le.weberknecht.request.routing.MetaRouter#routeUri(java.lang.String)}.
   */
  @Test
  public void testRouteUri() {
    HttpServletRequest foo = mock(HttpServletRequest.class);
    HttpServletRequest bar = mock(HttpServletRequest.class);
    HttpServletRequest foobar = mock(HttpServletRequest.class);

    RoutingTarget targetFoo = new RoutingTarget("foo", "do", null);
    RoutingTarget targetBar = new RoutingTarget("bar", "do", null);
    when(r1.routeUri(foo)).thenReturn(targetFoo);
    when(r2.routeUri(bar)).thenReturn(targetBar);

    assertEquals(targetFoo, router.routeUri(foo));
    assertEquals(targetBar, router.routeUri(bar));
    assertNull(router.routeUri(foobar));

    verify(r1, times(1)).routeUri(foo);
    verify(r1, times(1)).routeUri(bar);
    verify(r2, times(0)).routeUri(foo);
    verify(r2, times(1)).routeUri(bar);
  }
  public CollectionPathFinder collect() {
    Map<ItemKey, Integer> collected = new HashMap<ItemKey, Integer>();
    for (StartEndPath l : requester.getRouter().getRoutesByCost()) {
      Router r = l.end;
      IWorldRouter wr = r.getParent();
      if (wr instanceof IWorldCrafter && collectCrafts) {
        IWorldCrafter c = (IWorldCrafter) wr;
        c.getBroadcastedItems(collected);
        List<ItemKeyStack> list = c.getCraftedItems();
        if (list != null)
          for (ItemKeyStack stack : list)
            if (!collected.containsKey(stack.key())) collected.put(stack.key(), null);
      } else if (wr instanceof IWorldBroadcaster && collectBroadcasts) {
        IWorldBroadcaster b = (IWorldBroadcaster) wr;
        b.getBroadcastedItems(collected);
      }
    }

    this.collected = collected;
    return this;
  }
  // getDelay function
  // It takes in an optimized path and packet type as input.
  // Based on input, the function calculates delay occured when traveling
  // through the optimized path
  public double getDelay(int[] opath, PacketType type) {
    double delay = 0;

    for (int i = 1; i < 4; i++) {
      Router temp = statMux.getRouter(opath[i] - 4);
      int flow = temp.getFlowLevel();
      int delayR = temp.getDelay();
      int priority = temp.getPriority(type);
      int thr = temp.getThroughput();
      packThrough[i - 1] = thr;

      if (priority == 1) {
        loss[i - 1] = thr / 10.0;
      }
      if (priority == 2) {
        loss[i - 1] = thr / 5.0;
      }

      delay += numPack / thr + delayR + priority * flow;
    }

    return delay;
  }
Example #21
0
 /** Return an int with an int default */
 @Override
 public int getProperty(String propName, int defaultVal) {
   if (_router != null) {
     String val = _router.getConfigSetting(propName);
     if (val != null) {
       int ival = defaultVal;
       try {
         ival = Integer.parseInt(val);
       } catch (NumberFormatException nfe) {
       }
       return ival;
     }
   }
   return super.getProperty(propName, defaultVal);
 }
Example #22
0
 /**
  * Return a long with a long default
  *
  * @since 0.9.4
  */
 @Override
 public long getProperty(String propName, long defaultVal) {
   if (_router != null) {
     String val = _router.getConfigSetting(propName);
     if (val != null) {
       long rv = defaultVal;
       try {
         rv = Long.parseLong(val);
       } catch (NumberFormatException nfe) {
       }
       return rv;
     }
   }
   return super.getProperty(propName, defaultVal);
 }
Example #23
0
  public void run() {
    String threadName = Thread.currentThread().getName();
    if (logger != null) {
      logger.Log("Thread " + threadName + " started");
    }

    boolean status = Router.Publish(routerURI, topic, eventSize, eventCount, delay, logger);

    if (logger != null) {
      logger.Log("Thread " + threadName + " finished with status " + status);
    }

    if (reporter != null) {
      reporter.ReportStatus(reportIndex, status);
    }
  }
Example #24
0
  private List<RouteNodeInfo> testRoute(
      RouteRuleOp ruleOp, String ruleParamValue, String destination, String[] availHosts) {
    RouteInfo route = new RouteInfo();
    RouteRuleInfo rule = new RouteRuleInfo();
    rule.setType(RouteRuleType.HOST);
    rule.setSrcOp(ruleOp);
    rule.setSrcValue(ruleParamValue);
    rule.setDestination(destination);
    route.getRules().add(rule);

    for (String host : availHosts) {
      RouteNodeInfo node = new RouteNodeInfo();
      node.setHost(host);
      route.getNodes().add(node);
    }

    return router.route(rule, route.getNodes(), null);
  }
 @Override
 public void release(final HttpServerRequest request) {
   router.release(request);
 }
Example #26
0
  /**
   * Append a path, creates the necessary routes and returns the last route added.
   *
   * @param pathParamDescriptors the path param descriptors
   * @param path the path to append
   * @return the last route added
   */
  private Route append(Map<QualifiedName, PathParamDescriptor> pathParamDescriptors, String path)
      throws MalformedRouteException {
    if (path.length() == 0 || path.charAt(0) != '/') {
      throw new MalformedRouteException();
    }

    //
    int pos = path.length();
    int level = 0;
    List<Integer> start = new ArrayList<Integer>();
    List<Integer> end = new ArrayList<Integer>();
    for (int i = 1; i < path.length(); i++) {
      char c = path.charAt(i);
      if (c == '{') {
        if (level++ == 0) {
          start.add(i);
        }
      } else if (c == '}') {
        if (--level == 0) {
          end.add(i);
        }
      } else if (c == '/') {
        if (level == 0) {
          pos = i;
          break;
        }
      }
    }

    //
    Route next;
    if (start.isEmpty()) {
      String segment = path.substring(1, pos);
      SegmentRoute route = new SegmentRoute(router, segment);
      add(route);
      next = route;
    } else {
      if (start.size() == end.size()) {
        PatternBuilder builder = new PatternBuilder();
        builder.expr("^").expr('/');
        List<String> chunks = new ArrayList<String>();
        List<PathParam> parameterPatterns = new ArrayList<PathParam>();

        //
        int previous = 1;
        for (int i = 0; i < start.size(); i++) {
          builder.litteral(path, previous, start.get(i));
          chunks.add(path.substring(previous, start.get(i)));
          String parameterName = path.substring(start.get(i) + 1, end.get(i));

          //
          QualifiedName parameterQName = QualifiedName.parse(parameterName);

          // Now get path param metadata
          PathParamDescriptor parameterDescriptor = pathParamDescriptors.get(parameterQName);

          //
          PathParam param;
          if (parameterDescriptor != null) {
            param = PathParam.create(parameterDescriptor, router);
          } else {
            param = PathParam.create(parameterQName, router);
          }

          // Append routing regex to the route regex surrounded by a non capturing regex
          // to isolate routingRegex like a|b or a(.)b
          builder.expr("(?:").expr(param.routingRegex).expr(")");

          // Add the path param with the rendering regex
          parameterPatterns.add(param);
          previous = end.get(i) + 1;
        }

        //
        builder.litteral(path, previous, pos);

        // We want to satisfy one of the following conditions
        // - the next char after the matched expression is '/'
        // - the expression matched until the end
        // - the match expression is the '/' expression
        builder.expr("(?:(?<=^/)|(?=/)|$)");

        //
        chunks.add(path.substring(previous, pos));
        PatternRoute route =
            new PatternRoute(router, router.compile(builder.build()), parameterPatterns, chunks);

        // Wire
        add(route);

        //
        next = route;
      } else {
        throw new UnsupportedOperationException("Report error");
      }
    }

    //
    if (pos < path.length()) {
      return next.append(pathParamDescriptors, path.substring(pos));
    } else {
      return next;
    }
  }
Example #27
0
 /**
  * Convenience method for getting the router hash. Equivalent to
  * context.router().getRouterInfo().getIdentity().getHash()
  *
  * @return may be null if called very early
  */
 public Hash routerHash() {
   if (_router == null) return null;
   RouterInfo ri = _router.getRouterInfo();
   if (ri == null) return null;
   return ri.getIdentity().getHash();
 }
Example #28
0
 /**
  * @return new Properties with system and context properties
  * @since 0.8.4
  */
 @Override
 public Properties getProperties() {
   Properties rv = super.getProperties();
   if (_router != null) rv.putAll(_router.getConfigMap());
   return rv;
 }
    public void paint(Graphics g) {
      path = findOptimizedPath(srcID, dstID, type);

      /// Create the drawing board
      Dimension d = getSize();
      g.setColor(Color.white);
      g.fillRect(1, 1, d.width - 2, d.height - 2);

      g.setColor(Color.black);
      g.drawRect(1, 1, d.width - 2, d.height - 2);
      g.setFont(serifFont);

      /// Draw the whole network, including all routers with
      ///     delay and flow level, sources and destinations.
      int numR = 1;
      int w = 95;
      int h = d.height / 5;
      int pos = -1;

      for (int i = 0; i < 3; i++) {
        g.drawOval(w, h + 100 * i, 40, 40);
        g.drawString("S" + String.valueOf(i + 1), w + 13, h + 100 * i - 5);
      }

      for (int i = 0; i < 3; i++) {
        pos++;
        Router temp = statMux.getRouter(pos);
        g.drawOval(w + 110, h + 100 * i, 40, 40);
        g.drawString("R" + String.valueOf(numR++), w + 123, h + 100 * i - 5);
        g.drawString(
            String.valueOf(temp.getDelay() * temp.getPriority(type) + temp.getFlowLevel()),
            w + 125,
            h + 100 * i + 15);
        g.drawString(String.valueOf(temp.getFlowLevel()), w + 125, h + 100 * i + 35);
      }

      h = d.height / 11;
      for (int i = 0; i < 4; i++) {
        pos++;
        Router temp = statMux.getRouter(pos);
        g.drawOval(w + 210, h + 100 * i, 40, 40);
        g.drawString("R" + String.valueOf(numR++), w + 223, h + 100 * i - 5);
        g.drawString(
            String.valueOf(temp.getDelay() * temp.getPriority(type) + temp.getFlowLevel()),
            w + 225,
            h + 100 * i + 15);
        g.drawString(String.valueOf(temp.getFlowLevel()), w + 225, h + 100 * i + 35);
      }

      h = 20;
      for (int i = 0; i < 6; i++) {
        pos++;
        Router temp = statMux.getRouter(pos);
        g.drawOval(w + 310, h + 80 * i, 40, 40);
        g.drawString("R" + String.valueOf(numR++), w + 320, h + 80 * i - 5);
        g.drawString(
            String.valueOf(temp.getDelay() * temp.getPriority(type) + temp.getFlowLevel()),
            w + 325,
            h + 80 * i + 15);
        g.drawString(String.valueOf(temp.getFlowLevel()), w + 325, h + 80 * i + 35);
      }

      for (int i = 0; i < 4; i++) {
        g.drawOval(w + 410, d.height / 11 + 100 * i, 40, 40);
        g.drawString("D" + String.valueOf(i + 1), w + 423, d.height / 11 + 100 * i - 5);
      }

      g.setColor(Color.black);
      int[][] connection = statMux.getConnections();

      /// Check buffer for connections at each step and draw links at layer1
      for (int i = 0; i < connection[path[0] - 1].length; i++) {
        int temp = connection[path[0] - 1][i] - 3;
        g.drawLine(w + 40, (path[0]) * d.height / 5 + 20, w + 110, temp * d.height / 5 + 20);
      }

      /// Check buffer for connections at each step and draw links at layer2
      for (int i = 0; i < connection[path[1] - 1].length; i++) {
        int temp = connection[path[1] - 1][i] - 7;
        g.drawLine(
            w + 150, (path[1] - 3) * d.height / 5 + 20, w + 210, (d.height / 11) + 100 * temp + 20);
      }

      /// Check buffer for connections at each step and draw links at layer3
      for (int i = 0; i < connection[path[2] - 1].length; i++) {
        int temp = connection[path[2] - 1][i] - 11;
        g.drawLine(w + 250, (d.height / 11) + 100 * (path[2] - 7) + 20, w + 310, 80 * temp + 40);
      }

      /// Draw optimized path for packets traveling between source
      /// and destination
      h = d.height / 5;
      Graphics2D g2 = (Graphics2D) g;
      g2.setStroke(new BasicStroke(2));
      g2.setColor(Color.red);

      g2.drawLine(w + 40, h * (path[0]) + 20, w + 110, h * (path[1] - 3) + 20);
      g2.drawLine(
          w + 150, h * (path[1] - 3) + 20, w + 210, (d.height / 11) + 100 * (path[2] - 7) + 20);
      g2.drawLine(
          w + 250, (d.height / 11) + 100 * (path[2] - 7) + 20, w + 310, 80 * (path[3] - 11) + 40);
      g2.drawLine(
          w + 350, 80 * (path[3] - 11) + 40, w + 410, (d.height / 11) + 100 * (path[4] - 17) + 20);

      /// Calculate and display loss, delay, and throughput
      delayTime = getDelay(path, type);
      throughPut = getThroughput(path);

      int numPackLost = getLossRate(numTransfer);

      lossRate = numPackLost / 100000.0 + 0.0005 * delayTime;
      delayVal.setText(String.format("%.2f", delayTime));
      throuVal.setText(String.valueOf(throughPut));
      lossVal.setText(String.format("%.4f", lossRate));
    }
    /// Check for button clicking and apply appropriate response
    public void actionPerformed(ActionEvent e) {
      /// For each input, pass it to the correct handler
      /// Priority of router will be updated based on input
      /// Upon user's changes of the priority value, repaint
      /// the display component
      if (e.getSource() == aPlus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[0] = dataBound(pList[0] + 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }

      if (e.getSource() == aMinus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[0] = dataBound(pList[0] - 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }

      if (e.getSource() == vPlus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[1] = dataBound(pList[1] + 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }

      if (e.getSource() == vMinus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[1] = dataBound(pList[1] - 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }

      if (e.getSource() == tPlus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[2] = dataBound(pList[2] + 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }

      if (e.getSource() == tMinus) {
        Router temp = statMux.getRouter(indexR);
        int[] pList = temp.getPriorityList();
        pList[2] = dataBound(pList[2] - 1);
        temp.setPriorityList(pList);
        audioVal.setText(String.valueOf(pList[0]));
        videoVal.setText(String.valueOf(pList[1]));
        textVal.setText(String.valueOf(pList[2]));
        drawTest.repaint();
      }
    }