Java Code Examples for java.util.Collection.addAll()

The following are Jave code examples for showing how to use addAll() of the java.util.Collection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jdk8u-jdk   File: JDesktopPane.java   View Source Code Vote up 6 votes
private static Collection<JInternalFrame> getAllFrames(Container parent) {
    int i, count;
    Collection<JInternalFrame> results = new LinkedHashSet<>();
    count = parent.getComponentCount();
    for (i = 0; i < count; i++) {
        Component next = parent.getComponent(i);
        if (next instanceof JInternalFrame) {
            results.add((JInternalFrame) next);
        } else if (next instanceof JInternalFrame.JDesktopIcon) {
            JInternalFrame tmp = ((JInternalFrame.JDesktopIcon) next).getInternalFrame();
            if (tmp != null) {
                results.add(tmp);
            }
        } else if (next instanceof Container) {
            results.addAll(getAllFrames((Container) next));
        }
    }
    return results;
}
 
Example 2
Project: sstore-soft   File: ParameterMappingsSet.java   View Source Code Vote up 6 votes
/**
 * Get all of the ParameterMapping for this StmtParameter, regardless of the catalog_stmt_index
 * @param catalog_stmt
 * @param catalog_stmt_param
 * @return
 */
protected Collection<ParameterMapping> get(Statement catalog_stmt, StmtParameter catalog_stmt_param) {
    assert(catalog_stmt != null);
    assert(catalog_stmt_param != null);
    
    Collection<ParameterMapping> set = new TreeSet<ParameterMapping>();
    StatementMappings mappings = this.stmtIndex.get(catalog_stmt);
    if (mappings != null) {
        for (SortedMap<StmtParameter, SortedSet<ParameterMapping>> m : mappings.values()) {
            if (m.containsKey(catalog_stmt_param)) {
                set.addAll(m.get(catalog_stmt_param));
            }
        } // FOR
    }
    return (set);
}
 
Example 3
Project: CodeU-ProjectGroup6   File: RemoteRelay.java   View Source Code Vote up 6 votes
@Override
public Collection<Relay.Bundle> read(Uuid teamId, Secret teamSecret, Uuid root, int range) {

  final Collection<Relay.Bundle> result = new ArrayList<>();

  try (final Connection connection = source.connect()) {

    Serializers.INTEGER.write(connection.out(), NetworkCode.RELAY_READ_REQUEST);
    Uuid.SERIALIZER.write(connection.out(), teamId);
    Secret.SERIALIZER.write(connection.out(), teamSecret);
    Uuid.SERIALIZER.write(connection.out(), root);
    Serializers.INTEGER.write(connection.out(), range);

    if (Serializers.INTEGER.read(connection.in()) == NetworkCode.RELAY_READ_RESPONSE) {
      result.addAll(Serializers.collection(BUNDLE_SERIALIZER).read(connection.in()));
    } else {
      LOG.error("Server did not handle RELAY_READ_REQUEST");
    }
  } catch (Exception ex) {
    LOG.error(ex, "Unexpected error when sending RELAY_READ_REQUEST");
  }

  return result;
}
 
Example 4
Project: fresco_floodlight   File: OFSwitch.java   View Source Code Vote up 6 votes
/**
 * Sorts any invalid messages by moving them from the msgList. The net result
 * is a new list returned containing the invalid messages and a pruned msgList
 * containing only those messages that are valid for the given role of the controller
 * and OpenFlow version of the switch.
 * 
 * @param msgList the list of messages to sort
 * @param valid the list of valid messages (caller must allocate)
 * @param swVersion the OFVersion of the switch
 * @param isSlave true if controller is slave; false otherwise
 * @return list of messages that are not valid, removed from input parameter msgList
 */
protected static Collection<OFMessage> pruneInvalidMessages(Iterable<OFMessage> msgList, Collection<OFMessage> valid, OFVersion swVersion, boolean isActive) {
	if (isActive) { /* master or equal/other support all */
		valid.addAll(IterableUtils.toCollection(msgList));
		return Collections.emptyList();
	} else { /* slave */
		Set<OFType> invalidSlaveMsgs = invalidSlaveMsgsByOFVersion.get(swVersion);
		List<OFMessage> invalid = new ArrayList<OFMessage>();
		Iterator<OFMessage> itr = msgList.iterator();
		while (itr.hasNext()) {
			OFMessage m = itr.next();
			if (invalidSlaveMsgs.contains(m.getType())) {
				invalid.add(m);
			} else {
				valid.add(m);
			}
		}

		return invalid;
	}
}
 
Example 5
Project: ctsms   File: CourseServiceImpl.java   View Source Code Vote up 6 votes
@Override
protected Collection<DutyRosterTurnOutVO> handleGetCollidingDutyRosterTurns(
		AuthenticationVO auth, Long courseParticipationStatusEntryId, Boolean isRelevantForCourseAppointments) throws Exception {
	CourseParticipationStatusEntry courseParticipationStatusEntry = CheckIDUtil.checkCourseParticipationStatusEntryId(courseParticipationStatusEntryId,
			this.getCourseParticipationStatusEntryDao());
	Collection collidingDutyRosterTurns = new HashSet(); // ArrayList();
	Long staffId = courseParticipationStatusEntry.getStaff().getId();
	DutyRosterTurnDao dutyRosterTurnDao = this.getDutyRosterTurnDao();
	Iterator<InventoryBooking> it = this.getInventoryBookingDao()
			.findByCourseSorted(courseParticipationStatusEntry.getCourse().getId(), isRelevantForCourseAppointments, false).iterator();
	while (it.hasNext()) {
		InventoryBooking courseInventoryBooking = it.next();
		collidingDutyRosterTurns.addAll(dutyRosterTurnDao.findByStaffTrialCalendarInterval(staffId, null, null, courseInventoryBooking.getStart(),
				courseInventoryBooking.getStop()));
	}
	dutyRosterTurnDao.toDutyRosterTurnOutVOCollection(collidingDutyRosterTurns);
	return new ArrayList<DutyRosterTurnOutVO>(collidingDutyRosterTurns);
}
 
Example 6
Project: alevin-svn2   File: OptimalMappingsAlgorithm.java   View Source Code Vote up 6 votes
Collection<ResourceDemandEntry> mapEdges(
		SubstrateNetwork sNetwork,
		VirtualNetwork vNetwork,
		MappingCandidate<VirtualNode, SubstrateNode> candidate,
		NodeLinkMapping m,
		Collection<ResourceDemandEntry> demandedNodeEnergyResource,
		int epsilon) {

	Collection<ResourceDemandEntry> out = mapOutEdges(
			sNetwork, vNetwork, candidate, m, epsilon);
	if (out == null) {
		return null;
	}
	Collection<ResourceDemandEntry> in = mapInEdges(
			sNetwork, vNetwork, candidate, m, epsilon);
	if (in == null) {
		Utils.freeResources(out);
		return null;
	}

	out.addAll(in);
	return out;
}
 
Example 7
Project: neoscada   File: DataComponentGenerator.java   View Source Code Vote up 6 votes
protected Collection<Endpoint> getEndpoints ( final EquinoxApplication app )
{
    final Collection<Endpoint> result = new LinkedList<> ();

    if ( app == null )
    {
        return result;
    }

    for ( final Exporter exporter : app.getExporter () )
    {
        result.addAll ( exporter.getEndpoints () );
    }

    return result;
}
 
Example 8
Project: monarch   File: GMSJoinLeave.java   View Source Code Vote up 6 votes
void sendCurrentView() {
  NetView v = currentView;
  if (v != null) {
    InstallViewMessage msg = new InstallViewMessage(v,
        services.getAuthenticator().getCredentials(localAddress), false);
    Collection<InternalDistributedMember> recips =
        new ArrayList<>(v.size() + v.getCrashedMembers().size());
    recips.addAll(v.getMembers());
    recips.remove(localAddress);
    recips.addAll(v.getCrashedMembers());
    msg.setRecipients(recips);
    // use sendUnreliably since we are sending to crashed members &
    // don't want any retransmission tasks set up for them
    services.getMessenger().sendUnreliably(msg);
  }
}
 
Example 9
Project: googles-monorepo-demo   File: CharsTest.java   View Source Code Vote up 5 votes
public void testToArray_threadSafe() {
  for (int delta : new int[] { +1, 0, -1 }) {
    for (int i = 0; i < VALUES.length; i++) {
      List<Character> list = Chars.asList(VALUES).subList(0, i);
      Collection<Character> misleadingSize =
          Helpers.misleadingSizeCollection(delta);
      misleadingSize.addAll(list);
      char[] arr = Chars.toArray(misleadingSize);
      assertEquals(i, arr.length);
      for (int j = 0; j < i; j++) {
        assertEquals(VALUES[j], arr[j]);
      }
    }
  }
}
 
Example 10
Project: alfresco-repository   File: JscriptWorkflowTask.java   View Source Code Vote up 5 votes
private Collection<QName> getAllowedPackageResourceTypes()
{
    // look for content nodes or links to content
    // NOTE: folders within workflow packages are ignored for now
    Collection<QName> allowedTypes = dictionaryService.getSubTypes(ContentModel.TYPE_CONTENT, true);
    allowedTypes.addAll(dictionaryService.getSubTypes(ApplicationModel.TYPE_FILELINK, true));
    return allowedTypes;
}
 
Example 11
Project: Transport-Pipes   File: TransportPipes.java   View Source Code Vote up 5 votes
@Override
public void onDisable() {
	pipeThread.setRunning(false);
	try {
		pipeThread.join();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	savingManager.saveDuctsSync(true);

	// despawn all pipes and items
	Map<World, Map<BlockLoc, Duct>> fullDuctMap = getFullDuctMap();
	synchronized (fullDuctMap) {
		for (Map<BlockLoc, Duct> ductMap : fullDuctMap.values()) {
			for (Duct duct : ductMap.values()) {

				ductManager.destroyDuct(duct);

				if (duct instanceof Pipe) {
					Pipe pipe = (Pipe) duct;
					Collection<PipeItem> allItems = new ArrayList<>();
					synchronized (pipe.pipeItems) {
						allItems.addAll(pipe.pipeItems.keySet());
					}
					synchronized (pipe.tempPipeItems) {
						allItems.addAll(pipe.tempPipeItems.keySet());
					}
					synchronized (pipe.tempPipeItemsWithSpawn) {
						allItems.addAll(pipe.tempPipeItemsWithSpawn.keySet());
					}
					for (PipeItem pi : allItems) {
						ductManager.destroyPipeItem(pi);
					}
				}
			}
		}
	}

}
 
Example 12
Project: qpp-conversion-tool   File: ConversionEntry.java   View Source Code Vote up 5 votes
/**
 * Extract values from command line entries and use as a means of configuration.
 *
 * @param line parsed command line
 * @return paths extracted from the command line
 */
private static Collection<Path> checkArgs(CommandLine line) {
	Collection<Path> validFiles = new LinkedList<>();
	
	for (String arg : checkFlags(line).getArgs()) {
		validFiles.addAll(checkPath(arg));
	}

	return validFiles;
}
 
Example 13
Project: spring-cloud-dashboard   File: BootApplicationConfigurationMetadataResolver.java   View Source Code Vote up 5 votes
/**
 * Loads white lists of properties and group classes and add them to the given collections.
 */
private void loadWhiteLists(Resource[] resources, Collection<String> classes, Collection<String> names) throws IOException {
	for (Resource resource : resources) {
		Properties properties = new Properties();
		properties.load(resource.getInputStream());
		classes.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_CLASSES), ",", " ")));
		names.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(properties.getProperty(CONFIGURATION_PROPERTIES_NAMES), ",", " ")));
	}
}
 
Example 14
Project: magento2-phpstorm-plugin   File: PhpClassMemberCompletionProvider.java   View Source Code Vote up 4 votes
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    final Collection<PhpClassMember> members = new THashSet<>();
    String prefix = result.getPrefixMatcher().getPrefix();

    if (!(prefix.lastIndexOf("::") > 0 && prefix.lastIndexOf("\\") > 0
            && prefix.lastIndexOf("::") > prefix.lastIndexOf("\\"))) {
        return;
    }

    String className = prefix.substring(0, prefix.lastIndexOf("::"));

    PhpIndex phpIndex = PhpIndex.getInstance(parameters.getPosition().getProject());
    for (PhpClass phpClass : phpIndex.getAnyByFQN(className)) {
        members.addAll(phpClass.getFields());
        members.addAll(phpClass.getMethods());
    }

    for (PhpClassMember member : members) {
        if (Field.class.isInstance(member)) {
            result.addElement(
                    LookupElementBuilder
                            .create(className + (((Field) member).isConstant() ? "::" : "::$") + member.getName())
                            .withIcon(member.getIcon())
            );
        } else {
            result.addElement(
                    LookupElementBuilder
                            .create(className + "::" + member.getName() + "()")
                            .withIcon(member.getIcon())
            );
        }
    }
}
 
Example 15
Project: SparkSeq   File: FragmentUtils.java   View Source Code Vote up 4 votes
/**
 * Generic algorithm that takes an iterable over T objects, a getter routine to extract the reads in T,
 * and returns a FragmentCollection that contains the T objects whose underlying reads either overlap (or
 * not) with their mate pairs.
 *
 * @param readContainingObjects An iterator of objects that contain GATKSAMRecords
 * @param nElements the number of elements to be provided by the iterator, which is usually known upfront and
 *                  greatly improves the efficiency of the fragment calculation
 * @param getter a helper function that takes an object of type T and returns is associated GATKSAMRecord
 * @param <T>
 * @return a fragment collection
 */
private static <T> FragmentCollection<T> create(final Iterable<T> readContainingObjects, final int nElements, final ReadGetter<T> getter) {
    Collection<T> singletons = null;
    Collection<List<T>> overlapping = null;
    Map<String, T> nameMap = null;

    int lastStart = -1;

    // build an initial map, grabbing all of the multi-read fragments
    for ( final T p : readContainingObjects ) {
        final SAMRecord read = getter.get(p);

        if ( read.getAlignmentStart() < lastStart ) {
            throw new IllegalArgumentException(String.format(
                    "FragmentUtils.create assumes that the incoming objects are ordered by " +
                            "SAMRecord alignment start, but saw a read %s with alignment start " +
                            "%d before the previous start %d", read.getSAMString(), read.getAlignmentStart(), lastStart));
        }
        lastStart = read.getAlignmentStart();

        final int mateStart = read.getMateAlignmentStart();
        if ( mateStart == 0 || mateStart > read.getAlignmentEnd() ) {
            // if we know that this read won't overlap its mate, or doesn't have one, jump out early
            if ( singletons == null ) singletons = new ArrayList<T>(nElements); // lazy init
            singletons.add(p);
        } else {
            // the read might overlap it's mate, or is the rightmost read of a pair
            final String readName = read.getReadName();
            final T pe1 = nameMap == null ? null : nameMap.get(readName);
            if ( pe1 != null ) {
                // assumes we have at most 2 reads per fragment
                if ( overlapping == null ) overlapping = new ArrayList<List<T>>(); // lazy init
                overlapping.add(Arrays.asList(pe1, p));
                nameMap.remove(readName);
            } else {
                if ( nameMap == null ) nameMap = new HashMap<String, T>(nElements); // lazy init
                nameMap.put(readName, p);
            }
        }
    }

    // add all of the reads that are potentially overlapping but whose mate never showed
    // up to the oneReadPile
    if ( nameMap != null && ! nameMap.isEmpty() ) {
        if ( singletons == null )
            singletons = nameMap.values();
        else
            singletons.addAll(nameMap.values());
    }

    return new FragmentCollection<T>(singletons, overlapping);
}
 
Example 16
Project: HCFCore   File: FactionChatArgument.java   View Source Code Vote up 4 votes
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command is only executable by players.");
        return true;
    }

    Player player = (Player) sender;
    PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(player);

    if (playerFaction == null) {
        sender.sendMessage(ChatColor.RED + "You are not in a faction.");
        return true;
    }

    FactionMember member = playerFaction.getMember(player.getUniqueId());
    ChatChannel currentChannel = member.getChatChannel();
    ChatChannel parsed = args.length >= 2 ? ChatChannel.parse(args[1], null) : currentChannel.getRotation();

    if (parsed == null && currentChannel != ChatChannel.PUBLIC) {
        Collection<Player> recipients = playerFaction.getOnlinePlayers();
        if (currentChannel == ChatChannel.ALLIANCE) {
            for (PlayerFaction ally : playerFaction.getAlliedFactions()) {
                recipients.addAll(ally.getOnlinePlayers());
            }
        }

        String format = String.format(currentChannel.getRawFormat(player), "", StringUtils.join(args, ' ', 1, args.length));
        for (Player recipient : recipients) {
            recipient.sendMessage(format);
        }

        // spawn radius, border, allies, minigames,
        return true;
    }

    ChatChannel newChannel = parsed == null ? currentChannel.getRotation() : parsed;
    member.setChatChannel(newChannel);

    sender.sendMessage(ChatColor.YELLOW + "You are now in " + ChatColor.AQUA + newChannel.getDisplayName().toLowerCase() + ChatColor.YELLOW + " chat mode.");
    return true;
}
 
Example 17
Project: ipack   File: LDAPStoreHelper.java   View Source Code Vote up 4 votes
/**
 * Can use the issuer of the given of the X509CRLStoreSelector.
 *
 * @param xselector            The selector with the search criteria.
 * @param attrs                Attributes which contain the attribute certificates in the
 *                             LDAP directory.
 * @param attrNames            Attribute names in the LDAP directory which correspond to the
 *                             subjectAttributeNames.
 * @param issuerAttributeNames Issuer attribute names (like "CN", "O", "OU") to use to search
 *                             in the LDAP directory
 * @return A list of found DER encoded CRLs.
 * @throws StoreException if an error occurs while searching.
 */
private List cRLIssuerSearch(X509CRLStoreSelector xselector,
                             String[] attrs, String attrNames[], String issuerAttributeNames[])
    throws StoreException
{
    List list = new ArrayList();

    String issuer = null;
    Collection issuers = new HashSet();
    if (xselector.getIssuers() != null)
    {
        issuers.addAll(xselector.getIssuers());
    }
    if (xselector.getCertificateChecking() != null)
    {
        issuers.add(getCertificateIssuer(xselector.getCertificateChecking()));
    }
    if (xselector.getAttrCertificateChecking() != null)
    {
        Principal principals[] = xselector.getAttrCertificateChecking().getIssuer().getPrincipals();
        for (int i=0; i<principals.length; i++)
        {
            if (principals[i] instanceof X500Principal)
            {
                issuers.add(principals[i]);        
            }
        }
    }
    Iterator it = issuers.iterator();
    while (it.hasNext())
    {
        issuer = ((X500Principal)it.next()).getName("RFC1779");
        String attrValue = null;

        for (int i = 0; i < issuerAttributeNames.length; i++)
        {
            attrValue = parseDN(issuer, issuerAttributeNames[i]);
            list
                .addAll(search(attrNames, "*" + attrValue + "*",
                    attrs));
        }
    }
    if (issuer == null)
    {
        list.addAll(search(attrNames, "*", attrs));
    }

    return list;
}
 
Example 18
Project: Tarski   File: mxGraphComponent.java   View Source Code Vote up 4 votes
/**
 * Returns the children of the given parent that are contained in the given rectangle (x, y,
 * width, height). The result is added to the optional result array, which is returned from the
 * function. If no result array is specified then a new array is created and returned.
 * 
 * @return Returns the children inside the given rectangle.
 */
public Object[] getCells(Rectangle rect, Object parent) {
  Collection<Object> result = new ArrayList<Object>();

  if (rect.width > 0 || rect.height > 0) {
    if (parent == null) {
      parent = graph.getDefaultParent();
    }

    if (parent != null) {
      Point previousTranslate = canvas.getTranslate();
      double previousScale = canvas.getScale();

      try {
        canvas.setScale(graph.getView().getScale());
        canvas.setTranslate(0, 0);

        mxIGraphModel model = graph.getModel();
        mxGraphView view = graph.getView();

        int childCount = model.getChildCount(parent);

        for (int i = 0; i < childCount; i++) {
          Object cell = model.getChildAt(parent, i);
          mxCellState state = view.getState(cell);

          if (graph.isCellVisible(cell) && state != null) {
            if (canvas.contains(this, rect, state)) {
              result.add(cell);
            } else {
              result.addAll(Arrays.asList(getCells(rect, cell)));
            }
          }
        }
      } finally {
        canvas.setScale(previousScale);
        canvas.setTranslate(previousTranslate.x, previousTranslate.y);
      }
    }
  }

  return result.toArray();
}
 
Example 19
Project: incubator-netbeans   File: TemplatesPanel.java   View Source Code Vote up 4 votes
private void sortNodes () {
    Node [] originalNodes = original.getChildren ().getNodes ();
    Collection<Node> sortedNodes = new TreeSet<> (new TemplateCategotyComparator ());
    sortedNodes.addAll(Arrays.asList(originalNodes));
    setKeys (sortedNodes.toArray (new Node[0]));
}
 
Example 20
Project: Progetto-C   File: XMLElementList.java   View Source Code Vote up 2 votes
/**
 * Add all the elements in this list to another collection
 * 
 * @param collection The collection the elements should be added to
 */
public void addAllTo(Collection collection) {
	collection.addAll(list);
}