/** {@inheritDoc} */
  @Override
  public Map<K, V> peekAll(
      @Nullable Collection<? extends K> keys,
      @Nullable GridPredicate<? super GridCacheEntry<K, V>>[] filter) {
    if (keys == null || keys.isEmpty()) return emptyMap();

    final Collection<K> skipped = new GridLeanSet<K>();

    final Map<K, V> map = peekAll0(keys, filter, skipped);

    if (map.size() + skipped.size() != keys.size()) {
      map.putAll(
          dht.peekAll(
              F.view(
                  keys,
                  new P1<K>() {
                    @Override
                    public boolean apply(K k) {
                      return !map.containsKey(k) && !skipped.contains(k);
                    }
                  }),
              filter));
    }

    return map;
  }
예제 #2
0
    /**
     * if initialtoken was specified, use that (split on comma).
     * otherwise, if num_tokens == 1, pick a token to assume half the load of the most-loaded node.
     * else choose num_tokens tokens at random
     */
    public static Collection<Token> getBootstrapTokens(final TokenMetadata metadata) throws ConfigurationException
    {
        Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();
        // if user specified tokens, use those
        if (initialTokens.size() > 0)
        {
            logger.debug("tokens manually specified as {}",  initialTokens);
            List<Token> tokens = new ArrayList<Token>(initialTokens.size());
            for (String tokenString : initialTokens)
            {
                Token token = StorageService.getPartitioner().getTokenFactory().fromString(tokenString);
                if (metadata.getEndpoint(token) != null)
                    throw new ConfigurationException("Bootstrapping to existing token " + tokenString + " is not allowed (decommission/removenode the old node first).");
                tokens.add(token);
            }
            return tokens;
        }

        int numTokens = DatabaseDescriptor.getNumTokens();
        if (numTokens < 1)
            throw new ConfigurationException("num_tokens must be >= 1");

        if (numTokens == 1)
            logger.warn("Picking random token for a single vnode.  You should probably add more vnodes; failing that, you should probably specify the token manually");

        return getRandomTokens(metadata, numTokens);
    }
예제 #3
0
 public static void main(String[] args) {
   Collection c = new ArrayList();
   // 添加元素
   c.add("孙悟空");
   // 虽然集合里不能放基本类型的值,但Java支持自动装箱
   c.add(6);
   System.out.println("c集合的元素个数为:" + c.size());
   // 删除指定元素
   c.remove(6);
   System.out.println("c集合的元素个数为:" + c.size());
   // 判断是否包含指定字符串
   System.out.println("c集合的是否包含\"孙悟空\"字符串:" + c.contains("孙悟空"));
   c.add("轻量级Java EE企业应用实战");
   System.out.println("c集合的元素:" + c);
   Collection books = new HashSet();
   books.add("轻量级Java EE企业应用实战");
   books.add("疯狂Java讲义");
   System.out.println("c集合是否完全包含books集合?" + c.containsAll(books));
   // 用c集合减去books集合里的元素
   c.removeAll(books);
   System.out.println("c集合的元素:" + c);
   // 删除c集合里所有元素
   c.clear();
   System.out.println("c集合的元素:" + c);
   // books集合里只剩下c集合里也包含的元素
   books.retainAll(c);
   System.out.println("books集合的元素:" + books);
 }
예제 #4
0
  /**
   * Deletes a very specific mapping from the replica catalog. The LFN must be matches, the PFN, and
   * all PFN attributes specified in the replica catalog entry. More than one entry could
   * theoretically be removed. Upon removal of an entry, all attributes associated with the PFN also
   * evaporate (cascading deletion).
   *
   * @param lfn is the logical directory in the tuple.
   * @param tuple is a description of the PFN and its attributes.
   * @return the number of removed entries, either 0 or 1.
   */
  public int delete(String lfn, ReplicaCatalogEntry tuple) {
    int result = 0;
    if (lfn == null || tuple == null) {
      return result;
    }

    Collection c = (Collection) mLFNMap.get(lfn);
    if (c == null) {
      return result;
    }

    List l = new ArrayList();
    for (Iterator i = c.iterator(); i.hasNext(); ) {
      ReplicaCatalogEntry rce = (ReplicaCatalogEntry) i.next();
      if (!matchMe(rce, tuple)) {
        l.add(rce);
      }
    }

    // anything removed?
    if (l.size() != c.size()) {
      result = c.size() - l.size();
      mLFNMap.put(lfn, l);
    }

    // done
    return result;
  }
예제 #5
0
 public void use(Pagina r) {
   Collection<Pagina> sub = new LinkedList<Pagina>(), cur = new LinkedList<Pagina>();
   cons(r, sub);
   cons(this.cur, cur);
   if (sub.size() > 0) {
     this.cur = r;
     curoff = 0;
   } else if (r == bk) {
     this.cur = paginafor(this.cur.act().parent);
     curoff = 0;
   } else if (r == next) {
     int off = gsz.x * gsz.y - 2;
     if ((curoff + off) >= cur.size()) curoff = 0;
     else curoff += off;
   } else {
     String[] ad = r.act().ad;
     if ((ad == null) || (ad.length < 1)) {
       return;
     }
     if (ad[0].equals("@")) {
       usecustom(ad);
     } else {
       wdgmsg("act", (Object[]) ad);
     }
     this.cur = null;
     curoff = 0;
   }
   updlayout();
 }
  /*
   * (non-Javadoc)
   * @see de.hpi.bpt.hypergraph.abs.IDirectedHyperGraph#getEdgesWithSourcesAndTargets(java.util.Collection, java.util.Collection)
   */
  public Collection<E> getEdgesWithSourcesAndTargets(Collection<V> ss, Collection<V> ts) {
    Collection<E> result = new ArrayList<E>();
    if (ss == null && ts == null) return result;
    if (ss.size() == 0 && ts.size() == 0) return result;

    if (ss != null && ss.size() > 0) {
      V v = ss.iterator().next();
      Collection<E> es = this.getEdgesWithSource(v);
      if (es == null) return result;
      Iterator<E> i = es.iterator();
      while (i.hasNext()) {
        E e = i.next();
        if (e.hasSources(ss) && e.hasTargets(ts)) result.add(e);
      }
    } else if (ts != null && ts.size() > 0) {
      V v = ts.iterator().next();
      Collection<E> es = this.getEdgesWithTarget(v);
      if (es == null) return result;
      Iterator<E> i = es.iterator();
      while (i.hasNext()) {
        E e = i.next();
        if (e.hasSources(ss) && e.hasTargets(ts)) result.add(e);
      }
    }

    return result;
  }
  /** {@inheritDoc} */
  @Override
  public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr)
      throws IgniteCheckedException {
    super.finishUnmarshal(ctx, ldr);

    if (writes != null) unmarshalTx(writes, false, ctx, ldr);

    if (reads != null) unmarshalTx(reads, false, ctx, ldr);

    if (grpLockKeyBytes != null && grpLockKey == null)
      grpLockKey = ctx.marshaller().unmarshal(grpLockKeyBytes, ldr);

    if (dhtVerKeys != null && dhtVers == null) {
      assert dhtVerVals != null;
      assert dhtVerKeys.size() == dhtVerVals.size();

      Iterator<IgniteTxKey> keyIt = dhtVerKeys.iterator();
      Iterator<GridCacheVersion> verIt = dhtVerVals.iterator();

      dhtVers = U.newHashMap(dhtVerKeys.size());

      while (keyIt.hasNext()) {
        IgniteTxKey key = keyIt.next();

        key.finishUnmarshal(ctx.cacheContext(key.cacheId()), ldr);

        dhtVers.put(key, verIt.next());
      }
    }

    if (txNodesBytes != null) txNodes = ctx.marshaller().unmarshal(txNodesBytes, ldr);
  }
예제 #8
0
  /**
   * Clear the current list and set it to the contents of the <code>Collection</code>. object.
   *
   * @param collection The collection to use.
   */
  void clearAndSet(Collection collection) {
    Attribute[] old = elementData;
    int oldSize = size;

    elementData = null;
    size = 0;

    if ((collection != null) && (collection.size() != 0)) {
      ensureCapacity(collection.size());
      try {
        addAll(0, collection);
      } catch (RuntimeException exception) {
        elementData = old;
        size = oldSize;
        throw exception;
      }
    }

    if (old != null) {
      for (int i = 0; i < oldSize; i++) {
        Attribute attribute = old[i];
        attribute.setParent(null);
      }
    }
    modCount++;
  }
예제 #9
0
  /**
   * Inserts the specified collecton at the specified position in this list. Shifts the attribute
   * currently at that position (if any) and any subsequent attributes to the right (adds one to
   * their indices).
   *
   * @param index The offset to start adding the data in the collection
   * @param collection The collection to insert into the list.
   * @return <code>true</code> if the list was modified as a result of the add. throws
   *     IndexOutOfBoundsException if index < 0 || index > size()
   */
  public boolean addAll(int index, Collection collection) {
    if (index < 0 || index > size) {
      throw new IndexOutOfBoundsException("Index: " + index + " Size: " + size());
    }

    if ((collection == null) || (collection.size() == 0)) {
      return false;
    }
    ensureCapacity(size() + collection.size());

    int count = 0;

    try {
      Iterator i = collection.iterator();
      while (i.hasNext()) {
        Object obj = i.next();
        add(index + count, obj);
        count++;
      }
    } catch (RuntimeException exception) {
      for (int i = 0; i < count; i++) {
        remove(index);
      }
      throw exception;
    }

    return true;
  }
예제 #10
0
  public void testRegularAndOOBUnicasts2() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(
        discard, ProtocolStack.BELOW, (Class<? extends Protocol>[]) Util.getUnicastProtocols());

    Address dest = b.getAddress();
    Message m1 = new Message(dest, 1);
    Message m2 = new Message(dest, 2).setFlag(Message.Flag.OOB);
    Message m3 = new Message(dest, 3).setFlag(Message.Flag.OOB);
    Message m4 = new Message(dest, 4);

    MyReceiver receiver = new MyReceiver("B");
    b.setReceiver(receiver);
    a.send(m1);

    discard.setDropDownUnicasts(2);
    a.send(m2); // dropped
    a.send(m3); // dropped
    a.send(m4);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 4 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }
    System.out.println("list = " + list);
    assert list.size() == 4 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3) && list.contains(4);
  }
예제 #11
0
  public static void testDetermineMergeParticipantsAndMergeCoords4() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");
    org.jgroups.util.UUID.add(d, "D");

    View v1 = View.create(a, 1, a, b);
    View v2 = View.create(c, 1, c, d);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v1);
    map.put(d, v2);

    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 3;
    assert merge_participants.contains(a)
        && merge_participants.contains(c)
        && merge_participants.contains(d);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 2;
    assert merge_coords.contains(a) && merge_coords.contains(c);
  }
예제 #12
0
  /**
   * Restart of the application server :
   *
   * <p>All running services are stopped. LookupManager is flushed.
   *
   * <p>Client code that started us should notice the special return value and restart us.
   */
  protected final void doExecute(AdminCommandContext context) {
    try {
      // unfortunately we can't rely on constructors with HK2...
      if (registry == null)
        throw new NullPointerException(
            new LocalStringsImpl(getClass())
                .get("restart.server.internalError", "registry was not set"));

      init(context);

      if (!verbose) {
        // do it now while we still have the Logging service running...
        reincarnate();
      }
      // else we just return a special int from System.exit()

      Collection<Module> modules = registry.getModules("com.sun.enterprise.osgi-adapter");
      if (modules.size() == 1) {
        final Module mgmtAgentModule = modules.iterator().next();
        mgmtAgentModule.stop();
      } else
        context.getLogger().warning(strings.get("restart.server.badNumModules", modules.size()));

    } catch (Exception e) {
      context.getLogger().severe(strings.get("restart.server.failure", e));
    }

    int ret = RESTART_NORMAL;

    if (debug != null) ret = debug ? RESTART_DEBUG_ON : RESTART_DEBUG_OFF;

    System.exit(ret);
  }
예제 #13
0
  public Column get_column(String table, String key, ColumnPath column_path, int consistency_level)
      throws InvalidRequestException, NotFoundException {
    if (logger.isDebugEnabled()) logger.debug("get_column");
    ThriftValidation.validateColumnPath(table, column_path);

    QueryPath path = new QueryPath(column_path.column_family, column_path.super_column);
    ColumnFamily cfamily =
        readColumnFamily(
            new SliceByNamesReadCommand(table, key, path, Arrays.asList(column_path.column)),
            consistency_level);
    // TODO can we leverage getSlice here and just check that it returns one column?
    if (cfamily == null) {
      throw new NotFoundException();
    }
    Collection<IColumn> columns = null;
    if (column_path.super_column != null) {
      IColumn column = cfamily.getColumn(column_path.super_column);
      if (column != null) {
        columns = column.getSubColumns();
      }
    } else {
      columns = cfamily.getSortedColumns();
    }
    if (columns == null || columns.size() == 0) {
      throw new NotFoundException();
    }

    assert columns.size() == 1;
    IColumn column = columns.iterator().next();
    if (column.isMarkedForDelete()) {
      throw new NotFoundException();
    }

    return new Column(column.name(), column.value(), column.timestamp());
  }
  private List<HighlightInfo> getHighlights() {
    if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) {
      return Collections.emptyList();
    }
    Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>();
    for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) {
      existingMarkupTooltips.add(
          Pair.create(
              highlighter.getErrorStripeTooltip(),
              new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset())));
    }

    List<HighlightInfo> result =
        new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size());
    for (TextRange range : myReadAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips),
          result);
    }
    for (TextRange range : myWriteAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips),
          result);
    }
    return result;
  }
 public List<ShelvedChangeList> importChangeLists(
     final Collection<VirtualFile> files, final Consumer<VcsException> exceptionConsumer) {
   final List<ShelvedChangeList> result = new ArrayList<ShelvedChangeList>(files.size());
   try {
     final FilesProgress filesProgress = new FilesProgress(files.size(), "Processing ");
     for (VirtualFile file : files) {
       filesProgress.updateIndicator(file);
       final String description = file.getNameWithoutExtension().replace('_', ' ');
       final File patchPath = getPatchPath(description);
       final ShelvedChangeList list =
           new ShelvedChangeList(
               patchPath.getPath(),
               description,
               new SmartList<ShelvedBinaryFile>(),
               file.getTimeStamp());
       try {
         final List<TextFilePatch> patchesList =
             loadPatches(myProject, file.getPath(), new CommitContext());
         if (!patchesList.isEmpty()) {
           FileUtil.copy(new File(file.getPath()), patchPath);
           // add only if ok to read patch
           myShelvedChangeLists.add(list);
           result.add(list);
         }
       } catch (IOException e) {
         exceptionConsumer.consume(new VcsException(e));
       } catch (PatchSyntaxException e) {
         exceptionConsumer.consume(new VcsException(e));
       }
     }
   } finally {
     notifyStateChanged();
   }
   return result;
 }
예제 #16
0
  private boolean confirmClose(String action, Collection modifiedLayers) {
    if (modifiedLayers.isEmpty()) {
      return true;
    }

    JOptionPane pane =
        new JOptionPane(
            StringUtil.split(
                modifiedLayers.size()
                    + " dataset"
                    + StringUtil.s(modifiedLayers.size())
                    + " "
                    + ((modifiedLayers.size() > 1) ? "have" : "has")
                    + " been modified ("
                    + ((modifiedLayers.size() > 3) ? "e.g. " : "")
                    + StringUtil.toCommaDelimitedString(
                        new ArrayList(modifiedLayers)
                            .subList(0, Math.min(3, modifiedLayers.size())))
                    + "). Continue?",
                80),
            JOptionPane.WARNING_MESSAGE);
    pane.setOptions(new String[] {action, "Cancel"});
    pane.createDialog(this, AppContext.getMessage("GeopistaName")).setVisible(true);

    return pane.getValue().equals(action);
  }
예제 #17
0
  public SuperColumn get_super_column(
      String table, String key, SuperColumnPath super_column_path, int consistency_level)
      throws InvalidRequestException, NotFoundException {
    if (logger.isDebugEnabled()) logger.debug("get_superColumn");
    ThriftValidation.validateSuperColumnPath(table, super_column_path);

    ColumnFamily cfamily =
        readColumnFamily(
            new SliceByNamesReadCommand(
                table,
                key,
                new QueryPath(super_column_path.column_family),
                Arrays.asList(super_column_path.super_column)),
            consistency_level);
    if (cfamily == null) {
      throw new NotFoundException();
    }
    Collection<IColumn> columns = cfamily.getSortedColumns();
    if (columns == null || columns.size() == 0) {
      throw new NotFoundException();
    }

    assert columns.size() == 1;
    IColumn column = columns.iterator().next();
    if (column.getSubColumns().size() == 0) {
      throw new NotFoundException();
    }

    return new SuperColumn(column.name(), thriftifyColumns(column.getSubColumns()));
  }
예제 #18
0
  /**
   * @param in Object input.
   * @return Read collection.
   * @throws IOException If failed.
   * @throws ClassNotFoundException If failed.
   */
  private Collection<Object> readFieldsCollection(ObjectInput in)
      throws IOException, ClassNotFoundException {
    assert fields;

    int size = in.readInt();

    if (size == -1) return null;

    Collection<Object> res = new ArrayList<>(size);

    for (int i = 0; i < size; i++) {
      int size0 = in.readInt();

      Collection<Object> col = new ArrayList<>(size0);

      for (int j = 0; j < size0; j++) col.add(in.readObject());

      assert col.size() == size0;

      res.add(col);
    }

    assert res.size() == size;

    return res;
  }
예제 #19
0
  /**
   * add a collection
   *
   * @param index
   * @param c a collection to add
   * @return true if the collection was modified
   */
  public boolean addAll(int index, Collection c) {
    if (c != null) {
      if (this.collection == null) this.collection = this.initCollection();
      boolean modified = false;
      int i = index;
      for (Iterator it = c.iterator(); it.hasNext(); ) {
        Object object = it.next();
        if (this.itemAllowed(object)) {
          this.add(i++, object);
        }
      }
      /* fire event */
      int[] positions = new int[c.size()];
      for (int j = 0; j < c.size(); j++) positions[j] = j + index;
      this.firePropertyChange(
          new ContentChangeEvent(
              this,
              PROPERTY_CONTENT,
              ContentChangeEvent.ADD,
              positions,
              (AbstractSibType[]) c.toArray(new AbstractSibType[] {})));

      return modified;
    }
    return false;
  }
예제 #20
0
 @NotNull
 private Set<VcsRef> readBranches(@NotNull GitRepository repository) {
   StopWatch sw = StopWatch.start("readBranches in " + repository.getRoot().getName());
   VirtualFile root = repository.getRoot();
   repository.update();
   Collection<GitLocalBranch> localBranches = repository.getBranches().getLocalBranches();
   Collection<GitRemoteBranch> remoteBranches = repository.getBranches().getRemoteBranches();
   Set<VcsRef> refs = new THashSet<VcsRef>(localBranches.size() + remoteBranches.size());
   for (GitLocalBranch localBranch : localBranches) {
     refs.add(
         myVcsObjectsFactory.createRef(
             localBranch.getHash(), localBranch.getName(), GitRefManager.LOCAL_BRANCH, root));
   }
   for (GitRemoteBranch remoteBranch : remoteBranches) {
     refs.add(
         myVcsObjectsFactory.createRef(
             remoteBranch.getHash(),
             remoteBranch.getNameForLocalOperations(),
             GitRefManager.REMOTE_BRANCH,
             root));
   }
   String currentRevision = repository.getCurrentRevision();
   if (currentRevision != null) { // null => fresh repository
     refs.add(
         myVcsObjectsFactory.createRef(
             HashImpl.build(currentRevision), "HEAD", GitRefManager.HEAD, root));
   }
   sw.report();
   return refs;
 }
 private void growCollectionIfNecessary(final Collection collection, final int index) {
   if (index >= collection.size() && index < this.autoGrowCollectionLimit) {
     for (int i = collection.size(); i <= index; i++) {
       collection.add(null);
     }
   }
 }
예제 #22
0
  private void handleNewExternalTransactionsInt(Collection<TransactionEx> transactions)
      throws WapiException {
    // Transform and put into two arrays with matching indexes
    ArrayList<TransactionEx> texArray = new ArrayList<TransactionEx>(transactions.size());
    ArrayList<Transaction> txArray = new ArrayList<Transaction>(transactions.size());
    for (TransactionEx tex : transactions) {
      try {
        txArray.add(Transaction.fromByteReader(new ByteReader(tex.binary)));
        texArray.add(tex);
      } catch (TransactionParsingException e) {
        // We hit a transaction that we cannot parse. Log but otherwise ignore it
        _logger.logError("Received transaction that we cannot parse: " + tex.txid.toString());
        continue;
      }
    }

    // Grab and handle parent transactions
    fetchStoreAndValidateParentOutputs(txArray);

    // Store transaction locally
    for (int i = 0; i < txArray.size(); i++) {
      _backing.putTransaction(texArray.get(i));
      onNewTransaction(texArray.get(i), txArray.get(i));
    }
  }
예제 #23
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 for unicast messages */
  public void testOOBUnicastMessageLoss() throws Exception {
    MyReceiver receiver = new MySleepingReceiver("C2", 1000);
    b.setReceiver(receiver);

    a.getProtocolStack().getTransport().setOOBRejectionPolicy("discard");

    final int NUM = 10;
    final Address dest = b.getAddress();
    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(dest, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }

    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      // sendStableMessages(c1,c2); // not needed for unicasts !
    }

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
예제 #24
0
  /**
   * Tests sending 1, 2 (OOB) and 3, where they are received in the order 1, 3, 2. Message 3 should
   * not get delivered until message 4 is received (http://jira.jboss.com/jira/browse/JGRP-780)
   */
  public void testRegularAndOOBUnicasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, UNICAST.class, UNICAST2.class);

    Address dest = b.getAddress();
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownUnicasts(1);
    a.send(m2);
    a.send(m3);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 3 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }

    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
예제 #25
0
  /** Tests https://jira.jboss.org/jira/browse/JGRP-1079 */
  public void testOOBMessageLoss() throws Exception {
    Util.close(b); // we only need 1 channel
    MyReceiver receiver = new MySleepingReceiver("C1", 1000);
    a.setReceiver(receiver);

    TP transport = a.getProtocolStack().getTransport();
    transport.setOOBRejectionPolicy("discard");

    final int NUM = 10;

    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(null, null, i);
      msg.setFlag(Message.OOB);
      a.send(msg);
    }
    STABLE stable = (STABLE) a.getProtocolStack().findProtocol(STABLE.class);
    if (stable != null) stable.runMessageGarbageCollection();
    Collection<Integer> msgs = receiver.getMsgs();

    for (int i = 0; i < 20; i++) {
      if (msgs.size() == NUM) break;
      Util.sleep(1000);
      sendStableMessages(a, b);
    }

    System.out.println("msgs = " + Util.print(msgs));

    assert msgs.size() == NUM
        : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs);
    for (int i = 1; i <= NUM; i++) {
      assert msgs.contains(i);
    }
  }
예제 #26
0
  public void testRegularAndOOBMulticasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, NAKACK2.class);
    a.setDiscardOwnMessages(true);

    Address dest = null; // send to all
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownMulticasts(1);
    a.send(m2);
    a.send(m3);

    Util.sleep(500);
    Collection<Integer> list = receiver.getMsgs();
    for (int i = 0; i < 10; i++) {
      System.out.println("list = " + list);
      if (list.size() == 3) break;
      Util.sleep(1000); // give the asynchronous msgs some time to be received
      sendStableMessages(a, b);
    }
    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
  /** @throws Exception If failed. */
  public void testCreateFileColocated() throws Exception {
    GridGgfsPath path = new GridGgfsPath("/colocated");

    UUID uuid = UUID.randomUUID();

    GridUuid affKey;

    long idx = 0;

    while (true) {
      affKey = new GridUuid(uuid, idx);

      if (grid(0).mapKeyToNode(DATA_CACHE_NAME, affKey).id().equals(grid(0).localNode().id()))
        break;

      idx++;
    }

    try (GridGgfsOutputStream out = fs.create(path, 1024, true, affKey, 0, 1024, null)) {
      // Write 5M, should be enough to test distribution.
      for (int i = 0; i < 15; i++) out.write(new byte[1024 * 1024]);
    }

    GridGgfsFile info = fs.info(path);

    Collection<GridGgfsBlockLocation> affNodes = fs.affinity(path, 0, info.length());

    assertEquals(1, affNodes.size());
    Collection<UUID> nodeIds = F.first(affNodes).nodeIds();

    assertEquals(1, nodeIds.size());
    assertEquals(grid(0).localNode().id(), F.first(nodeIds));
  }
 @NotNull
 private static String toVfString(@NotNull Collection<VirtualFile> list) {
   List<VirtualFile> sub = new ArrayList<VirtualFile>(list).subList(0, Math.min(list.size(), 100));
   return list.size()
       + " files: "
       + StringUtil.join(sub, file -> file.getName(), ", ")
       + (list.size() == sub.size() ? "" : "...");
 }
예제 #29
0
 public boolean testSizeAdd() {
   description = "add increases size by 1 if not already in";
   Object e = new Object();
   precondition = new Boolean(!c.contains(e));
   int s = c.size();
   c.add(e);
   return c.size() == s + 1;
 }
예제 #30
0
 public AbstractMove getBestMove() {
   Collection moves = getBestMoves();
   Random generator = new Random(System.currentTimeMillis());
   int random = 0;
   if (moves.size() > 0) random = generator.nextInt(moves.size());
   Iterator moveIterator = moves.iterator();
   for (int i = 0; i < random; i++) moveIterator.next();
   return (AbstractMove) moveIterator.next();
 }