Java Code Examples for java.util.Map.Entry#getKey()

The following examples show how to use java.util.Map.Entry#getKey() . 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: ClustersRetriever.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Render the vertical combs of filaments
 *
 * @param g graphics context
 */
void renderItems (Graphics2D g)
{
    Color oldColor = g.getColor();
    g.setColor(combColor);

    for (Entry<Integer, List<FilamentComb>> entry : colCombs.entrySet()) {
        int col = entry.getKey();
        int x = colX[col];

        for (FilamentComb comb : entry.getValue()) {
            g.draw(new Line2D.Double(x, comb.getY(0), x, comb.getY(comb.getCount() - 1)));
        }
    }

    g.setColor(oldColor);
}
 
Example 2
Source File: TopicListSubCommand.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
private String findTopicBelongToWhichCluster(final String topic, final ClusterInfo clusterInfo,
    final DefaultMQAdminExt defaultMQAdminExt) throws RemotingException, MQClientException,
    InterruptedException {
    TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic);

    BrokerData brokerData = topicRouteData.getBrokerDatas().get(0);

    String brokerName = brokerData.getBrokerName();

    Iterator<Entry<String, Set<String>>> it = clusterInfo.getClusterAddrTable().entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, Set<String>> next = it.next();
        if (next.getValue().contains(brokerName)) {
            return next.getKey();
        }
    }
    return null;
}
 
Example 3
Source File: CassandraMetricBatch.java    From monasca-persister with Apache License 2.0 6 votes vote down vote up
private void logReplicaBatchMap(String name, Map<Set<Host>, Deque<BatchStatement>> map) {
  if (logger.isDebugEnabled()) {
    StringBuilder sb = new StringBuilder(name);
    sb.append(": Size: ").append(map.size());
    sb.append(". Replicas: |");
    for (Entry<Set<Host>, Deque<BatchStatement>> entry : map.entrySet()) {
      for (Host host : entry.getKey()) {
        sb.append(host.getAddress().toString()).append(",");
      }
      sb.append(":");
      for (BatchStatement bs : entry.getValue()) {
        sb.append(bs.size()).append(",");
      }

      sb.append("|");

    }
    logger.debug(sb.toString());
  }
}
 
Example 4
Source File: WebXml.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private static <T> boolean mergeMap(Map<String,T> fragmentMap,
        Map<String,T> mainMap, Map<String,T> tempMap, WebXml fragment,
        String mapName) {
    for (Entry<String, T> entry : fragmentMap.entrySet()) {
        final String key = entry.getKey();
        if (!mainMap.containsKey(key)) {
            // Not defined in main web.xml
            T value = entry.getValue();
            if (tempMap.containsKey(key)) {
                if (value != null && !value.equals(
                        tempMap.get(key))) {
                    log.error(sm.getString(
                            "webXml.mergeConflictString",
                            mapName,
                            key,
                            fragment.getName(),
                            fragment.getURL()));
                    return false;
                }
            } else {
                tempMap.put(key, value);
            }
        }
    }
    return true;
}
 
Example 5
Source File: TestClock.java    From here-aaa-java-sdk with Apache License 2.0 5 votes vote down vote up
protected void runAllPending() {
    List<Entry<Runnable, Long>> newList = new ArrayList<Entry<Runnable, Long>>();
    for (int i = 0; i < scheduledRunnables.size(); i++) {
        Entry<Runnable, Long> entry = scheduledRunnables.get(i);
        long runAt = entry.getValue();
        if (currentTimeMillis() >= runAt) {
            Runnable runnable = entry.getKey();
            runnable.run();
        } else {
            newList.add(entry);
        }
    }
    scheduledRunnables = newList;
}
 
Example 6
Source File: OffHeapStorageArea.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
private int getIndexForPage(Page p) {
  for (Entry<Integer, Page> e : pages.entrySet()) {
    if (e.getValue() == p) {
      return e.getKey();
    }
  }

  return -1;
}
 
Example 7
Source File: VendorNameMgr.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getDatabaseVendorName(String url) {
    String vendorName = "";
    for(Entry<String, String> entry : vendorNameToUrlMap.entrySet()) {
        if(url.indexOf(entry.getValue()) != -1){
            vendorName = entry.getKey();
            break;
        }
    }
    return vendorName;
}
 
Example 8
Source File: HumanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testChildrenMapAsRoot() {
    String etalon = Util.getLocalResource("recursive/with-children-as-map.yaml");

    Constructor constructor = new Constructor();
    TypeDescription Human2Description = new TypeDescription(Human2.class);
    Human2Description.putMapPropertyType("children", Human2.class, String.class);
    constructor.addTypeDescription(Human2Description);

    Yaml yaml = new Yaml(constructor);
    Map<Human2, String> children2 = (Map<Human2, String>) yaml.load(etalon);
    assertNotNull(children2);
    assertEquals(2, children2.size());

    Entry<Human2, String> firstEntry = children2.entrySet().iterator().next();
    Human2 firstChild = firstEntry.getKey();

    Human2 father2 = firstChild.getFather();
    assertEquals("Father", father2.getName());
    assertEquals("Mother", firstChild.getMother().getName());
    assertSame(father2, father2.getBankAccountOwner());
    assertSame(father2.getPartner(), firstChild.getMother());
    assertSame(father2, firstChild.getMother().getPartner());

    assertSame(father2.getPartner().getChildren(), children2);

    validateMapKeys(children2);
}
 
Example 9
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public final void removeHandler(MessageHandler handler) {
    Map<Class<?>, Boolean> types = ClassUtils.getHandlerTypes(handler.getClass());
    for (Entry<Class<?>, Boolean> e : types.entrySet()) {
        Class<?> type = e.getKey();
        List<HandlerWrapper> handlerWrappers = createHandlerWrappers(type, handler, e.getValue());
        for (HandlerWrapper handlerWrapper : handlerWrappers) {
            FrameType frameType = handlerWrapper.getFrameType();
            HandlerWrapper wrapper = handlers.get(frameType);
            if (wrapper != null && wrapper.getMessageType() == type) {
                handlers.remove(frameType, wrapper);
            }
        }
    }
}
 
Example 10
Source File: WordsFAResult.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/** 给外部匹配结果传值 */
public void setAllExterMatchWords(Map<Integer, Integer> allExterMathWords){
	Iterator<Entry<Integer, Integer>> it = allExterMathWords.entrySet().iterator();
	while(it.hasNext()){
		Entry<Integer, Integer> entry = it.next();
		int matchRate = entry.getKey();
		int words = entry.getValue();
		setAllExterMatchWords(matchRate, words);
	}
}
 
Example 11
Source File: DescriptorUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/** 
 * Method for building a descriptor list on the basis of document map as it is given in the HtrTrainingDialog of TranskribusSwtGui.
 * <br><br>
 * If no status is specified all pages of the document are selected, then the descriptor for the specific document 
 * will not specify any pages, reducing the payload when submitting it to the server. 
 * 
 * @param map the document map including the selected pages each with a list of transcripts
 * @param status if not null, then the most recent version with this status is chosen
 * @return
 */
public static List<DocumentSelectionDescriptor> buildSelectionDescriptorList(Map<TrpDocMetadata, List<TrpPage>> map, PageTranscriptSelector selector, EditStatus status) {
	final PageTranscriptSelector internalSelector; 
	if(selector == null) {
		//use base implementation
		logger.debug("No TrainDataSelector given! Falling back to base implementation.");
		internalSelector = new PageTranscriptSelector();
	} else {
		internalSelector = selector;
	}
	List<DocumentSelectionDescriptor> list = new LinkedList<>();

	for (Entry<TrpDocMetadata, List<TrpPage>> e : map.entrySet()) {
		DocumentSelectionDescriptor dsd = new DocumentSelectionDescriptor();
		TrpDocMetadata md = e.getKey();
		dsd.setDocId(md.getDocId());
		List<TrpPage> selectedPages = e.getValue();
		
		if(status != null || selectedPages.size() != md.getNrOfPages() 
				|| !selectedPages.stream().allMatch(p -> internalSelector.isQualifiedForTraining(p, status))) {
			//build detailed descriptor
			List<PageDescriptor> pdList = buildPageSelectionDescriptor(selectedPages, internalSelector, status);
			
			if(pdList.isEmpty()) {
				logger.debug("All pages discarded due to EditStatus selection. Ignoring document {}", dsd.getDocId());
				continue;
			}
			
			dsd.setPages(pdList);
		} else {
			//if all pages of the document are selected and qualify for training => set docId only. Payload of subsequent POST to server may get too large otherwise
			logger.debug("All pages selected and qualified. Setting docId only.");
		}
		list.add(dsd);
	}

	return list;
}
 
Example 12
Source File: Pair.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks for equality with Entries to match {@link #hashCode()}
 */
@Override
public final boolean equals(final @Nullable Object obj) {
	if (obj == this)
		return true;
	if (!(obj instanceof Entry))
		return false;
	final Entry<?, ?> other = (Entry<?, ?>) obj;
	final T1 first = this.first;
	final T2 second = this.second;
	return (first == null ? other.getKey() == null : first.equals(other.getKey())) &&
			(second == null ? other.getValue() == null : second.equals(other.getValue()));
}
 
Example 13
Source File: AbstractMetricsContext.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 *  Emits the records.
 */
private synchronized void emitRecords() throws IOException {
  for (String recordName : bufferedData.keySet()) {
    RecordMap recordMap = bufferedData.get(recordName);
    synchronized (recordMap) {
      Set<Entry<TagMap, MetricMap>> entrySet = recordMap.entrySet ();
      for (Entry<TagMap, MetricMap> entry : entrySet) {
        OutputRecord outRec = new OutputRecord(entry.getKey(), entry.getValue());
        emitRecord(contextName, recordName, outRec);
      }
    }
  }
  flush();
}
 
Example 14
Source File: SVGInteractiveRenderer.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param sb
 * @param propMap
 */
private static StringBuilder getPropertiesJS( 
		EMap<String, String> propMap )
{
	StringBuilder sb = new StringBuilder();
	for ( Entry<String, String> entry : propMap.entrySet( ) )
	{
		String key = entry.getKey();
		String properties = entry.getValue( );
		if ( MenuStylesKeyType.MENU.getName().equals( key ) )
		{
			sb.append( "\t menuInfo.menuStyles = '" + CSSHelper.getStylingHyphenFormat( properties ) + "';\n");//$NON-NLS-1$//$NON-NLS-2$
		}
		else if ( MenuStylesKeyType.MENU_ITEM.getName( ).equals( key  ) )
		{
			sb.append( "\t menuInfo.menuItemStyles = '" + CSSHelper.getStylingHyphenFormat( properties ) + "';\n");//$NON-NLS-1$//$NON-NLS-2$
		}
		else if ( MenuStylesKeyType.ON_MOUSE_OVER.getName( ).equals(key))
		{
			sb.append( "\t menuInfo.mouseOverStyles = '" + CSSHelper.getStylingHyphenFormat( properties ) + "';\n");//$NON-NLS-1$//$NON-NLS-2$
		}
		else if (MenuStylesKeyType.ON_MOUSE_OUT.getName( ).equals(key)) 
		{
			sb.append( "\tmenuInfo.mouseOutStyles = '" + CSSHelper.getStylingHyphenFormat( properties )  + "';\n");//$NON-NLS-1$//$NON-NLS-2$
		}
	}
	return sb;
}
 
Example 15
Source File: ClassFields.java    From reflectutils with Apache License 2.0 5 votes vote down vote up
/**
 * Get the types for fields in a class but filter the fields to get the types for
 * @param filter (optional) indicates the fields to return the types for, can be null for defaults
 * @return the map of fieldName -> field type
 */
public Map<String, Class<?>> getFieldTypes(FieldsFilter filter) {
    OrderedMap<String, Class<?>> fieldTypes = new ArrayOrderedMap<String, Class<?>>();
    fieldTypes.setName(getStoredClass().getName());
    for (Entry<String, ClassProperty> entry : namesToProperties.getEntries()) {
        String name = entry.getKey();
        ClassProperty cp = entry.getValue();
        if ( isFieldInFilter(cp, filter) ) {
            fieldTypes.put(name, cp.getType());
        }
    }
    return fieldTypes;
}
 
Example 16
Source File: Crop.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
public int getCurrentPhaseNum() {
	for (Entry<Integer, Phase> entry : phases.entrySet()) {
		if (entry.getValue().getPhaseType() == phaseType) {
			return entry.getKey();
		}
	}
	return -1;
}
 
Example 17
Source File: WordsFA.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 内部匹配 备注,是将一个source节点拿去跟所有的source节点进行匹配,并称这个source节点为比较者,其他所有的source节点为被比较者
 * 关于上下文匹配,在获取分割xliff文件时就没有必要去做了,故在获取加权系数时,传入两个空值即可
 * @param rowId
 *            : 被比较者的trans-unit节点的唯一标识符
 * @param srcContent
 *            : 被比较者的trans-unit节点的source子节点的完整内容(包括标记)
 * @param srcPureText
 *            : 被比较者的trans-unit节点的source子节点的纯文本
 * @param preTextHash
 *            上文的hash值
 * @param nextTexthash
 *            下文的hash值
 */
public int internalMatching(String rowId, String srcPureText, String tagStr, int textLength,
		String preTextHash, String nextTexthash, int interNewWordsMaxMatchRate) {
	int matchRate = 0; // 匹配率
	// System.out.println("长度为="+srcContent.length());
	//System.out.println("rowId = " + rowId);
	//System.out.println("ignoreTag = " + ignoreTag);
	
	int fileSize = model.getAnalysisIFileList().size();
	List<IFile> fileList = model.getAnalysisIFileList();
	
	for (int fileIndex = 0; fileIndex < fileSize; fileIndex++) {
		IFile iFile = fileList.get(fileIndex);
		String filePath = iFile.getLocation().toOSString();
		Map<String, WordsFABean> fileSrcTextMap = allSrcTextsMap.get(filePath);

		Iterator<Entry<String, WordsFABean>> it = fileSrcTextMap.entrySet().iterator();
		WordsFABean curBean;
		while (it.hasNext()) {
			Entry<String, WordsFABean> entry = (Entry<String, WordsFABean>) it.next();
			String curRowId = entry.getKey();

			// 比较者不与自己进行比较
			if (rowId.equals(curRowId)) {
				continue;
			}

			curBean = entry.getValue();
			String curSrcPureText = curBean.getSrcPureText();

			if (!checkIsideal(ignoreCase ? srcPureText.toLowerCase() : srcPureText, 
					ignoreCase ? curSrcPureText.toLowerCase() : curSrcPureText, interNewWordsMaxMatchRate)) { 
				continue;
			}

			// long time2 = System.currentTimeMillis();
			int curMatchRate = 0;
			curMatchRate = MatchQuality.similarity(ignoreCase ? srcPureText.toLowerCase() : srcPureText, 
					ignoreCase ? curSrcPureText.toLowerCase() : curSrcPureText);
			if (!ignoreTag) {
				String curTagStr = curBean.getTagStr();
				if (!curTagStr.equals(tagStr)) {
					curMatchRate -= tagPenalty;
				}
			}

			if (curMatchRate > matchRate) {
				matchRate = curMatchRate;
			}
			
			//如果当前文本段的匹配率小于本次所比较的匹配率,则重新刷新匹配率
			curBean.setThisMatchRate(curMatchRate);
			
			// System.out.println("比较时= " + (System.currentTimeMillis() - time2));
		}
	}
	
	return matchRate;
}
 
Example 18
Source File: ShardIndexQueryTransformer.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Override
public EventBase transform(Entry<Key,Value> input) {
    
    log.debug("Transform got " + input);
    @SuppressWarnings("unchecked")
    Entry<Key,Value> entry = (Entry<Key,Value>) input;
    
    if (entry.getKey() == null && entry.getValue() == null) {
        return null;
    }
    
    if (null == entry.getKey() || null == entry.getValue()) {
        throw new IllegalArgumentException("Null key or value. Key:" + entry.getKey() + ", Value: " + entry.getValue());
    }
    
    EventBase event = responseObjectFactory.getEvent();
    ColumnVisibility columnVisibility = new ColumnVisibility(entry.getKey().getColumnVisibility());
    Map<String,String> markings;
    try {
        markings = this.markingFunctions.translateFromColumnVisibilityForAuths(columnVisibility, this.auths);
    } catch (Exception e1) {
        throw new RuntimeException("could not make markings from: " + columnVisibility);
    }
    event.setMarkings(markings);
    
    List<FieldBase> fields = new ArrayList<>();
    
    Key key = entry.getKey();
    String row = key.getRow().toString();
    String cf = key.getColumnFamily().toString();
    String cq = key.getColumnQualifier().toString();
    String cv = key.getColumnVisibility().toString();
    
    fields.add(makeField("VALUE", markings, cv, 0L, row));
    /**
     * Added query model to alias FIELD
     */
    fields.add(makeField("FIELD", markings, cv, 0L, myQueryModel.aliasFieldNameReverseModel(cf)));
    fields.add(makeField("DATE", markings, cv, 0L, cq.substring(0, 8)));
    fields.add(makeField("DATA TYPE", markings, cv, 0L, cq.substring(9)));
    // Parse the UID.List object from the value
    Uid.List uidList = null;
    long count = 0;
    try {
        uidList = Uid.List.parseFrom(entry.getValue().get());
        if (null != uidList) {
            count = uidList.getCOUNT();
        }
    } catch (InvalidProtocolBufferException e) {
        log.error("Failed to parse Uid List", e);
    }
    fields.add(makeField("RECORD COUNT", markings, cv, 0L, Long.toString(count)));
    event.setFields(fields);
    
    Metadata metadata = new Metadata();
    String id = logic.getTableName() + ":" + row + ":" + cf + ":" + cq;
    metadata.setInternalId(UUID.nameUUIDFromBytes(id.getBytes()).toString());
    metadata.setDataType(entry.getKey().getColumnFamily().toString());
    metadata.setRow(entry.getKey().getRow().toString());
    metadata.setTable(logic.getTableName());
    event.setMetadata(metadata);
    return event;
}
 
Example 19
Source File: UpgradeFrom7To8Test.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void assertConfiguredObjects() throws Exception
{
    Map<UUID, UpgradeConfiguredObjectRecord> configuredObjects = loadConfiguredObjects();
    assertEquals("Unexpected number of configured objects", 11, configuredObjects.size());

    Map<UUID, Map<String, Object>> expected = new HashMap<UUID, Map<String, Object>>();

    String configVersion = "0.3";
    expected.putAll(createExpectedVirtualHost(configVersion));

    expected.putAll(createExpectedQueue("queue1", Boolean.FALSE, null, null));
    expected.putAll(createExpectedQueue("queue2", Boolean.FALSE, null, null));

    expected.putAll(createExpectedExchangeMap("myexch", "direct"));

    expected.putAll(createExpectedBindingMap("queue1", "queue1", "amq.direct", null));
    expected.putAll(createExpectedBindingMap("queue1", "queue1", "myexch", null));
    expected.putAll(createExpectedBindingMap("queue2", "queue2", "amq.fanout", null));

    expected.putAll(createExpectedExchangeMap("amq.direct", "direct"));
    expected.putAll(createExpectedExchangeMap("amq.fanout", "fanout"));
    expected.putAll(createExpectedExchangeMap("amq.match", "headers"));
    expected.putAll(createExpectedExchangeMap("amq.topic", "topic"));

    MapJsonSerializer jsonSerializer = new MapJsonSerializer();
    for (Entry<UUID, UpgradeConfiguredObjectRecord> entry : configuredObjects.entrySet())
    {
        UpgradeConfiguredObjectRecord object = entry.getValue();

        UUID actualKey = entry.getKey();
        String actualType = object.getType();
        String actualJson = object.getAttributes();
        Map<String, Object> actualDeserializedAttributes = jsonSerializer.deserialize(actualJson);

        assertTrue("Entry UUID " + actualKey + " of type " +  actualType + " is unexpected", expected.containsKey(actualKey));

        Map<String, Object> expectedDeserializedAttributes = expected.get(actualKey);

        assertEquals("Entry UUID " + actualKey + " of type " +  actualType + " has uenxpected deserialised value, json was: " + actualJson,
                     expectedDeserializedAttributes, actualDeserializedAttributes);
    }
}
 
Example 20
Source File: HashedDir.java    From Launcher with GNU General Public License v3.0 4 votes vote down vote up
private HashedDir sideDiff(HashedDir other, FileNameMatcher matcher, Deque<String> path, boolean mismatchList) {
    HashedDir diff = new HashedDir();
    for (Entry<String, HashedEntry> mapEntry : map.entrySet()) {
        String name = mapEntry.getKey();
        HashedEntry entry = mapEntry.getValue();
        path.add(name);

        // Should update?
        boolean shouldUpdate = matcher == null || matcher.shouldUpdate(path);

        // Not found or of different type
        Type type = entry.getType();
        HashedEntry otherEntry = other.map.get(name);
        if (otherEntry == null || otherEntry.getType() != type) {
            if (shouldUpdate || mismatchList && otherEntry == null) {
                diff.map.put(name, entry);

                // Should be deleted!
                if (!mismatchList)
                    entry.flag = true;
            }
            path.removeLast();
            continue;
        }

        // Compare entries based on type
        switch (type) {
            case FILE:
                HashedFile file = (HashedFile) entry;
                HashedFile otherFile = (HashedFile) otherEntry;
                if (mismatchList && shouldUpdate && !file.isSame(otherFile))
                    diff.map.put(name, entry);
                break;
            case DIR:
                HashedDir dir = (HashedDir) entry;
                HashedDir otherDir = (HashedDir) otherEntry;
                if (mismatchList || shouldUpdate) { // Maybe isn't need to go deeper?
                    HashedDir mismatch = dir.sideDiff(otherDir, matcher, path, mismatchList);
                    if (!mismatch.isEmpty())
                        diff.map.put(name, mismatch);
                }
                break;
            default:
                throw new AssertionError("Unsupported hashed entry type: " + type.name());
        }

        // Remove this path entry
        path.removeLast();
    }
    return diff;
}