Example #1
1
  protected Collection<TransactionOutputEx> getSpendableOutputs() {
    Collection<TransactionOutputEx> list = _backing.getAllUnspentOutputs();

    // Prune confirmed outputs for coinbase outputs that are not old enough
    // for spending. Also prune unconfirmed receiving coins except for change
    int blockChainHeight = getBlockChainHeight();
    Iterator<TransactionOutputEx> it = list.iterator();
    while (it.hasNext()) {
      TransactionOutputEx output = it.next();
      if (output.isCoinBase) {
        int confirmations = blockChainHeight - output.height;
        if (confirmations < COINBASE_MIN_CONFIRMATIONS) {
          it.remove();
          continue;
        }
      }
      // Unless we allow zero confirmation spending we prune all unconfirmed outputs sent from
      // foreign addresses
      if (!_allowZeroConfSpending) {
        if (output.height == -1 && !isFromMe(output.outPoint.hash)) {
          // Prune receiving coins that is not change sent to ourselves
          it.remove();
        }
      }
    }
    return list;
  }
  public static void main(String[] args) {
    int n = 10000;
    if (args.length > 0) n = Integer.parseInt(args[0]);

    List<Integer> sorted = new ArrayList<Integer>(n);
    for (int i = 0; i < n; i++) sorted.add(new Integer(i));
    List<Integer> shuffled = new ArrayList<Integer>(sorted);
    Collections.shuffle(shuffled);

    Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator());
    for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next());

    List<Integer> recons = new ArrayList<Integer>();
    while (!pq.isEmpty()) recons.add(pq.remove());
    if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed");

    recons.clear();
    pq = new PriorityQueue<Integer>(shuffled);
    while (!pq.isEmpty()) recons.add(pq.remove());
    if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed");

    // Remove all odd elements from queue
    pq = new PriorityQueue<Integer>(shuffled);
    for (Iterator<Integer> i = pq.iterator(); i.hasNext(); )
      if ((i.next().intValue() & 1) == 1) i.remove();
    recons.clear();
    while (!pq.isEmpty()) recons.add(pq.remove());

    for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); )
      if ((i.next().intValue() & 1) == 1) i.remove();

    if (!recons.equals(sorted)) throw new RuntimeException("Iterator remove test failed.");
  }
  @Override
  public void refresh() {
    int tierfound = 2;
    Iterator<IConductor> it = this.conductors.iterator();
    while (it.hasNext()) {
      IConductor conductor = it.next();

      if (conductor == null) {
        it.remove();
        continue;
      }

      TileEntity tile = (TileEntity) conductor;
      World world = tile.getWorldObj();
      // Remove any conductors in unloaded chunks
      if (tile.isInvalid() || world == null) {
        it.remove();
        continue;
      }

      if (conductor.getTierGC() < 2) {
        tierfound = 1;
      }

      if (conductor.getNetwork() != this) {
        conductor.setNetwork(this);
        conductor.onNetworkChanged();
      }
    }

    // This will set the network tier to 2 if all the conductors are tier 2
    this.networkTierGC = tierfound;
  }
Example #4
1
  public static Connection getConnection() {

    Iterator<ConnectionWrapper> poolIter = connectionPool.iterator();
    while (poolIter.hasNext()) {
      ConnectionWrapper conn = poolIter.next();
      try {
        if (conn == null || conn.isReallyClosed()) {
          poolIter.remove();
        } else if (!conn.isClosed()) {
          return conn;
        }
      } catch (SQLException e) {
        log.error("Bad connection", e);
        poolIter.remove();
      }
    }

    // No valid connections
    ConnectionWrapper conn = createConnection();
    if (conn != null) {
      connectionPool.add(conn);
      log.info("Connection pool size: " + connectionPool.size());
    }
    return conn;
  }
Example #5
0
  /**
   * @param <H> is something that handles CallableDescriptor inside
   * @return
   */
  @NotNull
  public static <H> Collection<H> extractMembersOverridableInBothWays(
      @NotNull H overrider,
      @NotNull @Mutable Collection<H> extractFrom,
      @NotNull Function1<H, CallableDescriptor> descriptorByHandle,
      @NotNull Function1<H, Unit> onConflict) {
    Collection<H> overridable = new ArrayList<H>();
    overridable.add(overrider);
    CallableDescriptor overriderDescriptor = descriptorByHandle.invoke(overrider);
    for (Iterator<H> iterator = extractFrom.iterator(); iterator.hasNext(); ) {
      H candidate = iterator.next();
      CallableDescriptor candidateDescriptor = descriptorByHandle.invoke(candidate);
      if (overrider == candidate) {
        iterator.remove();
        continue;
      }

      OverrideCompatibilityInfo.Result finalResult =
          getBothWaysOverridability(overriderDescriptor, candidateDescriptor);

      if (finalResult == OVERRIDABLE) {
        overridable.add(candidate);
        iterator.remove();
      } else if (finalResult == CONFLICT) {
        onConflict.invoke(candidate);
        iterator.remove();
      }
    }
    return overridable;
  }
  @Override
  public void run() {
    while (true) {
      try {
        synchronized (_pendingRequest) {
          Iterator changes = _pendingRequest.iterator();
          while (changes.hasNext()) {
            ChangeRequest change = (ChangeRequest) changes.next();
            if (!processPendingRequest(change)) break;
            changes.remove();
          }
        }

        // wait events from selected channels
        _selector.select();

        Iterator selectedKeys = _selector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
          SelectionKey key = (SelectionKey) selectedKeys.next();
          selectedKeys.remove();

          if (!key.isValid()) {
            continue;
          }

          processSelect(key);
        }
      } catch (Exception e) {
        logger.warning(Util.getErrorMessage(e));
      }
    }
  }
Example #7
0
  /**
   * <<<<<<< HEAD ���ߵ�valueֵ���й��� ======= 按边的value值进行过滤 >>>>>>> seuvislogwws/master
   *
   * @param filter
   * @return
   */
  public SankeyGraph FilterByEdgeValue(double filter) {
    Set<Integer> nodeset = new HashSet<Integer>();
    Iterator<? extends Edge> iterator_links = this.links.iterator();
    while (iterator_links.hasNext()) {
      Edge edge = iterator_links.next();
      double value = ((StreamEdge) edge).getValue();
      if (value < filter) iterator_links.remove(); // �Ƴ��
      else {
        nodeset.add(edge.getSource());
        nodeset.add(edge.getTarget());
      }
    }
    Iterator<? extends Node> iterator_nodes = this.nodes.iterator();
    while (iterator_nodes.hasNext()) {
      Node node = iterator_nodes.next();

      if (!nodeset.contains(node.getName())) { // ����nodes��
        iterator_nodes.remove();
      }
    }
    // System.out.println( "���˺�nodes�Ĵ�С�� "+this.nodes.size());
    // �����˹���json����ٴΰ�node��name��0��ʼ�ź�
    int index = 0;
    for (Node n : this.nodes) {
      int old_name = n.getName();
      int new_name = index++;
      n.setName(new_name);

      for (Edge e : this.links) {
        if (e.getSource() == old_name) e.setSource(new_name);
        if (e.getTarget() == old_name) e.setTarget(new_name);
      }
    }
    return this;
  }
  /**
   * Removes given value from the set and returns the instance stored in the set or {@code null} if
   * value was not found.
   *
   * @param val Value to remove.
   * @return The instance that was stored in the set or {@code null}.
   */
  @Nullable
  public V removex(V val) {
    A.notNull(val, "val");

    if (comp == null || !strict) {
      for (Iterator<V> it = vals.iterator(); it.hasNext(); ) {
        V v = it.next();

        if (v.equals(val)) {
          it.remove();

          return v;
        }
      }

      return null;
    }

    assert comp != null && strict;

    for (Iterator<V> it = vals.iterator(); it.hasNext(); ) {
      V v = it.next();

      // Prefer equals to comparator.
      if (v.equals(val)) {
        it.remove();

        return v;
      }

      if (comp.compare(v, val) > 0) break;
    }

    return null;
  }
Example #9
0
 private void importActiveRules(RulesDao rulesDao, RulesProfile profile) {
   for (Iterator<ActiveRule> iar = profile.getActiveRules(true).iterator(); iar.hasNext(); ) {
     ActiveRule activeRule = iar.next();
     Rule unMarshalledRule = activeRule.getRule();
     Rule matchingRuleInDb =
         rulesDao.getRuleByKey(unMarshalledRule.getRepositoryKey(), unMarshalledRule.getKey());
     if (matchingRuleInDb == null) {
       LoggerFactory.getLogger(getClass())
           .error(
               "Unable to find active rule "
                   + unMarshalledRule.getRepositoryKey()
                   + ":"
                   + unMarshalledRule.getKey());
       iar.remove();
       continue;
     }
     activeRule.setRule(matchingRuleInDb);
     activeRule.setRulesProfile(profile);
     activeRule.getActiveRuleParams();
     for (Iterator<ActiveRuleParam> irp = activeRule.getActiveRuleParams().iterator();
         irp.hasNext(); ) {
       ActiveRuleParam activeRuleParam = irp.next();
       RuleParam unMarshalledRP = activeRuleParam.getRuleParam();
       RuleParam matchingRPInDb = rulesDao.getRuleParam(matchingRuleInDb, unMarshalledRP.getKey());
       if (matchingRPInDb == null) {
         LoggerFactory.getLogger(getClass())
             .error("Unable to find active rule parameter " + unMarshalledRP.getKey());
         irp.remove();
         continue;
       }
       activeRuleParam.setActiveRule(activeRule);
       activeRuleParam.setRuleParam(matchingRPInDb);
     }
   }
 }
Example #10
0
File: ZCM.java Project: ZeroCM/zcm
  /**
   * Remove this particular regex/subscriber pair (UNTESTED AND API MAY CHANGE). If regex is null,
   * all subscriptions for 'sub' are cancelled. If subscriber is null, any previous subscriptions
   * matching the regular expression will be cancelled. If both 'sub' and 'regex' are null, all
   * subscriptions will be cancelled.
   */
  public void unsubscribe(String regex, ZCMSubscriber sub) {
    if (this.closed) throw new IllegalStateException();

    synchronized (this) {
      for (Provider p : providers) p.unsubscribe(regex);
    }

    // TODO: providers don't seem to use anything beyond first channel

    synchronized (subscriptions) {

      // Find and remove subscriber from list
      for (Iterator<SubscriptionRecord> it = subscriptions.iterator(); it.hasNext(); ) {
        SubscriptionRecord sr = it.next();

        if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
          it.remove();
        }
      }

      // Find and remove subscriber from map
      for (String channel : subscriptionsMap.keySet()) {
        for (Iterator<SubscriptionRecord> it = subscriptionsMap.get(channel).iterator();
            it.hasNext(); ) {
          SubscriptionRecord sr = it.next();

          if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
            it.remove();
          }
        }
      }
    }
  }
  public void addPrimaryKeyColumn(String columnName) {
    boolean found = false;
    // first search base columns
    Iterator<IntrospectedColumn> iter = baseColumns.iterator();
    while (iter.hasNext()) {
      IntrospectedColumn introspectedColumn = iter.next();
      if (introspectedColumn.getActualColumnName().equals(columnName)) {
        primaryKeyColumns.add(introspectedColumn);
        iter.remove();
        found = true;
        break;
      }
    }

    // search blob columns in the weird event that a blob is the primary key
    if (!found) {
      iter = blobColumns.iterator();
      while (iter.hasNext()) {
        IntrospectedColumn introspectedColumn = iter.next();
        if (introspectedColumn.getActualColumnName().equals(columnName)) {
          primaryKeyColumns.add(introspectedColumn);
          iter.remove();
          found = true;
          break;
        }
      }
    }
  }
Example #12
0
 @NotNull
 public static List<VcsDirectoryMapping> addMapping(
     @NotNull List<VcsDirectoryMapping> existingMappings,
     @NotNull String path,
     @NotNull String vcs) {
   List<VcsDirectoryMapping> mappings = new ArrayList<VcsDirectoryMapping>(existingMappings);
   for (Iterator<VcsDirectoryMapping> iterator = mappings.iterator(); iterator.hasNext(); ) {
     VcsDirectoryMapping mapping = iterator.next();
     if (mapping.isDefaultMapping() && StringUtil.isEmptyOrSpaces(mapping.getVcs())) {
       LOG.debug("Removing <Project> -> <None> mapping");
       iterator.remove();
     } else if (FileUtil.pathsEqual(mapping.getDirectory(), path)) {
       if (!StringUtil.isEmptyOrSpaces(mapping.getVcs())) {
         LOG.warn(
             "Substituting existing mapping ["
                 + path
                 + "] -> ["
                 + mapping.getVcs()
                 + "] with ["
                 + vcs
                 + "]");
       } else {
         LOG.debug("Removing [" + path + "] -> <None> mapping");
       }
       iterator.remove();
     }
   }
   mappings.add(new VcsDirectoryMapping(path, vcs));
   return mappings;
 }
Example #13
0
  /** This function is called to refresh all conductors in this network */
  @Override
  public void refresh() {
    this.oxygenTiles.clear();

    try {
      Iterator<ITransmitter> it = this.pipes.iterator();

      while (it.hasNext()) {
        ITransmitter transmitter = it.next();

        if (transmitter == null) {
          it.remove();
          continue;
        }

        transmitter.onNetworkChanged();

        if (((TileEntity) transmitter).isInvalid()
            || ((TileEntity) transmitter).getWorldObj() == null) {
          it.remove();
          continue;
        } else {
          transmitter.setNetwork(this);
        }
      }
    } catch (Exception e) {
      FMLLog.severe("Failed to refresh oxygen pipe network.");
      e.printStackTrace();
    }
  }
  private Set<TypeElement> getTypeFromProperties(Set<TypeElement> parents) {
    Set<TypeElement> elements = new HashSet<TypeElement>();
    for (Element element : parents) {
      if (element instanceof TypeElement) {
        processFromProperties((TypeElement) element, elements);
      }
    }

    Iterator<TypeElement> iterator = elements.iterator();
    while (iterator.hasNext()) {
      TypeElement element = iterator.next();
      String name = element.getQualifiedName().toString();
      if (name.startsWith("java.") || name.startsWith("org.joda.time.")) {
        iterator.remove();
      } else {
        boolean annotated = false;
        for (Class<? extends Annotation> annotation : conf.getEntityAnnotations()) {
          annotated |= element.getAnnotation(annotation) != null;
        }
        if (annotated) {
          iterator.remove();
        }
      }
    }

    return elements;
  }
Example #15
0
  @Override
  public void update(double t) {

    { // UPDATE TOWERS
      for (Tile[] tiles : getTiles())
        for (Tile tile : tiles) if (tile.hasTower()) tile.getTower().update(t);
    }

    { // UPDATE BULLETS
      final Iterator<Bullet> it = getBullets().iterator();

      while (it.hasNext()) {

        final Bullet b = it.next();

        if (b.update(t)) it.remove();
      }
    }

    { // UPDATE MOBS
      final Iterator<Mob> it = getMobs().iterator();

      while (it.hasNext()) {

        final Mob m = it.next();

        m.update(t);

        if (m.shouldBeRemoved()) {
          m.onRemove(getGame());
          it.remove();
        }
      }
    }
  }
Example #16
0
  @NotNull
  private static Collection<CallableMemberDescriptor> extractMembersOverridableInBothWays(
      @NotNull CallableMemberDescriptor overrider,
      @NotNull Queue<CallableMemberDescriptor> extractFrom,
      @NotNull DescriptorSink sink) {
    Collection<CallableMemberDescriptor> overridable = new ArrayList<CallableMemberDescriptor>();
    overridable.add(overrider);
    for (Iterator<CallableMemberDescriptor> iterator = extractFrom.iterator();
        iterator.hasNext(); ) {
      CallableMemberDescriptor candidate = iterator.next();
      if (overrider == candidate) {
        iterator.remove();
        continue;
      }

      OverrideCompatibilityInfo.Result result1 =
          DEFAULT.isOverridableBy(candidate, overrider).getResult();
      OverrideCompatibilityInfo.Result result2 =
          DEFAULT.isOverridableBy(overrider, candidate).getResult();
      if (result1 == OVERRIDABLE && result2 == OVERRIDABLE) {
        overridable.add(candidate);
        iterator.remove();
      } else if (result1 == CONFLICT || result2 == CONFLICT) {
        sink.conflict(overrider, candidate);
        iterator.remove();
      }
    }
    return overridable;
  }
Example #17
0
 private void deploy() {
   List startList = new ArrayList();
   Iterator iter = dirMap.entrySet().iterator();
   try {
     while (iter.hasNext() && !shutdown) {
       Map.Entry entry = (Map.Entry) iter.next();
       File f = (File) entry.getKey();
       QEntry qentry = (QEntry) entry.getValue();
       long deployed = qentry.getDeployed();
       if (deployed == 0) {
         if (deploy(f)) {
           if (qentry.isQBean()) startList.add(qentry.getInstance());
           qentry.setDeployed(f.lastModified());
         } else {
           // deploy failed, clean up.
           iter.remove();
         }
       } else if (deployed != f.lastModified()) {
         undeploy(f);
         iter.remove();
         loader.forceNewClassLoaderOnNextScan();
       }
     }
     iter = startList.iterator();
     while (iter.hasNext()) {
       start((ObjectInstance) iter.next());
     }
   } catch (Exception e) {
     log.error("deploy", e);
   }
 }
  /** {@inheritDoc} */
  public void applyFederationFilter(final Collection list, final Class objectType) {
    final Set<Long> manageableShopIds =
        shopFederationStrategy.getAccessibleShopIdsByCurrentManager();
    final Iterator<CarrierDTO> carriersIt = list.iterator();
    while (carriersIt.hasNext()) {
      final CarrierDTO carrier = carriersIt.next();

      try {
        final Map<ShopDTO, Boolean> shops =
            carrierService.getAssignedCarrierShops(carrier.getCarrierId());
        boolean manageable = false;
        for (final ShopDTO shop : shops.keySet()) {
          if (manageableShopIds.contains(shop.getShopId())) {
            manageable = true;
            break;
          }
        }

        if (!manageable) {
          carriersIt.remove();
        }
      } catch (Exception exp) {
        carriersIt.remove();
      }
    }
  }
Example #19
0
    /**
     * Set the display for the data
     *
     * @param isEmpty true if the data is null
     * @throws RemoteException Java RMI error
     * @throws VisADException problem creating VisAD object
     */
    public synchronized void setDisplay(boolean isEmpty) throws VisADException, RemoteException {

      if (isEmpty) {
        for (Iterator iter = extantDatums.iterator(); iter.hasNext(); ) {
          ((DataAdapter) iter.next()).addTo();
        }
      } else {
        for (Iterator iter = obsoleteDatums.iterator(); iter.hasNext(); ) {
          ((DataAdapter) iter.next()).removeFrom();
        }
      }

      obsoleteDatums.clear();

      for (Iterator iter = changedDatums.iterator(); iter.hasNext(); ) {
        DataAdapter adapter = (DataAdapter) iter.next();

        adapter.addTo();
        iter.remove();
        extantDatums.add(adapter);
      }

      for (Iterator iter = newDatums.iterator(); iter.hasNext(); ) {
        DataAdapter adapter = (DataAdapter) iter.next();

        adapter.addTo();
        iter.remove();
        extantDatums.add(adapter);

        // Add listener now so fewest notifications.
        adapter.addPropertyChangeListener(adapter.CONSTANT_MAP, listener);
      }

      changed = false;
    }
Example #20
0
  public void removeChannel(Channel channel) {
    lock.lock();
    try {
      if (channel.getDirection() == Direction.OUT) {
        BrokerHost registeredHost = null;
        for (Map.Entry<BrokerHost, List<Channel>> e : brokerHostToProducerChannelMap.entrySet()) {
          List<Channel> channels = e.getValue();
          Iterator<Channel> channelIterator = channels.iterator();
          while (channelIterator.hasNext()) {
            Channel c = channelIterator.next();
            if (c.equals(channel)) {
              registeredHost = e.getKey();
              channelIterator.remove();

              // if there are no more channels remove the producer
              if (channels.size() == 0) {
                Manageable producer = producers.remove(registeredHost);
                producer.stop();
              }
              break;
            }
          }
          if (registeredHost != null) {
            break;
          }
        }
      } else if (channel.getDirection() == Direction.IN) {
        BrokerHost registeredHost = null;
        for (Map.Entry<BrokerHost, List<Channel>> e : brokerHostToConsumerChannelMap.entrySet()) {
          List<Channel> channels = e.getValue();
          Iterator<Channel> channelIterator = channels.iterator();
          while (channelIterator.hasNext()) {
            Channel c = channelIterator.next();
            if (c.equals(channel)) {
              registeredHost = e.getKey();
              channelIterator.remove();

              // if there are no more channels remove the producer
              if (channels.size() == 0) {
                ConsumingWorker worker = consumingWorkers.remove(registeredHost);
                worker.stop();

                Manageable consumer = consumers.remove(registeredHost);
                consumer.stop();
              }
              break;
            }
          }
          if (registeredHost != null) {
            break;
          }
        }
      }
    } finally {
      lock.unlock();
    }
  }
Example #21
0
 public <T extends Anim> void clearanims(Class<T> type) {
   for (Iterator<Anim> i = nanims.iterator(); i.hasNext(); ) {
     Anim a = i.next();
     if (type.isInstance(a)) i.remove();
   }
   for (Iterator<Anim> i = anims.iterator(); i.hasNext(); ) {
     Anim a = i.next();
     if (type.isInstance(a)) i.remove();
   }
 }
Example #22
0
  /**
   * This method is the access point to the planning procedure. Initially, it adds all variables
   * from axioms to the set of found vars, then does the linear planning. If lp does not solve the
   * problem and there are subtasks, goal-driven recursive planning with backtracking is invoked.
   * Planning is performed until no new variables are introduced into the algorithm.
   */
  public EvaluationAlgorithm invokePlaning(Problem problem, boolean _computeAll) {
    long startTime = System.currentTimeMillis();

    computeAll = _computeAll;
    EvaluationAlgorithm algorithm = new EvaluationAlgorithm();

    PlanningContext context = problem.getCurrentContext();

    // add all axioms at the beginning of an algorithm
    Collection<Var> flattened = new HashSet<Var>();
    for (Iterator<Rel> axiomIter = problem.getAxioms().iterator(); axiomIter.hasNext(); ) {
      Rel rel = axiomIter.next();

      unfoldVarsToSet(rel.getOutputs(), flattened);

      // do not overwrite values of variables that come via args of compute() or as inputs of
      // independent subtasks
      if (!problem.getAssumptions().containsAll(flattened)
      // do not overwrite values of already known variables.
      // typically this is the case when a value of a variable
      // is given in a scheme via a properties window
      //                    && !problem.getKnownVars().containsAll( flattened )
      ) {
        algorithm.addRel(rel);
      }
      axiomIter.remove();
      context.getKnownVars().addAll(flattened);
      flattened.clear();
    }

    context.getFoundVars().addAll(context.getKnownVars());

    // remove all known vars with no relations
    for (Iterator<Var> varIter = context.getKnownVars().iterator(); varIter.hasNext(); ) {
      if (varIter.next().getRels().isEmpty()) {
        varIter.remove();
      }
    }

    // start planning
    if (problem.getRelsWithSubtasks().isEmpty()
        && linearForwardSearch(context, algorithm, computeAll)) {
      if (isLinearLoggingOn()) logger.debug("Problem solved without subtasks");
    } else if (!problem.getRelsWithSubtasks().isEmpty() && subtaskPlanning(problem, algorithm)) {
      if (isLinearLoggingOn()) logger.debug("Problem solved with subtasks");
    } else if (!computeAll) {
      if (isLinearLoggingOn()) logger.debug("Problem not solved");
    }

    if (!nested) {
      logger.info("Planning time: " + (System.currentTimeMillis() - startTime) + "ms.");
    }
    return algorithm;
  }
Example #23
0
  /**
   * Set the current groups for the item.
   *
   * @param groups The new lists of groups the item belongs to.
   * @throws org.jivesoftware.openfire.SharedGroupException if trying to remove shared group.
   */
  public void setGroups(List<String> groups) throws SharedGroupException {
    if (groups == null) {
      this.groups = new LinkedList<String>();
    } else {
      // Raise an error if the user is trying to remove the item from a shared group
      for (Group group : getSharedGroups()) {
        // Get the display name of the group
        String groupName = group.getProperties().get("sharedRoster.displayName");
        // Check if the group has been removed from the new groups list
        if (!groups.contains(groupName)) {
          throw new SharedGroupException("Cannot remove item from shared group");
        }
      }

      // Remove shared groups from the param
      Collection<Group> existingGroups = GroupManager.getInstance().getSharedGroups();
      for (Iterator<String> it = groups.iterator(); it.hasNext(); ) {
        String groupName = it.next();
        try {
          // Optimistic approach for performance reasons. Assume first that the shared
          // group name is the same as the display name for the shared roster

          // Check if exists a shared group with this name
          Group group = GroupManager.getInstance().getGroup(groupName);
          // Get the display name of the group
          String displayName = group.getProperties().get("sharedRoster.displayName");
          if (displayName != null && displayName.equals(groupName)) {
            // Remove the shared group from the list (since it exists)
            try {
              it.remove();
            } catch (IllegalStateException e) {
              // Do nothing
            }
          }
        } catch (GroupNotFoundException e) {
          // Check now if there is a group whose display name matches the requested group
          for (Group group : existingGroups) {
            // Get the display name of the group
            String displayName = group.getProperties().get("sharedRoster.displayName");
            if (displayName != null && displayName.equals(groupName)) {
              // Remove the shared group from the list (since it exists)
              try {
                it.remove();
              } catch (IllegalStateException ise) {
                // Do nothing
              }
            }
          }
        }
      }
      this.groups = groups;
    }
  }
 /*
   Place all motionless objects (fire stations, police offices, ambulance teams and refuges)
   @param fire An array to be filled with fire stations
   @param police An array to be filled with police offices
   @param ambulance An array to be filled with ambulance centres
   @param refuge An array to be filled with refuges
   @param allBuildings All buildings in the map
   @return All ordinary buildings
 */
 public static Building[] placeMotionlessObjects(
     FireStation[] fire,
     PoliceOffice[] police,
     AmbulanceCenter[] ambulance,
     Refuge[] refuge,
     Building[] allBuildings) {
   List remaining = new ArrayList();
   for (int i = 0; i < allBuildings.length; ++i) remaining.add(allBuildings[i]);
   Collections.shuffle(remaining);
   System.out.println("Placing " + ambulance.length + " ambulance centers");
   Iterator it = remaining.iterator();
   for (int i = 0; i < ambulance.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     AmbulanceCenter a = new AmbulanceCenter(location);
     a.setID(location.getID());
     ambulance[i] = a;
     //			writeFixedObjectData(out,TYPE_AMBULANCE_CENTER,i,location);
   }
   System.out.println("Placing " + fire.length + " fire stations");
   for (int i = 0; i < fire.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     FireStation a = new FireStation(location);
     a.setID(location.getID());
     fire[i] = a;
     //			writeFixedObjectData(out,TYPE_FIRE_STATION,i,location);
     //			System.out.print(".");
   }
   System.out.println("Placing " + police.length + " police stations");
   for (int i = 0; i < police.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     PoliceOffice a = new PoliceOffice(location);
     a.setID(location.getID());
     police[i] = a;
     //			writeFixedObjectData(out,TYPE_POLICE_OFFICE,i,location);
     //			System.out.print(".");
   }
   System.out.println("Placing " + refuge.length + " refuges");
   for (int i = 0; i < refuge.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     Refuge a = new Refuge(location);
     a.setID(location.getID());
     refuge[i] = a;
     //			writeFixedObjectData(out,TYPE_REFUGE,i,location);
     //			System.out.print(".");
   }
   //		System.out.println();
   return (Building[]) remaining.toArray(new Building[0]);
 }
Example #25
0
  private void processNext() {
    Ref<ArrayList<SimpleTimerTask>> tasks = new Ref<ArrayList<SimpleTimerTask>>();

    synchronized (myTime2Task) {
      final long current = System.currentTimeMillis();

      final Iterator<Long> times = myTime2Task.keySet().iterator();

      if (times.hasNext()) {
        final Long time = times.next();
        tasks.set(myTime2Task.get(time));
        times.remove();
      }

      if (!times.hasNext()) {
        myNextScheduledTime = Long.MAX_VALUE;
        myNextProcessingTask = null;
      } else {
        Long nextEffectiveTime = null;
        while (times.hasNext()) {
          Long nextTime = times.next();
          if (nextTime <= current) {
            tasks.get().addAll(myTime2Task.get(nextTime));
            times.remove();
          } else {
            nextEffectiveTime = nextTime;
            break;
          }
        }

        if (nextEffectiveTime == null) {
          myNextProcessingTask = null;
          myNextScheduledTime = Long.MAX_VALUE;
        } else {
          scheduleNext(nextEffectiveTime - current, nextEffectiveTime);
        }
      }
    }

    final ArrayList<SimpleTimerTask> toRun = tasks.get();
    if (toRun != null) {
      for (SimpleTimerTask each : toRun) {
        try {
          each.run();
        } catch (ProcessCanceledException e) {
          throw e;
        } catch (Throwable e) {
          LOG.error(e);
        }
      }
    }
  }
Example #26
0
  /**
   * Internal method to remove the community and all its children from the database, and perform any
   * pre/post-cleanup
   *
   * @throws SQLException
   * @throws AuthorizeException
   * @throws IOException
   */
  protected void rawDelete(Context context, Community community)
      throws SQLException, AuthorizeException, IOException {
    log.info(
        LogManager.getHeader(context, "delete_community", "community_id=" + community.getID()));

    context.addEvent(
        new Event(
            Event.DELETE,
            Constants.COMMUNITY,
            community.getID(),
            community.getHandle(),
            getIdentifiers(context, community)));

    // Remove collections
    Iterator<Collection> collections = community.getCollections().iterator();

    while (collections.hasNext()) {
      Collection collection = collections.next();
      collections.remove();
      removeCollection(context, community, collection);
    }
    // delete subcommunities
    Iterator<Community> subCommunities = community.getSubcommunities().iterator();

    while (subCommunities.hasNext()) {
      Community subComm = subCommunities.next();
      subCommunities.remove();
      delete(context, subComm);
    }

    // Remove the logo
    setLogo(context, community, null);

    // Remove all authorization policies
    authorizeService.removeAllPolicies(context, community);

    // Remove any Handle
    handleService.unbindHandle(context, community);

    deleteMetadata(context, community);

    Group g = community.getAdministrators();

    // Delete community row
    communityDAO.delete(context, community);

    // Remove administrators group - must happen after deleting community

    if (g != null) {
      groupService.delete(context, g);
    }
  }
Example #27
0
 void removeFriendsAndBorders(Piece piece, ArrayList<Point> points) {
   boolean up = piece.isUp();
   for (Iterator<Point> it = points.iterator(); it.hasNext(); ) {
     Point point = it.next();
     if (point != Poussin.PROMOTING
         && (point.x < 0 || point.y < 0 || point.x >= GRID_WIDTH || point.y >= GRID_HEIGHT)) {
       it.remove();
       continue;
     }
     Piece pieceOnSquare = getPosition().getPiece(point.x, point.y);
     if (pieceOnSquare != null && pieceOnSquare.isUp() == up) it.remove();
   }
 }
Example #28
0
  /**
   * Compare two collections by size, then by contents. List comparisons will preserve order. All
   * other collections will be treated with bag semantics.
   */
  private static boolean sameOrEquals(
      Collection<?> collection,
      Collection<?> otherCollection,
      Map<PendingComparison, Comparison> pending,
      Map<Object, Object> pairs) {
    if (collection.size() != otherCollection.size()) {
      return false;
    }

    if (collection instanceof List<?>) {
      // Lists we can simply iterate over
      Iterator<?> it = collection.iterator();
      Iterator<?> otherIt = otherCollection.iterator();
      while (it.hasNext()) {
        assert otherIt.hasNext();
        Object element = it.next();
        Object otherElement = otherIt.next();
        if (!sameOrEquals(element, otherElement, pending)) {
          return false;
        }
        if (pairs != null) {
          pairs.put(element, otherElement);
        }
      }
    } else {
      // Do an n*m comparison on any other collection type
      List<Object> values = new ArrayList<Object>(collection);
      List<Object> otherValues = new ArrayList<Object>(otherCollection);
      it:
      for (Iterator<Object> it = values.iterator(); it.hasNext(); ) {
        Object value = it.next();
        for (Iterator<Object> otherIt = otherValues.iterator(); otherIt.hasNext(); ) {
          Object otherValue = otherIt.next();
          if (sameOrEquals(value, otherValue, pending)) {
            if (pairs != null) {
              pairs.put(value, otherValue);
            }
            // If a match is found, remove both values from their lists
            it.remove();
            otherIt.remove();
            continue it;
          }
        }
        // A match for the value wasn't found
        return false;
      }
      assert values.isEmpty() && otherValues.isEmpty();
    }
    return true;
  }
Example #29
0
 public void checkScheduledActions() {
   if (!node.joined() || !node.isActive()) return;
   if (setScheduledActions.size() > 0) {
     Iterator<ScheduledAction> it = setScheduledActions.iterator();
     while (it.hasNext()) {
       ScheduledAction sa = it.next();
       if (sa.expired() && sa.isValid()) {
         sa.onExpire();
         it.remove();
       } else if (!sa.isValid()) {
         it.remove();
       }
     }
   }
 }
  /**
   * JUnit.
   *
   * @throws Exception If failed.
   */
  public void testIterator() throws Exception {
    // Random queue name.
    String queueName = UUID.randomUUID().toString();

    IgniteQueue<String> queue = grid(0).queue(queueName, 0, config(false));

    for (int i = 0; i < 100; i++) assert queue.add(Integer.toString(i));

    Iterator<String> iter1 = queue.iterator();

    int cnt = 0;
    for (int i = 0; i < 100; i++) {
      assertNotNull(iter1.next());
      cnt++;
    }

    assertEquals(100, queue.size());
    assertEquals(100, cnt);

    assertNotNull(queue.take());
    assertNotNull(queue.take());
    assertTrue(queue.remove("33"));
    assertTrue(queue.remove("77"));

    assertEquals(96, queue.size());

    Iterator<String> iter2 = queue.iterator();

    try {
      iter2.remove();
    } catch (IllegalStateException e) {
      info("Caught expected exception: " + e);
    }

    iter2.next();
    iter2.remove();

    cnt = 0;
    while (iter2.hasNext()) {
      assertNotNull(iter2.next());
      cnt++;
    }

    assertEquals(95, cnt);
    assertEquals(95, queue.size());

    iter2.remove();
  }