/** Start the thread that periodically updates the metadata. */
  public void startUpdating() {
    if (update == true) {
      return;
    }

    final Sink metadataSink = new Sink();
    try {
      metadataSink.OpenRBNBConnection(rbnbController.getRBNBConnectionString(), rbnbSinkName);
    } catch (SAPIException e) {
      log.error("Failed to connect to RBNB server: " + e.getMessage());
      e.printStackTrace();
      return;
    }

    updateMetadata(metadataSink);

    updateThread =
        new Thread("MetadataManager") {
          public void run() {
            log.info("RBNB Metadata thread is starting.");

            updateMetadataThread(metadataSink);

            metadataSink.CloseRBNBConnection();

            channels.clear();
            ctree = null;

            log.info("RBNB Metadata thread is stopping.");
          }
        };
    update = true;
    updateThread.start();
  }
 private void testConnect() {
   try {
     // test the connection to the server
     Sink sink = new Sink();
     sink.OpenRBNBConnection(getServer(), sinkName);
     connected = true;
     System.out.println(
         "DataVideoGather: Test connection made to server = "
             + getServer()
             + " as "
             + sinkName
             + ".");
     sink.CloseRBNBConnection();
   } catch (SAPIException se) {
     se.printStackTrace();
   }
 }
  private ChannelTree getChannelTree(String pattern) {

    ChannelTree tr = null;

    try {
      sMap = new ChannelMap();
      if ((pattern != null) && (pattern.length() > 0)) sMap.Add(pattern);
      sink.RequestRegistration(sMap);
      sMap = sink.Fetch(-1, sMap);
      tr = ChannelTree.createFromChannelMap(sMap);

    } catch (SAPIException se) {
      se.printStackTrace();
    }

    return tr;
  }
  public void appendChannelListFromPattern() {
    try {
      // Create a sink and connect:
      Sink sink = new Sink();
      sink.OpenRBNBConnection(getServer(), sinkName);

      // get all the channel paths that match the pattern
      ChannelMap sMap = new ChannelMap();
      sink.RequestRegistration();
      sMap = sink.Fetch(-1, sMap);
      ChannelTree tree = ChannelTree.createFromChannelMap(sMap);

      Pattern p = Pattern.compile(channelPathPattern);
      // for each channel path, check match, collect matches...

      Iterator nodes = tree.iterator();
      while (nodes.hasNext()) {
        ChannelTree.Node n = (ChannelTree.Node) nodes.next();
        // System.out.println("Checking " + n.getFullName() + ";" + n.getName());
        if (!includeHidden && n.getFullName().startsWith("_")) continue;
        if (n.getType() != ChannelTree.CHANNEL) continue;
        String name = n.getFullName();
        Matcher m = p.matcher(name);
        if (m.matches()) {
          //					System.out.println("Matches");
          boolean isSource = false;
          ChannelTree.Node upNode = n.getParent();
          while ((!isSource) || (upNode != null)) {
            if (upNode.getType() == ChannelTree.SOURCE) isSource = true;
            upNode = upNode.getParent();
          }
          if (isSource) {
            // System.out.println("... and is a source.");
            channelPathList.add(n);
          } else {
            // System.out.println("... and is NOT a source.");
          }
        }
      }

    } catch (SAPIException se) {
      se.printStackTrace();
    }
  } // appendChannelListFromPattern
  public void appendChannelListFromString() {
    try {
      StringTokenizer st = new StringTokenizer(channelPathListString, ",");

      // Create a sink and connect:
      Sink sink = new Sink();
      sink.OpenRBNBConnection(getServer(), sinkName);

      // get all the channel paths that match the pattern
      ChannelMap sMap = new ChannelMap();
      sink.RequestRegistration();
      sMap = sink.Fetch(-1, sMap);
      ChannelTree tree = ChannelTree.createFromChannelMap(sMap);

      Pattern p = Pattern.compile(channelPathPattern);
      // for each channel path, check match, collect matches...

      while (st.hasMoreTokens()) {
        String path = st.nextToken();
        //				System.out.println("Checking " + path);

        ChannelTree.Node n = tree.findNode(path);
        if (n == null) continue;
        if (n.getType() != ChannelTree.CHANNEL) continue;
        String name = n.getFullName();
        //				System.out.println("Found it...");
        boolean isSource = false;
        ChannelTree.Node upNode = n.getParent();
        while ((!isSource) || (upNode != null)) {
          if (upNode.getType() == ChannelTree.SOURCE) isSource = true;
          upNode = upNode.getParent();
        }
        if (isSource) {
          //					System.out.println("... and is a source.");
          channelPathList.add(n);
        } else {
          //					System.out.println("... and is NOT a source.");
        }
      } // while next token
    } catch (SAPIException se) {
      se.printStackTrace();
    }
  } // appendChannelListFromString
  /**
   * Updates the metadata and posts it to listeners. It also notifies all threads waiting on this
   * object.
   *
   * @param metadataSink the RBNB sink to use for the server connection
   */
  private synchronized void updateMetadata(Sink metadataSink) {
    // log.info("Updating channel listing at " + DataViewer.formatDate(System.currentTimeMillis
    // ()));

    Map<String, Channel> newChannels = new HashMap<String, Channel>();

    ChannelTree channelTree;
    try {
      // create metadata channel tree
      channelTree = getChannelTree(metadataSink, newChannels);
    } catch (SAPIException e) {
      log.error("Failed to update metadata: " + e.getMessage() + ".");

      if (!metadataSink.VerifyConnection()) {
        log.error(
            "Metadata RBNB connection is severed, try to reconnect to "
                + rbnbController.getRBNBConnectionString()
                + ".");
        metadataSink.CloseRBNBConnection();
        try {
          metadataSink.OpenRBNBConnection(rbnbController.getRBNBConnectionString(), "RDVMetadata");
        } catch (SAPIException error) {
          log.error("Failed to connect to RBNB server: " + error.getMessage());
          error.printStackTrace();
        }
      }

      return;
    }

    if (LocalChannelManager.getInstance().hasChannels()) {
      ChannelTree localChannelTree = getLocalChannelTree(newChannels, channelTree);
      ctree = localChannelTree.merge(channelTree);
    } else {
      ctree = channelTree;
    }

    channels = newChannels;

    // notify metadata listeners
    fireMetadataUpdated(ctree);
  }
 public void connect() {
   try {
     // Create a sink and connect:
     sink = new Sink();
     sink.OpenRBNBConnection(getServer(), "ChannelListRequest");
     connected = true;
     System.out.println(
         "ChannelList: Connection made to server = " + getServer() + " requesting channel list.");
   } catch (SAPIException se) {
     se.printStackTrace();
   }
 }
  /**
   * Get the metadata channel tree for the given <code>path</code>. This will populate the channel
   * map with channel objects derived from the metadata. This will recursively make requests for
   * child servers and plugins up to the maximum request depth of {@value #MAX_REQUEST_DEPTH}.
   *
   * @param sink sink the sink connection to the RBNB server
   * @param path the path for the desired metadata
   * @param channels the map to populate with channel objects
   * @param depth the depth of the request
   * @return the metadata channel tree for the given path
   * @throws SAPIException if a server error occurs
   * @see #MAX_REQUEST_DEPTH
   */
  private ChannelTree getChannelTree(
      Sink sink, String path, Map<String, Channel> channels, int depth) throws SAPIException {
    depth++;

    ChannelTree ctree = ChannelTree.EMPTY_TREE;

    ChannelMap markerChannelMap = new ChannelMap();

    ChannelMap cmap = new ChannelMap();

    if (path == null) {
      path = "";
      cmap.Add("...");
    } else {
      cmap.Add(path + "/...");
    }

    sink.RequestRegistration(cmap);

    cmap = sink.Fetch(FETCH_TIMEOUT, cmap);

    if (cmap.GetIfFetchTimedOut()) {
      log.error("Failed to get metadata.  Fetch timed out.");
      return ctree;
    }

    ctree = ChannelTree.createFromChannelMap(cmap);

    // store user metadata in channel objects
    String[] channelList = cmap.GetChannelList();
    for (int i = 0; i < channelList.length; i++) {
      int channelIndex = cmap.GetIndex(channelList[i]);
      if (channelIndex != -1) {
        ChannelTree.Node node = ctree.findNode(channelList[i]);
        String userMetadata = cmap.GetUserInfo(channelIndex);
        Channel channel = new RBNBChannel(node, userMetadata);
        channels.put(channelList[i], channel);

        // look for marker channels
        String mimeType = channel.getMetadata("mime");
        if (mimeType != null && mimeType.compareToIgnoreCase(EventMarker.MIME_TYPE) == 0) {
          markerChannelMap.Add(node.getFullName());
        }
      }
    }

    Iterator<?> it = ctree.iterator();
    while (it.hasNext()) {
      ChannelTree.Node node = (ChannelTree.Node) it.next();
      NodeTypeEnum type = node.getType();

      // look for child servers or plugins and get their channels
      if ((type == ChannelTree.SERVER || type == ChannelTree.PLUGIN)
          && !path.startsWith(node.getFullName())
          && depth < MAX_REQUEST_DEPTH) {
        ChannelTree childChannelTree = getChannelTree(sink, node.getFullName(), channels, depth);
        ctree = childChannelTree.merge(ctree);
      }
    }

    if (markerChannelMap.NumberOfChannels() > 0) {
      double markersDuration = System.currentTimeMillis() / 1000d;

      // request from start of marker channels to now
      sink.Request(markerChannelMap, 0, markersDuration, "absolute");

      markerChannelMap = sink.Fetch(FETCH_TIMEOUT, markerChannelMap);
      if (!markerChannelMap.GetIfFetchTimedOut()) {
        // notify marker listeners
        fireMarkersUpdated(markerChannelMap);
      } else {
        log.error("Failed to get event markers. Fetched timed out.");
      }
    }

    return ctree;
  }
    public void run() {
      if (debug) System.err.println("PIrun, sourceFolder: " + sourceFolder + ", sName: " + sName);

      PlugInChannelMap picm = new PlugInChannelMap();
      plugin = new PlugIn();

      try {
        plugin.OpenRBNBConnection(rbnbServer, sName);
        sink = new Sink();
        sink.OpenRBNBConnection(rbnbServer, sinkName);
      } catch (Exception e) {
        System.err.println("Error on connect: " + e);
        System.exit(0);
        //		    RBNBProcess.exit(0);
      }

      if (preRegister) {
        try {
          System.err.println("pre-registering channels for source: " + sName);
          picm.Add("...");
          regPicm = handleRegistration(picm);
          //					plugin.Register(picm);			// pre-register
          System.err.println("pre-register done: " + sName);
        } catch (Exception se) {
          System.err.println("Oops, exception on preRegister: " + se);
        }
      }

      // process is to wait for request, get data from sink, convert data, send response, repeat
      while (true) {
        try {
          if (debug) System.err.println("waiting on fetch...");
          picm = plugin.Fetch(-1); // block until request arrives
          if (debug) System.err.println("request picm: " + picm);

          if (picm.NumberOfChannels() == 0) {
            System.err.println("oops, no channels in request");
            continue;
          }

          if (picm.GetRequestReference().equals("registration")) {
            if (debug) System.err.println("registration request!");
            plugin.Flush(handleRegistration(picm));
            continue;
          } else {
            double tget = picm.GetRequestStart();
            double tdur = picm.GetRequestDuration();
            String tmode = picm.GetRequestReference();
            CTmap ctmap = PI2CTmap(picm);
            ctmap = ctreader.getDataMap(ctmap, sourceFolder, tget, tdur, tmode);
            picm = CT2PImap(picm, ctmap, tget, tdur, tmode);
            if (debug) System.err.println("Flush picm: " + picm + ", nframe: " + ctmap.size());
            if (picm == null) System.err.println("no channels!");
            else plugin.Flush(picm);
          }
        } catch (Exception e) {
          System.err.println("oops, exception: " + e + ", picm: " + picm);
          e.printStackTrace();
          try {
            Thread.sleep(1000);
            picm.PutDataAsString(0, "error: " + e);
            plugin.Flush(picm);
          } catch (Exception ee) {
          }
          ; // no busy loop
          //				System.exit(0);		// no infinite loops
        }
      }
    }