下面列出了怎么用java.util.Iterator的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* finds and deletes a Chat line by ID
*/
public void deleteChatLine(int id) {
Iterator<GuiChatLine> iterator = this.singleChatLines.iterator();
GuiChatLine chatLine;
while (iterator.hasNext()) {
chatLine = iterator.next();
if (chatLine.getChatLineID() == id) {
iterator.remove();
}
}
iterator = this.chatLines.iterator();
while (iterator.hasNext()) {
chatLine = iterator.next();
if (chatLine.getChatLineID() == id) {
iterator.remove();
break;
}
}
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
private static String createSign(Map<String, String> paramMap, String key) {
StringBuffer sb = new StringBuffer();
SortedMap<String,String> sort=new TreeMap<String,String>(paramMap);
Set<Entry<String, String>> es = sort.entrySet();
Iterator<Entry<String, String>> it = es.iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v)&& !"null".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + key);
LOG.info("HMAC source:{}", new Object[] { sb.toString() } );
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
LOG.info("HMAC:{}", new Object[] { sign } );
return sign;
}
private boolean validate() {
this.unfoundProps = new Object[0];
Iterator i$ = this.expectedProps.iterator();
while(i$.hasNext()) {
String prop = (String)i$.next();
boolean validProp = this.config.containsKey(prop);
boolean validMatchProp = this.config.containsKey(prop + ".1");
if (validProp || validMatchProp) {
validProp = true;
}
if (!validProp) {
LOG.warn("Could not find property:" + prop);
this.unfoundProps = ArrayUtils.add(this.unfoundProps, prop);
}
}
return ArrayUtils.isEmpty(this.unfoundProps);
}
private NodeList getWSDLDefintionNode(Node bindings, Node target) {
return evaluateXPathMultiNode(bindings, target, "wsdl:definitions",
new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return "http://schemas.xmlsoap.org/wsdl/";
}
@Override
public String getPrefix(String nsURI) {
throw new UnsupportedOperationException();
}
@Override
public Iterator getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException();
}
});
}
@Override
public Number queryNumber(CassandraSessionPool.Session session,
Query query) {
Aggregate aggregate = query.aggregateNotNull();
Iterator<Number> results = this.query(query, statement -> {
// Set request timeout to a large value
int timeout = session.aggregateTimeout();
statement.setReadTimeoutMillis(timeout * 1000);
return session.query(statement);
}, (q, rs) -> {
Row row = rs.one();
if (row == null) {
return IteratorUtils.of(aggregate.defaultValue());
}
return IteratorUtils.of(row.getLong(0));
});
return aggregate.reduce(results);
}
public void testSetSoftwareList() throws Exception {
KickstartData ksProfile = KickstartDataTest.createKickstartWithProfile(admin);
List<String> packages = new ArrayList<String>();
packages.add("gcc");
int result = handler.setSoftwareList(admin, ksProfile.getLabel(), packages);
boolean pkgFound = false;
for (Iterator<KickstartPackage> itr = ksProfile.getKsPackages().iterator();
itr.hasNext();) {
KickstartPackage pkg = itr.next();
if (pkg.getPackageName().getName().equals("gcc")) {
pkgFound = true;
}
}
assertEquals(1, result);
assertEquals(ksProfile.getKsPackages().size(), 1);
assertEquals(pkgFound, true);
}
private void findPropertiesByPrefix( Set prefixes,
Iterator propertyNames, PropertyCallback getProperty )
{
while (propertyNames.hasNext()) {
String name = (String)(propertyNames.next()) ;
Iterator iter = prefixes.iterator() ;
while (iter.hasNext()) {
String prefix = (String)(iter.next()) ;
if (name.startsWith( prefix )) {
String value = getProperty.get( name ) ;
// Note: do a put even if value is null since just
// the presence of the property may be significant.
setProperty( name, value ) ;
}
}
}
}
private Map<Integer, PartitionInfoSnapshot> getPartitionInfo(String metricsJson) throws IOException {
JsonNode metricsNode = mapper.readTree(metricsJson).path("gauges");
Map<Integer, PartitionInfoSnapshot> partitionInfo = new HashMap<>();
if (metricsNode.path(STORAGE_PARTITION_METRIC_KEY) != null) {
JsonNode partitionIds = metricsNode.path(STORAGE_PARTITION_METRIC_KEY).path("value");
Iterator<JsonNode> element = partitionIds.elements();
while (element.hasNext()) {
Integer id = element.next().asInt();
PartitionInfoSnapshot partitionInfoSnapshot = new PartitionInfoSnapshot(
id,
metricsNode.path("waltz-storage.partition-" + id + ".session-id").path("value").asInt(),
metricsNode.path("waltz-storage.partition-" + id + ".low-water-mark").path("value").asInt(),
metricsNode.path("waltz-storage.partition-" + id + ".local-low-water-mark").path("value").asInt(),
metricsNode.path("waltz-storage.partition-" + id + ".flags").path("value").asInt()
);
partitionInfo.put(id, partitionInfoSnapshot);
}
}
return partitionInfo;
}
private static void markEval(final LexicalContext lc) {
final Iterator<FunctionNode> iter = lc.getFunctions();
boolean flaggedCurrentFn = false;
while (iter.hasNext()) {
final FunctionNode fn = iter.next();
if (!flaggedCurrentFn) {
lc.setFlag(fn, FunctionNode.HAS_EVAL);
flaggedCurrentFn = true;
} else {
lc.setFlag(fn, FunctionNode.HAS_NESTED_EVAL);
}
// NOTE: it is crucial to mark the body of the outer function as needing scope even when we skip
// parsing a nested function. functionBody() contains code to compensate for the lack of invoking
// this method when the parser skips a nested function.
lc.setBlockNeedsScope(lc.getFunctionBody(fn));
}
}
public String getRoleNameFByusername(String username) {
logger.debug("enter getAccountByName for username=" + username);
String SQL = "SELECT RL.name, 'Roles' FROM role as RL, user as U , users_roles as RU WHERE U.userid = RU.userid and RU.roleid = RL.roleid and U.name = ?";
//String SQL = "SELECT name FROM role where roleid=(SELECT roleid FROM users_roles WHERE userid = ( SELECT userId FROM user WHERE name=? ) )";
List queryParams = new ArrayList();
queryParams.add(username);
String roleName = null;
try {
List list = jdbcTempSSOSource.getJdbcTemp().queryMultiObject(queryParams, SQL);
Iterator iter = list.iterator();
if (iter.hasNext()) {
logger.debug("found the role");
Map map = (Map) iter.next();
roleName = ((String) map.get("name")).trim();
}
} catch (Exception se) {
logger.error(username + " error:" + se);
}
return roleName;
}
/**
* @param name the name of the field to check
* @return true if the name exists
*/
@JsxFunction({CHROME, FF})
public boolean has(final String name) {
if (StringUtils.isEmpty(name)) {
return false;
}
final Iterator<NameValuePair> iter = requestParameters_.iterator();
while (iter.hasNext()) {
final NameValuePair pair = iter.next();
if (name.equals(pair.getName())) {
return true;
}
}
return false;
}
@Override
public Set<String> getTopicClusterList(
final String topic) throws InterruptedException, MQBrokerException, MQClientException,
RemotingException {
Set<String> clusterSet = new HashSet<String>();
ClusterInfo clusterInfo = examineBrokerClusterInfo();
TopicRouteData topicRouteData = examineTopicRouteInfo(topic);
BrokerData brokerData = topicRouteData.getBrokerDatas().get(0);
String brokerName = brokerData.getBrokerName();
Iterator<Map.Entry<String, Set<String>>> it = clusterInfo.getClusterAddrTable().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Set<String>> next = it.next();
if (next.getValue().contains(brokerName)) {
clusterSet.add(next.getKey());
}
}
return clusterSet;
}
public static String jstack(Map<Thread, StackTraceElement[]> map) {
StringBuilder result = new StringBuilder();
try {
Iterator<Map.Entry<Thread, StackTraceElement[]>> ite = map.entrySet().iterator();
while (ite.hasNext()) {
Map.Entry<Thread, StackTraceElement[]> entry = ite.next();
StackTraceElement[] elements = entry.getValue();
Thread thread = entry.getKey();
if (elements != null && elements.length > 0) {
String threadName = entry.getKey().getName();
result.append(String.format("%-40sTID: %d STATE: %s%n", threadName, thread.getId(), thread.getState()));
for (StackTraceElement el : elements) {
result.append(String.format("%-40s%s%n", threadName, el.toString()));
}
result.append("\n");
}
}
} catch (Throwable e) {
result.append(RemotingHelper.exceptionSimpleDesc(e));
}
return result.toString();
}
/**
* @param progressLogger pass null if not interested in progress.
* @return An iterator with all the records from underlyingIterator, in order defined by comparator.
*/
public static CloseableIterator<SAMRecord> create(final SAMFileHeader header,
final Iterator<SAMRecord> underlyingIterator,
final Comparator<SAMRecord> comparator,
final ProgressLogger progressLogger) {
final SortingIteratorFactory.ProgressCallback<SAMRecord> progressCallback;
if (progressLogger != null)
progressCallback = new SortingIteratorFactory.ProgressCallback<SAMRecord>() {
@Override
public void logProgress(final SAMRecord record) {
progressLogger.record(record);
}
};
else
progressCallback = null;
return SortingIteratorFactory.create(SAMRecord.class,
underlyingIterator, comparator, new BAMRecordCodec(header),
SAMFileWriterImpl.getDefaultMaxRecordsInRam(),
progressCallback);
}
@Override
public Iterator<PluginPrivilege> privileges(final String remote)
throws IOException, UnexpectedResponseException {
final UncheckedUriBuilder uri =
new UncheckedUriBuilder(
this.baseUri.toString().concat("/privileges")
).addParameter("remote", remote);
return new ResourcesIterator<>(
this.client,
new HttpGet(
uri.build()
),
PluginPrivilege::new
);
}
@Override
Iterator<CopyOnWriteStateMap.StateMapEntry<K, N, S>> getEntryIterator(
final CopyOnWriteStateMap.StateMapEntry<K, N, S> stateMapEntry) {
return new Iterator<CopyOnWriteStateMap.StateMapEntry<K, N, S>>() {
CopyOnWriteStateMap.StateMapEntry<K, N, S> nextEntry = stateMapEntry;
@Override
public boolean hasNext() {
return nextEntry != null;
}
@Override
public CopyOnWriteStateMap.StateMapEntry<K, N, S> next() {
if (nextEntry == null) {
throw new NoSuchElementException();
}
CopyOnWriteStateMap.StateMapEntry<K, N, S> entry = nextEntry;
nextEntry = nextEntry.next;
return entry;
}
};
}
@Override
public synchronized void onSlot(final UnsignedLong slot) {
boolean shouldUpdateENR = false;
final Iterator<Entry<Integer, UnsignedLong>> iterator =
subnetIdToUnsubscribeSlot.entrySet().iterator();
while (iterator.hasNext()) {
final Entry<Integer, UnsignedLong> entry = iterator.next();
if (entry.getValue().compareTo(slot) < 0) {
iterator.remove();
int subnetId = entry.getKey();
eth2Network.unsubscribeFromAttestationSubnetId(subnetId);
if (persistentSubnetIdSet.contains(subnetId)) {
persistentSubnetIdSet.remove(subnetId);
shouldUpdateENR = true;
}
}
}
if (shouldUpdateENR) {
eth2Network.setLongTermAttestationSubnetSubscriptions(persistentSubnetIdSet);
}
}
@Override
public int size() {
//todo, implement a counter variable instead
//only count active members in this node
int counter = 0;
Iterator<Map.Entry<K,MapEntry<K,V>>> it = innerMap.entrySet().iterator();
while (it!=null && it.hasNext() ) {
Map.Entry<?,?> e = it.next();
if ( e != null ) {
MapEntry<K,V> entry = innerMap.get(e.getKey());
if (entry!=null && entry.isActive() && entry.getValue() != null) counter++;
}
}
return counter;
}
/**
* Helper method to prePopulate a new set
* This method is utiliy method NOT intended to be extended
* It can be used when overriding the 'processRequestAttributes' method
* A good use case for this method is when are preselecting a list of items
* from the global list.
*
* @param rctx a request context object
* @param identifiables A Iterator iterating over items of type
* "com.redhat.rhn.domain.Identifiable"
*/
protected final void populateNewSet(RequestContext rctx, Iterator identifiables) {
RhnSet set = getSetDecl().get(rctx.getCurrentUser());
set.clear();
while (identifiables.hasNext()) {
Identifiable tkn = (Identifiable) identifiables.next();
set.addElement(tkn.getId());
}
RhnSetFactory.save(set);
rctx.getRequest().setAttribute("set", set);
}
private <T extends Metric> Function<ByteBuf, Boolean> metricWriter(final MetricFamily<T> metricFamily, final BiConsumer<T, ByteBuf> writer) {
final Iterator<T> metricIterator = metricFamily.metrics().iterator();
return (buffer) -> {
if (metricIterator.hasNext()) {
writer.accept(metricIterator.next(), buffer);
return true;
}
return false;
};
}
@Override
public E peek() {
Iterator<E> iter = set.iterator();
if (iter.hasNext()) {
return iter.next();
} else {
return null;
}
}
private static void assertValueIterator(Iterator<? extends CharSequence> strItr) {
assertTrue(strItr.hasNext());
assertEquals("a", strItr.next());
assertTrue(strItr.hasNext());
assertEquals("", strItr.next());
assertTrue(strItr.hasNext());
assertEquals("b", strItr.next());
assertTrue(strItr.hasNext());
assertEquals("", strItr.next());
assertTrue(strItr.hasNext());
assertEquals("c, d", strItr.next());
assertFalse(strItr.hasNext());
}
public void hideTasks(List<TaskView> filteredTasks) {
Iterator<TaskView> iterator = filteredTasks.iterator();
while (iterator.hasNext()) {
TaskView taskView = iterator.next();
if (!filteredOutTaskNames.contains(taskView.getName())) {
filteredOutTaskNames.add(taskView.getName());
}
}
notifyChanges();
}
public void putAll(Map map) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
put(entry.getKey(), entry.getValue());
}
}
/**
* 树状恢复
* @param prefix 前缀
* @param sourceMap 原始map
* @param dstMap 目标map
* @param remove 命中遍历后是否删除
*/
public static void treeCopyTo(String prefix, Map<String, String> sourceMap,
Map<String, String> dstMap, boolean remove) {
Iterator<Map.Entry<String, String>> it = sourceMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
if (entry.getKey().startsWith(prefix)) {
dstMap.put(entry.getKey().substring(prefix.length()), entry.getValue());
if (remove) {
it.remove();
}
}
}
}
private void verifyTrustStore() throws TechnicalConnectorException {
String trustStoreFilePath = System.getProperty("javax.net.ssl.trustStore");
String location = this.getTrustStoreLocation(trustStoreFilePath);
if (!StringUtils.isEmpty(location)) {
InputStream is = null;
try {
KeyStore truststore = KeyStore.getInstance("JKS");
char[] passwordCharArray = new char[0];
String password = System.getProperty("javax.net.ssl.trustStorePassword");
if (password != null) {
passwordCharArray = password.toCharArray();
}
is = ConnectorIOUtils.getResourceAsStream(location);
truststore.load(is, passwordCharArray);
List<String> aliases = Collections.list(truststore.aliases());
LOG.debug("Content of truststore at location: " + location);
Iterator i$ = aliases.iterator();
while(i$.hasNext()) {
String alias = (String)i$.next();
Certificate cert = truststore.getCertificate(alias);
X509Certificate x509Cert = (X509Certificate)cert;
String dn = x509Cert.getSubjectX500Principal().getName("RFC2253");
LOG.debug("\t." + alias + " :" + dn);
}
} catch (Exception var16) {
LOG.warn(var16.getClass().getSimpleName() + ":" + var16.getMessage());
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_CONFIG, var16, new Object[]{var16.getMessage()});
} finally {
ConnectorIOUtils.closeQuietly((Object)is);
}
}
}
@Test
public void testJacksonPropertyOrderCustomName() {
AugmentedIndexView index = new AugmentedIndexView(indexOf(JacksonPropertyOrderCustomName.class));
ClassInfo leafKlazz = index.getClassByName(componentize(JacksonPropertyOrderCustomName.class.getName()));
Type leaf = Type.create(leafKlazz.name(), Type.Kind.CLASS);
Map<String, TypeResolver> properties = TypeResolver.getAllFields(index, leaf, leafKlazz);
assertEquals(4, properties.size());
Iterator<Entry<String, TypeResolver>> iter = properties.entrySet().iterator();
assertEquals("theName", iter.next().getValue().getPropertyName());
assertEquals("comment2ActuallyFirst", iter.next().getValue().getPropertyName());
assertEquals("comment", iter.next().getValue().getPropertyName());
}
static synchronized boolean syncWorld()
{
boolean ok = true;
if (cachedFiles != null && !cachedFiles.isEmpty()) {
Iterator<WeakReference<MacOSXPreferencesFile>> iter =
cachedFiles.values().iterator();
while (iter.hasNext()) {
WeakReference<MacOSXPreferencesFile> ref = iter.next();
MacOSXPreferencesFile f = ref.get();
if (f != null) {
if (!f.synchronize()) ok = false;
} else {
iter.remove();
}
}
}
// Kill any pending flush
if (flushTimerTask != null) {
flushTimerTask.cancel();
flushTimerTask = null;
}
// Clear changed file list. The changed files were guaranteed to
// have been in the cached file list (because there was a strong
// reference from changedFiles.
if (changedFiles != null) changedFiles.clear();
return ok;
}
public void coGroup(Iterable<Vertex<K, VV>> vertex,
Iterable<Edge<K, EV>> edges, Collector<T> out) throws Exception {
Iterator<Vertex<K, VV>> vertexIterator = vertex.iterator();
if (vertexIterator.hasNext()) {
function.iterateEdges(vertexIterator.next(), edges, out);
} else {
throw new NoSuchElementException("The edge src/trg id could not be found within the vertexIds");
}
}
@Override
public void getPrediction(Map<String, EmotionSample> emotionSampleMap, Map<String, Object> prediction) {
Iterator<String> Iterator = emotionSampleMap.keySet().iterator();
while(Iterator.hasNext()) {
String word = Iterator.next();
EmotionSample emotionSample = emotionSampleMap.get(word);
if(prediction.containsKey(emotionSample.getTrending())) {
emotionSample.setPrediction(prediction.get(emotionSample.getTrending()).toString());
} else if(prediction.containsKey(emotionSample.getMotivation())) {
emotionSample.setPrediction(prediction.get(emotionSample.getMotivation()).toString());
}
emotionSampleMap.put(word, emotionSample);
}
}