Java Code Examples for java.util.Map#containsValue()

The following examples show how to use java.util.Map#containsValue() . 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: RoutingManager.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Nullable
private Set<String> getOnlineSegments(String tableNameWithType) {
  ZNRecord znRecord = _zkDataAccessor.get(_idealStatePathPrefix + tableNameWithType, null, AccessOption.PERSISTENT);
  if (znRecord != null) {
    Map<String, Map<String, String>> segmentAssignment = znRecord.getMapFields();
    Set<String> onlineSegments = new HashSet<>(HashUtil.getHashMapCapacity(segmentAssignment.size()));
    for (Map.Entry<String, Map<String, String>> entry : segmentAssignment.entrySet()) {
      Map<String, String> instanceStateMap = entry.getValue();
      if (instanceStateMap.containsValue(SegmentStateModel.ONLINE) || instanceStateMap
          .containsValue(SegmentStateModel.CONSUMING)) {
        onlineSegments.add(entry.getKey());
      }
    }
    return onlineSegments;
  } else {
    return null;
  }
}
 
Example 2
Source File: TimeZoneNameUtility.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static String[] examineAliases(TimeZoneNameProvider tznp, Locale locale,
                                       String id,
                                       Map<String, String> aliases) {
    if (aliases.containsValue(id)) {
        for (Map.Entry<String, String> entry : aliases.entrySet()) {
            if (entry.getValue().equals(id)) {
                String alias = entry.getKey();
                String[] names = buildZoneStrings(tznp, locale, alias);
                if (names != null) {
                    return names;
                }
                names = examineAliases(tznp, locale, alias, aliases);
                if (names != null) {
                    return names;
                }
            }
        }
    }

    return null;
}
 
Example 3
Source File: UniqueNullValue.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Map<TestEnum, Integer> map = new EnumMap<>(TestEnum.class);

    map.put(TestEnum.e00, 0);
    if (false == map.containsValue(0)) {
        throw new RuntimeException("EnumMap unexpectedly missing 0 value");
    }
    if (map.containsValue(null)) {
        throw new RuntimeException("EnumMap unexpectedly holds null value");
    }

    map.put(TestEnum.e00, null);
    if (map.containsValue(0)) {
        throw new RuntimeException("EnumMap unexpectedly holds 0 value");
    }
    if (false == map.containsValue(null)) {
        throw new RuntimeException("EnumMap unexpectedly missing null value");
    }
}
 
Example 4
Source File: TimeZoneNameUtility.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static String examineAliases(TimeZoneNameProvider tznp, Locale locale,
                                     String requestID, String tzid, int style,
                                     Map<String, String> aliases) {
    if (aliases.containsValue(tzid)) {
        for (Map.Entry<String, String> entry : aliases.entrySet()) {
            if (entry.getValue().equals(tzid)) {
                String alias = entry.getKey();
                String name = getName(tznp, locale, requestID, style, alias);
                if (name != null) {
                    return name;
                }
                name = examineAliases(tznp, locale, requestID, alias, style, aliases);
                if (name != null) {
                    return name;
                }
            }
        }
    }
    return null;
}
 
Example 5
Source File: UniqueNullValue.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Map<TestEnum, Integer> map = new EnumMap<>(TestEnum.class);

    map.put(TestEnum.e00, 0);
    if (false == map.containsValue(0)) {
        throw new RuntimeException("EnumMap unexpectedly missing 0 value");
    }
    if (map.containsValue(null)) {
        throw new RuntimeException("EnumMap unexpectedly holds null value");
    }

    map.put(TestEnum.e00, null);
    if (map.containsValue(0)) {
        throw new RuntimeException("EnumMap unexpectedly holds 0 value");
    }
    if (false == map.containsValue(null)) {
        throw new RuntimeException("EnumMap unexpectedly missing null value");
    }
}
 
Example 6
Source File: AsMapTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@CheckNoWriter @CheckNoStats
@SuppressWarnings("ReturnValueIgnored")
@CacheSpec(removalListener = { Listener.DEFAULT, Listener.REJECTING })
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
public void containsValue_null(Map<Integer, Integer> map, CacheContext context) {
  map.containsValue(null);
}
 
Example 7
Source File: ExportAssetsTag.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Map<Integer, String> getTagToNameMap() {
    Map<Integer, String> exportNames = new HashMap<>();
    for (int i = 0; i < tags.size(); i++) {
        int tagId = tags.get(i);
        String name = names.get(i);
        if ((!exportNames.containsKey(tagId)) && (!exportNames.containsValue(name))) {
            exportNames.put(tagId, name);
        }
    }
    return exportNames;
}
 
Example 8
Source File: AbstractTable.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean containsValue(@Nullable Object value) {
  for (Map<C, V> row : rowMap().values()) {
    if (row.containsValue(value)) {
      return true;
    }
  }
  return false;
}
 
Example 9
Source File: KafkaManager.java    From spark-streaming-direct-kafka with Apache License 2.0 5 votes vote down vote up
private static void fillInLatestOffsets(Map<TopicAndPartition, Long> offsets, Map<String, String> kafkaParams) {
    if (offsets.containsValue(null)) {

        Set<TopicAndPartition> needOffset = offsets.entrySet().stream().filter(entry -> entry.getValue() == null)
                .map(Map.Entry::getKey).collect(Collectors.toSet());
        log.info("No initial offsets for " + needOffset + " reading from Kafka");

        // The high price of calling private Scala stuff:
        @SuppressWarnings("unchecked")
        scala.collection.immutable.Map<String, String> kafkaParamsScalaMap =
                (scala.collection.immutable.Map<String, String>)
                        scala.collection.immutable.Map$.MODULE$.apply(JavaConversions.mapAsScalaMap(kafkaParams)
                                .toSeq());
        @SuppressWarnings("unchecked")
        scala.collection.immutable.Set<TopicAndPartition> needOffsetScalaSet =
                (scala.collection.immutable.Set<TopicAndPartition>)
                        scala.collection.immutable.Set$.MODULE$.apply(JavaConversions.asScalaSet(needOffset)
                                .toSeq());

        KafkaCluster kc = new KafkaCluster(kafkaParamsScalaMap);
        Map<TopicAndPartition, ?> leaderOffsets =
                JavaConversions.mapAsJavaMap(kc.getLatestLeaderOffsets(needOffsetScalaSet).right().get());
        leaderOffsets.forEach((tAndP, leaderOffsetsObj) -> {
            // Can't reference LeaderOffset class, so, hack away:
            Matcher m = Pattern.compile("LeaderOffset\\([^,]+,[^,]+,([^)]+)\\)").matcher(leaderOffsetsObj
                    .toString());
            Preconditions.checkState(m.matches());
            offsets.put(tAndP, Long.valueOf(m.group(1)));
        });
    }
}
 
Example 10
Source File: AbstractTable.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean containsValue(@Nullable Object value) {
  for (Map<C, V> row : rowMap().values()) {
    if (row.containsValue(value)) {
      return true;
    }
  }
  return false;
}
 
Example 11
Source File: SettlementConfig.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Obtains the key of a value in a particular map
 * 
 * @param map
 * @param name
 * @return
 */
public int getMapKey(Map<Integer, String> map, String name) {
	int result = -1;
	if (map.containsValue(name)) {
		for (Map.Entry<Integer, String> e : map.entrySet()) {
			Integer key = e.getKey();
			Object value2 = e.getValue();
			if ((value2.toString()).equalsIgnoreCase(name)) {
				result = key;
			}
		}
	}

	return result;
}
 
Example 12
Source File: ClusterPublicEndpointManagementService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void changeGatewayAddress(Stack stack, Map<String, String> newAddressesByFqdn) {
    InstanceMetaData gatewayInstanceMetadata = stack.getPrimaryGatewayInstance();
    String ipWrapper = gatewayInstanceMetadata.getPublicIpWrapper();

    if (newAddressesByFqdn.containsValue(ipWrapper)) {
        LOGGER.info("Gateway's DNS entry needs to be updated because primary gateway IP has been updated to: '{}'", ipWrapper);
        changeGateway(stack, ipWrapper);
    }
}
 
Example 13
Source File: XFLConverter.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
private static Map<Integer, String> getCharacterClasses(ReadOnlyTagList tags) {
    Map<Integer, String> ret = new HashMap<>();
    for (Tag t : tags) {
        if (t instanceof SymbolClassTag) {
            SymbolClassTag sc = (SymbolClassTag) t;
            for (int i = 0; i < sc.tags.size(); i++) {
                if (!ret.containsKey(sc.tags.get(i)) && !ret.containsValue(sc.names.get(i))) {
                    ret.put(sc.tags.get(i), sc.names.get(i));
                }
            }
        }
    }
    return ret;
}
 
Example 14
Source File: TranslationProductComponentAction.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public APIResponseDTO checkTranslationResult(String productName, String component, String version, String locale, APIResponseDTO resp) {
Map<String, String> r = checkTranslationStatus(productName, component, version, locale, resp);
Object o = resp.getData();
if(o instanceof ComponentMessagesDTO) {
	((ComponentMessagesDTO)o).setStatus(JSONObject.toJSONString(r));
}
  	if(!r.isEmpty() && !r.containsValue("0")) {
  		return super.handleResponse(APIResponseStatus.TRANSLATION_READY, resp.getData());
  	} else {
  		return super.handleResponse(APIResponseStatus.TRANSLATION_NOT_READY, resp.getData());    	
  	}    	
  }
 
Example 15
Source File: AxolotlService.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
    SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
    Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName());
    Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName());
    if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
        FetchStatus report = null;
        if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
            report = FetchStatus.SUCCESS;
        } else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
            report = FetchStatus.SUCCESS_VERIFIED;
        } else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
            report = FetchStatus.SUCCESS_TRUSTED;
        } else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
            report = FetchStatus.ERROR;
        }
        mXmppConnectionService.keyStatusUpdated(report);
    }
    if (Config.REMOVE_BROKEN_DEVICES) {
        Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
        boolean publish = false;
        for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
            int id = entry.getKey();
            if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
                publish = true;
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
            }
        }
        if (publish) {
            publishOwnDeviceId(ownDeviceIds);
        }
    }
}
 
Example 16
Source File: Salut.java    From Salut with MIT License 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setupDNSRespondersWithDevice(final SalutDeviceCallback onDeviceFound, final boolean callContinously) {
     /*Here, we register a listener for when services are actually found. The WiFi P2P specification notes that we need two types of
     *listeners, one for a DNS service and one for a TXT record. The DNS service listener is invoked whenever a service is found, regardless
     *of whether or not it is yours. To that determine if it is, we must compare our service name with the service name. If it is our service,
     * we simply log.*/

    WifiP2pManager.DnsSdServiceResponseListener serviceListener = new WifiP2pManager.DnsSdServiceResponseListener() {
        @Override
        public void onDnsSdServiceAvailable(String instanceName, String serviceNameAndTP, WifiP2pDevice sourceDevice) {

            Log.d(TAG, "Found " + instanceName + " " + serviceNameAndTP);
        }
    };

    /*The TXT record contains specific information about a service and it's listener can also be invoked regardless of the device. Here, we
    *double check if the device is ours, and then we go ahead and pull that specific information from it and put it into an Map. The function
    *that was passed in early is also called.*/
    WifiP2pManager.DnsSdTxtRecordListener txtRecordListener = new WifiP2pManager.DnsSdTxtRecordListener() {
        @Override
        public void onDnsSdTxtRecordAvailable(String serviceFullDomainName, Map<String, String> record, WifiP2pDevice device) {


            if (!foundDevices.isEmpty()) {
                for (SalutDevice found : foundDevices) {
                    if (found.deviceName.equals(device.deviceName)) {
                        return;
                    }
                }
            }

            if (record.containsValue(thisDevice.serviceName)) {
                SalutDevice foundDevice = new SalutDevice(device, record);

                foundDevices.add(foundDevice);
                if (callContinously) {
                    onDeviceFound.call(foundDevice);
                } else {
                    if (!firstDeviceAlreadyFound) {
                        onDeviceFound.call(foundDevice);
                        firstDeviceAlreadyFound = true;
                    }
                }
            }
        }
    };

    manager.setDnsSdResponseListeners(channel, serviceListener, txtRecordListener);
    respondersAlreadySet = true;
}
 
Example 17
Source File: SWF.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
public boolean generatePCodeSwdFile(File file, Map<String, Set<Integer>> breakpoints) throws IOException {
    DebugIDTag dit = getDebugId();
    if (dit == null) {
        return false;
    }
    List<SWD.DebugItem> items = new ArrayList<>();
    Map<String, ASMSource> asms = getASMs(true);

    try {
        items.add(new SWD.DebugId(dit.debugId));

    } catch (Throwable t) {
        logger.log(Level.SEVERE, "message", t);
        return false;
    }

    int moduleId = 0;
    List<String> names = new ArrayList<>(asms.keySet());
    Collections.sort(names);
    for (String name : names) {
        moduleId++;
        String sname = "#PCODE " + name;
        int bitmap = SWD.bitmapAction;
        items.add(new SWD.DebugScript(moduleId, bitmap, sname, ""));

        HighlightedTextWriter writer = new HighlightedTextWriter(Configuration.getCodeFormatting(), true);
        try {
            asms.get(name).getASMSource(ScriptExportMode.PCODE, writer, null);
        } catch (InterruptedException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        List<Highlighting> hls = writer.instructionHilights;

        Map<Integer, Integer> offsetToLine = new TreeMap<>();
        String txt = writer.toString();
        txt = txt.replace("\r", "");
        int line = 1;
        for (int i = 0; i < txt.length(); i++) {
            Highlighting h = Highlighting.searchPos(hls, i);
            if (h != null) {
                int of = (int) h.getProperties().fileOffset;
                if (of > -1 && !offsetToLine.containsKey(of) && !offsetToLine.containsValue(line)) {
                    offsetToLine.put(of, line);
                }
            }
            if (txt.charAt(i) == '\n') {
                line++;
            }
        }

        for (int ofs : offsetToLine.keySet()) {
            items.add(new SWD.DebugOffset(moduleId, offsetToLine.get(ofs), ofs));
        }

        if (breakpoints.containsKey(sname)) {
            Set<Integer> bplines = breakpoints.get(sname);
            for (int bpline : bplines) {
                if (offsetToLine.containsValue(bpline)) {
                    try {
                        SWD.DebugBreakpoint dbp = new SWD.DebugBreakpoint(moduleId, bpline);
                        items.add(dbp);
                    } catch (IllegalArgumentException iex) {
                        logger.log(Level.WARNING, "Cannot generate breakpoint to SWD: {0}", iex.getMessage());
                    }
                }
            }
        }
    }

    SWD swd = new SWD(7, items);
    try (FileOutputStream fis = new FileOutputStream(file)) {
        swd.saveTo(fis);
    }
    return true;
}
 
Example 18
Source File: OrganisationMetricsActor.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
private String getQueryRequest(String periodStr, String orgId, String operation) {
  ProjectLogger.log("orgId " + orgId);
  Map<String, Object> dateMap = getStartAndEndDate(periodStr);
  Map<String, String> operationMap = new LinkedHashMap<>();
  ProjectLogger.log("period" + dateMap);
  switch (operation) {
    case "Create":
      operationMap.put("dateKey", "createdOn");
      operationMap.put("status", OrganisationMetricsUtil.ContentStatus.Draft.name());
      operationMap.put("userActionKey", "createdBy");
      operationMap.put("contentCount", "required");
      break;

    case "Review":
      operationMap.put("dateKey", "lastSubmittedOn");
      operationMap.put("status", OrganisationMetricsUtil.ContentStatus.Review.name());
      break;

    case "Publish":
      operationMap.put("dateKey", "lastPublishedOn");
      operationMap.put("status", OrganisationMetricsUtil.ContentStatus.Live.name());
      operationMap.put("userActionKey", "lastPublishedBy");
      break;

    default:
      operationMap.put("dateKey", "");
      operationMap.put("status", "");
      operationMap.put("userActionKey", "");
      break;
  }
  StringBuilder builder = new StringBuilder();
  builder
      .append("{\"request\":{\"rawQuery\":{\"query\":{\"bool\":{\"must\":[{\"range\":{\"")
      .append(operationMap.get("dateKey"))
      .append("\":{\"gte\":\"")
      .append(dateMap.get(STARTDATE) + "\",\"lte\":\"" + dateMap.get(ENDDATE) + "\"}}}")
      .append(",{\"bool\":{\"should\":[{\"match\":{\"contentType.raw\":\"Resource\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"Collection\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"TextBook\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"TextBookUnit\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"Course\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"CourseUnit\"}}]}},")
      .append("{\"match\":{\"createdFor.raw\":\"" + orgId + "\"}}")
      .append(",{\"match\":{\"status.raw\":\"" + operationMap.get("status"))
      .append("\"}}]}},\"aggs\":{\"");
  if (operationMap.containsValue("createdOn")) {
    builder
        .append(operationMap.get("dateKey") + "\":{\"date_histogram\":{\"field\":\"")
        .append(operationMap.get("dateKey"))
        .append("\",\"interval\":\"" + dateMap.get(INTERVAL) + "\",\"format\":\"")
        .append(dateMap.get(FORMAT) + "\"")
        .append(",\"time_zone\":\"+05:30\",\"extended_bounds\":{\"min\":")
        .append(dateMap.get(START_TIME_MILLIS) + ",\"max\":")
        .append(dateMap.get(END_TIME_MILLIS) + "}}},\"");
  }
  builder
      .append("status\":{\"terms\":{\"field\":\"status.raw\",\"include\":[\"")
      .append(operationMap.get("status").toLowerCase() + "\"]},\"aggs\":{\"")
      .append(operationMap.get("dateKey") + "\":{\"date_histogram\":{\"field\":\"")
      .append(operationMap.get("dateKey") + "\",\"interval\":\"" + dateMap.get(INTERVAL))
      .append("\",\"format\":\"" + dateMap.get(FORMAT))
      .append("\",\"time_zone\":\"+05:30\",\"extended_bounds\":{\"min\":")
      .append(dateMap.get(START_TIME_MILLIS) + ",\"max\":")
      .append(dateMap.get(END_TIME_MILLIS))
      .append("}}}}}");
  if (operationMap.containsKey("userActionKey")) {
    builder
        .append(",\"" + operationMap.get("userActionKey") + ".count\":")
        .append("{\"cardinality\":{\"field\":\"" + operationMap.get("userActionKey"))
        .append(".raw\",\"precision_threshold\":100}}");
  }

  if (operationMap.containsKey("contentCount")) {
    builder
        .append(",\"content_count\":{\"terms\":{\"field\":\"contentType.raw\"")
        .append(",\"exclude\":[\"assets\",\"plugin\",\"template\"]}},")
        .append("\"total_content_count\":{\"sum_bucket\":")
        .append("{\"buckets_path\":\"content_count>_count\"}}");
  }
  builder.append("}}}}");
  return builder.toString();
}
 
Example 19
Source File: ConcurrentMapTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "guardedMap", expectedExceptions = NullPointerException.class)
public void containsValue_withNull(Map<Integer, Integer> map) {
  map.containsValue(null);
}
 
Example 20
Source File: EntityType.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object replace(
		Object original,
		Object target,
		SharedSessionContractImplementor session,
		Object owner,
		Map copyCache) throws HibernateException {
	if ( original == null ) {
		return null;
	}
	Object cached = copyCache.get( original );
	if ( cached != null ) {
		return cached;
	}
	else {
		if ( original == target ) {
			return target;
		}
		if ( session.getContextEntityIdentifier( original ) == null &&
				ForeignKeys.isTransient( associatedEntityName, original, Boolean.FALSE, session ) ) {
			// original is transient; it is possible that original is a "managed" entity that has
			// not been made persistent yet, so check if copyCache contains original as a "managed" value
			// that corresponds with some "merge" value.
			if ( copyCache.containsValue( original ) ) {
				return original;
			}
			else {
				// the transient entity is not "managed"; add the merge/managed pair to copyCache
				final Object copy = session.getEntityPersister( associatedEntityName, original )
						.instantiate( null, session );
				copyCache.put( original, copy );
				return copy;
			}
		}
		else {
			Object id = getIdentifier( original, session );
			if ( id == null ) {
				throw new AssertionFailure(
						"non-transient entity has a null id: " + original.getClass()
								.getName()
				);
			}
			id = getIdentifierOrUniqueKeyType( session.getFactory() )
					.replace( id, null, session, owner, copyCache );
			return resolve( id, session, owner );
		}
	}
}