java.util.Iterator Java Examples

The following examples show how to use java.util.Iterator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Gui2ndChat.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
/**
 * 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;
		}
	}
}
 
Example #2
Source File: SignatureUtil.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 创建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;
}
 
Example #3
Source File: ConfigValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: Internalizer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
                }
            });
}
 
Example #5
Source File: CassandraTable.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: CodecUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 树状恢复
 * @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();
            }
        }
    }
}
 
Example #7
Source File: SoftwareHandlerTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
 
Example #8
Source File: DataCollectorBase.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
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 ) ;
            }
        }
    }
}
 
Example #9
Source File: StorageCli.java    From waltz with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: Parser.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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));
    }
}
 
Example #11
Source File: AccountSSOSql.java    From jivejdon with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: FormData.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #13
Source File: DefaultMQAdminExtImpl.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: UtilAll.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #15
Source File: SamRecordSortingIteratorFactory.java    From Drop-seq with MIT License 6 votes vote down vote up
/**
   * @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);
  }
 
Example #16
Source File: RtPlugins.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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
    );
}
 
Example #17
Source File: CopyOnWriteStateMapSnapshot.java    From flink with Apache License 2.0 6 votes vote down vote up
@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;
		}
	};
}
 
Example #18
Source File: AttestationTopicSubscriber.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #19
Source File: AbstractReplicatedMap.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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;
}
 
Example #20
Source File: BaseSetListAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: TextFormatMetricFamilyWriter.java    From cassandra-exporter with Apache License 2.0 5 votes vote down vote up
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;
    };
}
 
Example #22
Source File: SetQueue.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public E peek() {
	Iterator<E> iter = set.iterator();
	if (iter.hasNext()) {
		return iter.next();
	} else {
		return null;
	}
}
 
Example #23
Source File: CombinedHttpHeadersTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #24
Source File: BasicFilterEditor.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}
 
Example #25
Source File: TreeBidiMap.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #26
Source File: ConfigurationModuleSSL.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
      }

   }
}
 
Example #27
Source File: TypeResolverTests.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #28
Source File: MacOSXPreferencesFile.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #29
Source File: Graph.java    From flink with Apache License 2.0 5 votes vote down vote up
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");
	}
}
 
Example #30
Source File: RatioMapImp.java    From Deta_Parser with Apache License 2.0 5 votes vote down vote up
@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);
	}	
}