示例#1
0
  // need a responder with objects to pipeline
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    readHandle = CCNHandle.open();
    writeHandle = CCNHandle.open();

    ContentName namespace = testHelper.getTestNamespace("pipelineTest");
    testName = new ContentName(namespace, "PipelineSegments");
    testName = VersioningProfile.addVersion(testName);
    try {
      putSegments();
    } catch (Exception e) {
      Log.info(Log.FAC_TEST, "failed to put objects for pipeline test: " + e.getMessage());
      Assert.fail();
    }
  }
示例#2
0
 /**
  * Handle a top-level namespace.
  *
  * @param namespace
  * @throws IOException
  */
 public void handleNamespace(ContentName namespace) throws IOException {
   synchronized (_interests) {
     if (_shutdown) {
       Log.info(
           Log.FAC_TEST,
           "FLOSSER: in the process of shutting down. Not handling new namespace {0}.",
           namespace);
       return;
     }
     if (_interests.containsKey(namespace)) {
       Log.fine(Log.FAC_TEST, "FLOSSER: Already handling namespace: {0}", namespace);
       return;
     }
     Log.info(Log.FAC_TEST, "FLOSSER: handling namespace: {0}", namespace);
     Interest namespaceInterest = new Interest(namespace);
     _interests.put(namespace, namespaceInterest);
     _handle.expressInterest(namespaceInterest, this);
     Set<ContentName> subNamespaces = _subInterests.get(namespace);
     if (null == subNamespaces) {
       subNamespaces = new HashSet<ContentName>();
       _subInterests.put(namespace, subNamespaces);
       Log.info(Log.FAC_TEST, "FLOSSER: setup parent namespace: {0}", namespace);
     }
   }
 }
示例#3
0
 // put segments
 private static void putSegments() throws Exception {
   ContentName segment;
   ContentObject object;
   long lastMarkerTest = 1;
   bytesWritten = 0;
   byte[] toWrite;
   for (int i = 0; i < segments; i++) {
     if (i > 0) lastMarkerTest = segments - 1;
     segment = SegmentationProfile.segmentName(testName, i);
     toWrite = ("this is segment " + i + " of " + segments).getBytes();
     bytesWritten = bytesWritten + toWrite.length;
     object =
         ContentObject.buildContentObject(
             segment,
             toWrite,
             null,
             null,
             SegmentationProfile.getSegmentNumberNameComponent(lastMarkerTest));
     if (i == 0) {
       firstDigest = object.digest();
     }
     writeHandle.put(object);
   }
   System.out.println("wrote " + bytesWritten + " bytes");
 }
示例#4
0
 @Test
 public void testFilterListenerAssertError() throws Exception {
   AssertionCCNHandle getHandle = AssertionCCNHandle.open();
   ContentName filter = testHelper.getTestNamespace("testFilterListenerAssertError");
   FilterListenerTester flt = new FilterListenerTester();
   getHandle.registerFilter(filter, flt);
   putHandle.expressInterest(new Interest(filter), new InterestListenerTester());
   getHandle.checkError(WAIT_TIME);
   ContentName pastFilter = new ContentName(filter, "pastFilter");
   putHandle.expressInterest(new Interest(pastFilter), new InterestListenerTester());
   try {
     getHandle.checkError(WAIT_TIME);
   } catch (AssertionFailedError afe) {
     return;
   }
   Assert.fail("Missed an assertion error we should have seen");
 }
示例#5
0
 @Test
 public void testFilterListenerNoError() throws Exception {
   AssertionCCNHandle getHandle = AssertionCCNHandle.open();
   ContentName filter = testHelper.getTestNamespace("testNoError");
   FilterListenerTester flt = new FilterListenerTester();
   getHandle.registerFilter(filter, flt);
   putHandle.expressInterest(new Interest(filter), new InterestListenerTester());
   getHandle.checkError(WAIT_TIME);
 }
示例#6
0
 protected void removeInterest(ContentName namespace) {
   synchronized (_interests) {
     if (!_interests.containsKey(namespace)) {
       return;
     }
     Interest interest = _interests.get(namespace);
     _handle.cancelInterest(interest, this);
     _interests.remove(namespace);
     Log.fine(Log.FAC_TEST, "Cancelled interest in {0}", namespace);
   }
 }
示例#7
0
  public void handleNamespace(ContentName namespace, ContentName parent) throws IOException {
    synchronized (_interests) {
      if (_shutdown) {
        Log.info(
            Log.FAC_TEST,
            "FLOSSER: in the process of shutting down. Not handling new subnamespace {0} under parent {1}.",
            namespace,
            parent);
        return;
      }
      if (_interests.containsKey(namespace)) {
        Log.fine(Log.FAC_TEST, "Already handling child namespace: {0}", namespace);
        return;
      }
      Log.info(
          Log.FAC_TEST,
          "FLOSSER: handling child namespace: {0} expected parent: {1}",
          namespace,
          parent);
      Interest namespaceInterest = new Interest(namespace);
      namespaceInterest.minSuffixComponents(2); // Don't reget the parent
      _interests.put(namespace, namespaceInterest);
      _handle.expressInterest(namespaceInterest, this);

      // Now we need to find a parent in the subInterest map, and reflect this namespace underneath
      // it.
      ContentName parentNamespace = parent;
      Set<ContentName> subNamespace = _subInterests.get(parentNamespace);
      while ((subNamespace == null) && (!parentNamespace.equals(ContentName.ROOT))) {
        parentNamespace = parentNamespace.parent();
        subNamespace = _subInterests.get(parentNamespace);
        Log.info(
            Log.FAC_TEST,
            "FLOSSER: initial parent not found in map, looked up {0} found in map? {1}",
            parentNamespace,
            ((null == subNamespace) ? "no" : "yes"));
      }
      if (null != subNamespace) {
        Log.info(
            Log.FAC_TEST,
            "FLOSSER: Adding subnamespace: {0} to ancestor {1}",
            namespace,
            parentNamespace);
        subNamespace.add(namespace);
      } else {
        Log.info(Log.FAC_TEST, "FLOSSER: Cannot find ancestor namespace for {0}", namespace);
        for (ContentName n : _subInterests.keySet()) {
          Log.info(Log.FAC_TEST, "FLOSSER: 		available ancestor: {0}", n);
        }
      }
    }
  }
示例#8
0
 public void stop() {
   Log.info(Log.FAC_TEST, "Stop flossing.");
   synchronized (_interests) {
     _shutdown = true;
     stopMonitoringNamespaces();
     Log.info(
         Log.FAC_TEST,
         "Stopped flossing: remaining namespaces {0} (should be 0), subnamespaces {1} (should be 0).",
         _interests.size(),
         _subInterests.size());
   }
   _handle.close();
 }
示例#9
0
文件: puttap.java 项目: YichiLL/ccnx
  public boolean go(String encFlag, String ccnName, String tapName, String readName) {
    CCNNetworkManager manager = null;
    try {
      if (encFlag.equals("0")) {
        SystemConfiguration.setDefaultEncoding(TextXMLCodec.codecName());
      } else {
        SystemConfiguration.setDefaultEncoding(BinaryXMLCodec.codecName());
      }
      File theFile = new File(readName);
      if (!theFile.exists()) {
        System.out.println("No such file: " + readName);
        usage();
        return false;
      }

      // Get writing handle
      CCNHandle handle = CCNHandle.open();
      manager = handle.getNetworkManager();
      // Set up tap so packets get written to file
      manager.setTap(tapName);

      ContentName name = ContentName.fromURI(ccnName);

      // Register standing interest so our put's will flow
      // This must be through separate handle instance so it
      // appears that there is an interest from a separate app
      // because interest from the same app as the writer will
      // not consume the data and therefore will block
      CCNHandle reader = CCNHandle.open();
      reader.expressInterest(new Interest(ccnName), this);

      // Remove automatic verification at this level. Can put it back in at
      // the tap level. CCNWriter is a segmenting writer, it makes no real
      // sense for it to return "a" ContentObject to verify.

      // Dump the file in small packets
      InputStream is = new FileInputStream(theFile);
      byte[] bytes = new byte[CHUNK_SIZE];
      int i = 0;
      CCNWriter writer = new CCNWriter(name, handle);
      writer.disableFlowControl();
      while (is.read(bytes) >= 0) {
        writer.put(ContentName.fromNative(name, new Integer(i++).toString()), bytes);
      }

      return true;

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      if (null != manager) {
        // Need to call shutdown directly on manager at this point
        manager.shutdown();
      }
    }
  }
  @Before
  public void setUp() {
    try {

      names = new ArrayList<ContentName>();

      _putHandle = CCNHandle.open();
      _getHandle = CCNHandle.open();
      _fileHandle = CCNHandle.open();

      getne = new CCNNameEnumerator(_getHandle, this);

      putne = new CCNNameEnumerator(_putHandle, this);

      helper = new CCNTestHelper(this.getClass().getName());

      _prefix = helper.getClassNamespace();

      _class = ContentName.fromNative(_prefix, "classResponder");
      _class2 = ContentName.fromNative(_prefix, "classResponder2");
      _repo = ContentName.fromNative(_prefix, "repoResponder");

      updated = false;

      putne.registerNameSpace(_prefix);
      Log.info("registering namespace prefix: {0} count: {1}", _prefix, _prefix.count());

      putNERegisterName(_class);

      addContentToRepo(_repo);

    } catch (ConfigurationException e) {
      Assert.fail("Configuration Exception when setting up test. " + e.getMessage());
    } catch (IOException e) {
      Assert.fail("IOException when setting up test. " + e.getMessage());
    }
  }
  @Test
  public void testLinkQueue() throws Exception {
    Log.info(Log.FAC_TEST, "Started testLinkQueue");

    String prefix = String.format("/repotest/test_%016X", rnd.nextLong());
    String queuenamestring = prefix + "/queue";
    String objnamestring = prefix + "/obj";
    ContentName queuename = ContentName.fromNative(queuenamestring);
    ContentName objname = ContentName.fromNative(objnamestring);
    int objsize = 1024 * 600;
    CCNHandle recvhandle = CCNHandle.getHandle();
    CCNHandle sendhandle = CCNHandle.open(recvhandle.keyManager());

    char[] buf = new char[objsize];
    Arrays.fill(buf, 'x');
    String objfill = String.valueOf(buf);

    VersioningInterest vi = new VersioningInterest(recvhandle);
    TestListener listener = new TestListener();
    vi.expressInterest(queuename, listener);

    Thread.sleep(1000);

    CCNStringObject so =
        new CCNStringObject(objname, objfill, SaveType.LOCALREPOSITORY, sendhandle);
    so.save();
    so.close();

    Link link = new Link(so.getVersionedName());
    LinkObject lo = new LinkObject(queuename, link, SaveType.LOCALREPOSITORY, sendhandle);
    lo.save();
    lo.close();

    sendhandle.close();

    // now see if we got it in the TestListener

    Assert.assertTrue(listener.cl.waitForValue(1, 60000));

    ReceivedData rd = listener.received.get(0);

    ContentObject co = rd.object;

    CCNStringObject so2 = new CCNStringObject(co.name(), recvhandle);

    Assert.assertEquals(so, so2);

    Log.info(Log.FAC_TEST, "Completed testLinkQueue");
  }
示例#12
0
 public EnumeratedNameList(ContentName namePrefix, boolean startEnumerating, CCNHandle handle)
     throws IOException {
   if (null == namePrefix) {
     throw new IllegalArgumentException("namePrefix cannot be null!");
   }
   if (null == handle) {
     try {
       handle = CCNHandle.open();
     } catch (ConfigurationException e) {
       throw new IOException(
           "ConfigurationException attempting to open a handle: " + e.getMessage());
     }
   }
   _namePrefix = namePrefix;
   if (startEnumerating) {
     _enumerating = true;
     _hasEnumerated = true;
     _enumerator = new CCNNameEnumerator(namePrefix, handle, this);
   } else {
     _enumerator = new CCNNameEnumerator(handle, this);
   }
 }
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {

    CCNTestHelper testHelper = new CCNTestHelper(GroupRecursiveKeyUpdateTestRepo.class);
    directoryBase = testHelper.getTestNamespace("testInOrder");
    userNamespace =
        GroupAccessControlProfile.userNamespaceName(UserConfiguration.defaultNamespace());
    groupNamespace =
        GroupAccessControlProfile.groupNamespaceName(UserConfiguration.defaultNamespace());
    userKeyStorePrefix = ContentName.fromNative(UserConfiguration.defaultNamespace(), "_keystore_");

    // create user identities with TestUserData
    td = new CreateUserData(userKeyStorePrefix, numberOfusers, true, "password".toCharArray());
    td.publishUserKeysToRepository(userNamespace);
    friendlyNames = td.friendlyNames().toArray(new String[0]);

    // create ACM
    handle = td.getHandleForUser(friendlyNames[1]);
    acm = new GroupAccessControlManager(directoryBase, groupNamespace, userNamespace, handle);
    acm.publishMyIdentity(
        ContentName.fromNative(userNamespace, friendlyNames[1]),
        handle.keyManager().getDefaultPublicKey());
  }
示例#14
0
 @AfterClass
 public static void tearDownAfterClass() throws Exception {
   readHandle.close();
   writeHandle.close();
   KeyManager.closeDefaultKeyManager();
 }
 @AfterClass
 public static void tearDownAfterClass() throws Exception {
   td.closeAll();
   handle.close();
 }
示例#16
0
  /**
   * This actual CCN loop to send/receive messages. Called by the UI class. This method blocks! If
   * the UI is not multi-threaded, you should start a thread to hold listen().
   *
   * <p>When shutdown() is called, listen() will exit.
   *
   * @throws ConfigurationException
   * @throws IOException
   * @throws MalformedContentNameStringException
   */
  public void listen()
      throws ConfigurationException, IOException, MalformedContentNameStringException,
          RuntimeException {

    // Also publish your keys under the chat "channel name" namespace
    if (_namespace.toString().startsWith("ccnx:/")) {
      UserConfiguration.setDefaultNamespacePrefix(_namespace.toString().substring(5));
    } else {
      UserConfiguration.setDefaultNamespacePrefix(_namespace.toString());
    }

    CCNHandle tempReadHandle = CCNHandle.getHandle();

    // Writing must be on a different handle, to enable us to read back text
    // we have
    // written when nobody else is reading.
    CCNHandle tempWriteHandle = CCNHandle.open();

    _readString = new CCNStringObject(_namespace, (String) null, SaveType.RAW, tempReadHandle);
    _readString.updateInBackground(true);

    String introduction = UserConfiguration.userName() + " has entered " + _namespace;
    _writeString = new CCNStringObject(_namespace, introduction, SaveType.RAW, tempWriteHandle);
    _writeString.save();

    // Publish the user's friendly name as a speaker if needed
    // AND if this topic doesn't already have a speaker!
    if (this.currentUser.isSpeaker()) {
      if (this.userList.getSpeaker() == null
          || this.userList.getSpeaker().equals(this.currentUser)) {
        String friendlyNameNamespaceStr = _namespaceStr + TextConf.SPEAKER_COMPONENT;
        _spkrNamespace =
            KeyProfile.keyName(
                ContentName.fromURI(friendlyNameNamespaceStr), _writeString.getContentPublisher());
        Log.info("**** Speaker Namespace is " + _spkrNamespace);

        // read the string here.....
        _readNameString =
            new CCNStringObject(_spkrNamespace, (String) null, SaveType.RAW, tempReadHandle);
        _readNameString.updateInBackground(true);

        String publishedNameStr = UserConfiguration.userName();
        Log.info("*****I am adding my own speaker name as " + publishedNameStr);
        _writeNameString =
            new CCNStringObject(_spkrNamespace, publishedNameStr, SaveType.RAW, tempWriteHandle);
        _writeNameString.save();
      } else {
        throw new RuntimeException(
            "The conference topic "
                + this.currentTopic.getTopicName()
                + " already has a Speaker ("
                + this.userList.getSpeaker().getUserName()
                + ")!!!");
      }
    } else {
      // If the current user isn't a speaker, then they can't join a conference
      // that doesn't have one (i.e. they can't create a conference)
      if (this.userList.speaker == null) {
        throw new RuntimeException(
            "The conference topic "
                + this.currentTopic.getTopicName()
                + " doesn't have a Speaker yet so it isn't accepting non-Speakers!!!");
      }
    }

    // Publish the user's friendly name under a new ContentName
    String friendlyNameNamespaceStr = _namespaceStr + TextConf.MEMBER_COMPONENT;
    _userNamespace =
        KeyProfile.keyName(
            ContentName.fromURI(friendlyNameNamespaceStr), _writeString.getContentPublisher());
    Log.info("**** Friendly Namespace is " + _userNamespace);

    // read the string here.....
    _readNameString =
        new CCNStringObject(_userNamespace, (String) null, SaveType.RAW, tempReadHandle);
    _readNameString.updateInBackground(true);

    String publishedNameStr = UserConfiguration.userName();
    Log.info("*****I am adding my own friendly name as " + publishedNameStr);
    _writeNameString =
        new CCNStringObject(_userNamespace, publishedNameStr, SaveType.RAW, tempWriteHandle);
    _writeNameString.save();

    try {
      addNameToHash(_writeNameString.getContentPublisher(), _writeNameString.string());
    } catch (IOException e) {
      System.err.println("Unable to read from " + _writeNameString + "for writing to hashMap");
      e.printStackTrace();
    }

    // Need to do synchronization for updates that come in while we're
    // processing last one.

    while (!_finished) {
      try {
        synchronized (_readString) {
          _readString.wait(CYCLE_TIME);
        }
      } catch (InterruptedException e) {
      }

      if (_readString.isSaved()) {
        Timestamp thisUpdate = _readString.getVersion();
        if ((null == _lastUpdate) || thisUpdate.after(_lastUpdate)) {
          Log.info(
              "Got an update from "
                  + _readString.getBaseName().toURIString()
                  + ": "
                  + _readString.getVersion()
                  + "..."
                  + _readString.string());
          _lastUpdate = thisUpdate;

          // lookup friendly name to display for this user.....
          User userFriendlyName =
              getFriendlyName(_readString.getContentPublisher(), tempReadHandle, tempWriteHandle);

          if (!userFriendlyName.equals(this.currentUser)) {
            messageReceived(userFriendlyName, thisUpdate, _readString.string());
          }
        }
      }
    }
  }
 @After
 public void cleanup() {
   _putHandle.close();
   _getHandle.close();
   _fileHandle.close();
 }
示例#18
0
  /** @param args */
  public void write(String[] args) {
    Log.setDefaultLevel(Level.WARNING);

    for (int i = 0; i < args.length - 2; i++) {
      if (args[i].equals("-local")) {
        CommonParameters.local = true;
      } else if (args[i].equals(("-raw"))) {
        CommonParameters.rawMode = true;
      } else {
        if (!CommonArguments.parseArguments(args, i, ccnputfile)) {
          usage();
        }
        if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1;
      }
      if (CommonParameters.startArg <= i) CommonParameters.startArg = i + 1;
    }

    if (args.length < CommonParameters.startArg + 2) {
      usage();
    }

    long starttime = System.currentTimeMillis();
    try {
      // If we get one file name, put as the specific name given.
      // If we get more than one, put underneath the first as parent.
      // Ideally want to use newVersion to get latest version. Start
      // with random version.
      ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]);

      CCNHandle handle = CCNHandle.open();

      if (args.length == (CommonParameters.startArg + 2)) {
        if (CommonParameters.verbose)
          Log.info("ccnputfile: putting file " + args[CommonParameters.startArg + 1]);

        doPut(handle, args[CommonParameters.startArg + 1], argName);
        System.out.println("Inserted file " + args[CommonParameters.startArg + 1] + ".");
        if (CommonParameters.verbose)
          System.out.println(
              "ccnputfile took: " + (System.currentTimeMillis() - starttime) + " ms");
        System.exit(0);
      } else {
        for (int i = CommonParameters.startArg + 1; i < args.length; ++i) {

          // put as child of name
          ContentName nodeName = ContentName.fromURI(argName, args[i]);

          doPut(handle, args[i], nodeName);
          // leave this one as always printing for now
          System.out.println("Inserted file " + args[i] + ".");
        }
        if (CommonParameters.verbose)
          System.out.println(
              "ccnputfile took: " + (System.currentTimeMillis() - starttime) + " ms");
        System.exit(0);
      }
    } catch (ConfigurationException e) {
      System.out.println("Configuration exception in put: " + e.getMessage());
      e.printStackTrace();
    } catch (MalformedContentNameStringException e) {
      System.out.println(
          "Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("Cannot put file. " + e.getMessage());
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      System.out.println("Cannot publish invalid key: " + e.getMessage());
      e.printStackTrace();
    }
    System.exit(1);
  }
示例#19
0
  /** @param args */
  public static void main(String[] args) {
    String extraUsage = "";
    Log.setDefaultLevel(Level.WARNING);

    try {

      int offset = 0;
      SaveType type = SaveType.REPOSITORY;

      for (int i = 0; i < args.length; i++) {
        if (i == 0 && args[0].startsWith("[")) {
          extraUsage = args[0];
          offset++;
          continue;
        } else if (args[i].equals("-h")) {
          usage(extraUsage);
          System.exit(0);
        } else if (!args[i].startsWith("-")) break;
        if (args[i].equals("-q")) {
          Log.setDefaultLevel(Level.WARNING);
          offset++;
        }

        if (args[i].equals("-r")) {
          type = SaveType.RAW;
          offset++;
        }
      }

      if (args.length - offset < 2) {
        usage(extraUsage);
        System.exit(1);
      }

      boolean hasAs = false;
      if (args.length - offset > 2) {
        if (args[offset + 2].equals("-as")) hasAs = true;
        else {
          usage(extraUsage);
          System.exit(1);
        }
      }

      ContentName linkName = ContentName.fromURI(args[offset++]);
      ContentName targetName = ContentName.fromURI(args[offset++]);

      Tuple<Integer, CCNHandle> tuple = null;

      if (hasAs) {
        tuple = CreateUserData.handleAs(args, offset);
        if (null == tuple) {
          usage(extraUsage);
          System.exit(1);
        }
      }

      // Can also use command line system properties and environment variables to
      // point this handle to the correct user.
      CCNHandle handle =
          ((null == tuple) || (null == tuple.second())) ? CCNHandle.getHandle() : tuple.second();

      LinkObject theLink = new LinkObject(linkName, new Link(targetName), type, handle);
      theLink.save();
      theLink.close();

      System.out.println("Created link: " + theLink);

      handle.close();

    } catch (Exception e) {
      handleException("Error: cannot initialize device. ", e);
      System.exit(-3);
    }
  }
示例#20
0
 /** @throws java.lang.Exception */
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
   writeHandle = CCNHandle.open();
   readHandle = CCNHandle.open();
   TARGET_POSTFIX_NAME = ContentName.fromNative(TARGET_POSTFIX);
 }
示例#21
0
 /**
  * Constructors that called handleNamespace() now throwing NullPointerException as this doesn't
  * exist yet.
  *
  * @throws ConfigurationException
  * @throws IOException
  */
 public Flosser() throws ConfigurationException, IOException {
   _handle = CCNHandle.open();
 }
示例#22
0
 @AfterClass
 public static void tearDownAfterClass() {
   writeHandle.close();
   readHandle.close();
 }
示例#23
0
 @Before
 public void setUp() throws Exception {
   putHandle = CCNHandle.open();
 }