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

The following are Jave code examples for showing how to use containsValue() of the java.util.Map 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: BIMplatform   File: SplitIfcModel.java   View Source Code Vote up 6 votes
public void processObject(IdEObject originObject, Map<Integer, IdEObject> result) {
	if (result.containsValue(originObject)) {
		return;
	}
	result.put(originObject.getExpressId(), originObject);
	for (EStructuralFeature feature : originObject.eClass().getEAllStructuralFeatures()) {
		if (getPackageMetaData().useForDatabaseStorage(originObject.eClass(), feature)) {
			if (feature.isMany()) {
				processList(originObject, feature, result);
			} else {
				Object value = originObject.eGet(feature);
				if (feature.getEType() instanceof EClass) {
					if (value != null) {
						IdEObject referencedObject = (IdEObject) value;
						processObject(referencedObject, result);
					}
				} 
			}
		}
	}
}
 
Example 2
Project: BIMplatform   File: SplitIfcModel.java   View Source Code Vote up 6 votes
public void processList(IdEObject originObject, EStructuralFeature feature, Map<Integer, IdEObject> result) {
	if (result.containsValue(feature)) {
		return;
	}
	if (feature.getEType() instanceof EClass) {
		EList<?> list = (EList<?>) originObject.eGet(feature);
		for (Object o : list) {
			if (o != null) {
				IdEObject listObject = (IdEObject) o;
				if (feature.getEAnnotation("twodimensionalarray") != null) {
					processList(listObject, feature, result);
				} else {
					processObject(listObject, result);
				}
				
			}
		}
	}
}
 
Example 3
Project: openjdk-jdk10   File: UniqueNullValue.java   View Source Code Vote up 6 votes
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
Project: Java-9-Programming-Blueprints   File: BeanPathAdapter.java   View Source Code Vote up 6 votes
/**
 * Synchronizes the {@link Collection} values to the supplied
 * {@link Observable} {@link Map}
 * 
 * @param fromCol
 *            the {@link Collection} that synchronization will derive
 *            from
 * @param oc
 *            the {@link Observable} {@link Map} that should be
 *            synchronized to
 * @return true when the synchronization resulted in a change to the
 *         {@link Collection}/{@link Map}
 */
private boolean syncObservableFromCollectionValues(
		final Collection<Object> fromCol, final Map<Object, Object> oc) {
	boolean changed = false;
	boolean missing = false;
	FieldProperty<?, ?, ?> fp;
	Object fpv;
	int i = -1;
	for (final Object item : fromCol) {
		fp = genFieldProperty(item, null);
		fpv = fp != null ? fp.getDirty() : item;
		missing = !oc.containsValue(fpv);
		changed = !changed ? missing : changed;
		if (collectionSelectionModel == null) {
			oc.put(++i, fpv);
		} else {
			selectCollectionValue(fpv);
		}
	}
	return changed;
}
 
Example 5
Project: satisfy   File: ProxyFixture.java   View Source Code Vote up 6 votes
@Override
public void addCapabilitiesTo(DesiredCapabilities capabilities) {
    Map<String, String> proxyProperties = getProxyProperties();

    if (proxyProperties.size() == 0) {
        return;
    } else if (proxyProperties.containsValue("")) {
        try {
            throw new Exception(
                    "Proxy cannot be set. Please provide all settings " +
                            "needed to setup proxy connection.");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    } else {
        LOGGER.error("Setting proxy ...");
        setProxyTo(capabilities, proxyProperties);
    }
}
 
Example 6
Project: OpenJSharp   File: TimeZoneNameUtility.java   View Source Code Vote up 6 votes
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 7
Project: googles-monorepo-demo   File: AbstractTable.java   View Source Code Vote up 5 votes
@Override
public boolean containsValue(@Nullable Object value) {
  for (Map<C, V> row : rowMap().values()) {
    if (row.containsValue(value)) {
      return true;
    }
  }
  return false;
}
 
Example 8
Project: alevin-svn2   File: MiscelFunctions.java   View Source Code Vote up 5 votes
/**
 * 
 * @param vNode
 *            virtual node
 * @param dem
 *            demand of the virtual node
 * @param filtratedsNodes
 *            set of all nodes to extract the feasible substrate node
 *            candidates
 * 
 * @return The set of substrate nodes accomplishing a demand
 */
public static List<SubstrateNode> findFulfillingNodes(VirtualNode vNode,
		List<SubstrateNode> filtratedsNodes,
		Map<VirtualNode, SubstrateNode> nodeMapping) {
	List<SubstrateNode> nodes = new LinkedList<SubstrateNode>();
	for (SubstrateNode n : filtratedsNodes) {
		if (NodeLinkAssignation.isMappable(vNode, n)
				&& !nodeMapping.containsValue(n)) {
			nodes.add(n);
		}
	}
	return nodes;
}
 
Example 9
Project: TFWebSock   File: SubscriptionHandler.java   View Source Code Vote up 5 votes
public void Subscribe( SubscriptionRequest req, Channel chan)
{
    // Top level: get the sub map that hold the subscriptions for the relevant ecn
    Map<String,Map<String,Channel>> ecnmap = null;
    String ecn = req.getECN( );
    if ( subscriptions.containsKey( ecn)) {
        ecnmap = subscriptions.get( ecn);
    }
    else {
        ecnmap = new HashMap<String,Map<String,Channel>>( );
        subscriptions.put( ecn, ecnmap);
    }
    // Now let's find if there are existing subs for the instrument in question on this ecn
    Map<String,Channel> submap = null;
    String instrument = req.getInstrument( );
    if ( ecnmap.containsKey( instrument)) {
        submap = ecnmap.get( instrument);
    }
    else {
        submap = new HashMap<String,Channel>( );
        ecnmap.put(instrument, submap);
    }
    // Is there already an entry for this channel?
    if ( submap.containsValue( chan)) {
        logr.info( "StockTickerMessageHandler.Subscribe: " + ecn + " already has sub for " + instrument + " on " + chan.toString( ));
        return;
    }
    JSON.MarketDataSubscriptionRequestMessage sreq = new JSON.MarketDataSubscriptionRequestMessage( ecn, instrument, chan);
    try {
        outQ.put( sreq);
    }
    catch (InterruptedException e) {
        logr.info( "StockTickerMessageHandler.Subscribe: outQ.put( ) failed for "
                   + ecn + ":" + instrument + "\n" + e.toString( ));
    }
}
 
Example 10
Project: sstore-soft   File: AbstractTable.java   View Source Code Vote up 5 votes
@Override
public boolean containsValue(@Nullable Object value) {
  for (Map<C, V> row : rowMap().values()) {
    if (row.containsValue(value)) {
      return true;
    }
  }
  return false;
}
 
Example 11
Project: monarch   File: MapCheckJUnitTest.java   View Source Code Vote up 5 votes
static void t9(Map s) {
  int sum = 0;
  int iters = 20;
  timer.start("ContainsValue (/n)     ", iters * s.size());
  int step = absentSize / iters;
  for (int i = 0; i < absentSize; i += step)
    if (s.containsValue(absent[i]))
      ++sum;
  timer.finish();
  reallyAssert(sum != 0);
}
 
Example 12
Project: react-native-samsung-health   File: ConnectionListener.java   View Source Code Vote up 5 votes
@Override
public void onConnected() {
    Log.d(REACT_MODULE, "Health data service is connected.");
    HealthPermissionManager pmsManager = new HealthPermissionManager(mModule.getStore());

    mKeySet = new HashSet<PermissionKey>();
    //mKeySet.add(new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, PermissionType.READ));
    mKeySet.add(new PermissionKey(SamsungHealthModule.STEP_DAILY_TREND_TYPE, PermissionType.READ));

    try {
        // Check whether the permissions that this application needs are acquired
        Map<PermissionKey, Boolean> resultMap = pmsManager.isPermissionAcquired(mKeySet);

        if (resultMap.containsValue(Boolean.FALSE)) {
            // Request the permission for reading step counts if it is not acquired
            pmsManager.requestPermissions(mKeySet, mModule.getContext().getCurrentActivity()).setResultListener(
                new PermissionListener(mModule, mErrorCallback, mSuccessCallback)
            );
        } else {
            // Get the current step count and display it
            Log.d(REACT_MODULE, "COUNT THE STEPS!");
            mSuccessCallback.invoke(true);
        }
    } catch (Exception e) {
        Log.e(REACT_MODULE, e.getClass().getName() + " - " + e.getMessage());
        mErrorCallback.invoke("Permission setting fails");
    }
}
 
Example 13
Project: tomcat7   File: ResourceLinkFactory.java   View Source Code Vote up 5 votes
private static boolean validateGlobalResourceAccess(String globalName) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    while (cl != null) {
        Map<String,String> registrations = globalResourceRegistrations.get(cl);
        if (registrations != null && registrations.containsValue(globalName)) {
            return true;
        }
        cl = cl.getParent();
    }
    return false;
}
 
Example 14
Project: openjdk-jdk10   File: MapCheck.java   View Source Code Vote up 5 votes
static void t9(Map s) {
    int sum = 0;
    int iters = 20;
    timer.start("ContainsValue (/n)     ", iters * s.size());
    int step = absentSize / iters;
    for (int i = 0; i < absentSize; i += step)
        if (s.containsValue(absent[i])) ++sum;
    timer.finish();
    reallyAssert(sum != 0);
}
 
Example 15
Project: gemini.blueprint   File: DefaultMandatoryDependencyManager.java   View Source Code Vote up 5 votes
private boolean checkIfExporterShouldStart(Object exporter, Map<Object, Boolean> importers) {

		if (!importers.containsValue(Boolean.FALSE)) {
			startExporter(exporter);

			if (log.isDebugEnabled())
				log.trace("Exporter [" + exporterToName.get(exporter) + "] started; "
						+ "all its dependencies are satisfied");
			return true;

		} else {
			List<String> unsatisfiedDependencies = new ArrayList<String>(importers.size());

			for (Iterator<Map.Entry<Object, Boolean>> iterator = importers.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<Object, Boolean> entry = iterator.next();
				if (Boolean.FALSE.equals(entry.getValue()))
					unsatisfiedDependencies.add(importerToName.get(entry.getKey()));
			}

			if (log.isTraceEnabled()) {
				log.trace("Exporter [" + exporterToName.get(exporter)
						+ "] not started; there are still unsatisfied dependencies " + unsatisfiedDependencies);
			}

			return false;
		}
	}
 
Example 16
Project: monarch   File: PartitionedRegion.java   View Source Code Vote up 5 votes
public void validateParalleGatewaySenderIds() throws PRLocallyDestroyedException {
  for (String senderId : this.getParallelGatewaySenderIds()) {
    for (PartitionRegionConfig config : this.prRoot.values()) {
      if (config.getGatewaySenderIds().contains(senderId)) {
        Map<String, PartitionedRegion> colocationMap =
            ColocationHelper.getAllColocationRegions(this);
        if (!colocationMap.isEmpty()) {
          if (colocationMap.containsKey(config.getFullPath())) {
            continue;
          } else {
            int prID = config.getPRId();
            PartitionedRegion colocatedPR = PartitionedRegion.getPRFromId(prID);
            PartitionedRegion leader = ColocationHelper.getLeaderRegion(colocatedPR);
            if (colocationMap.containsValue(leader)) {
              continue;
            } else {
              throw new IllegalStateException(
                  LocalizedStrings.PartitionRegion_NON_COLOCATED_REGIONS_1_2_CANNOT_HAVE_SAME_PARALLEL_GATEWAY_SENDER_ID_2
                      .toString(new Object[] {this.getFullPath(), config.getFullPath(),
                          senderId.contains(AsyncEventQueueImpl.ASYNC_EVENT_QUEUE_PREFIX)
                              ? "async event queue" : "gateway sender",
                          senderId}));
            }
          }
        } else {
          throw new IllegalStateException(
              LocalizedStrings.PartitionRegion_NON_COLOCATED_REGIONS_1_2_CANNOT_HAVE_SAME_PARALLEL_GATEWAY_SENDER_ID_2
                  .toString(new Object[] {this.getFullPath(), config.getFullPath(),
                      senderId.contains(AsyncEventQueueImpl.ASYNC_EVENT_QUEUE_PREFIX)
                          ? "async event queue" : "gateway sender",
                      senderId}));
        }

      }
    }
  }
}
 
Example 17
Project: jaffa-framework   File: QuerySaver.java   View Source Code Vote up 4 votes
/**
 *
 * @param queryName Name of the query
 * @param componentName Name of the component
 * @param parameters Map of the query parameters
 * @param isDefault declares whether this query should be the default.  This overrides any previous defaults
 * @param isShortCut declares whether this query should be a shortcut
 * @return the id of the query
 * @throws ApplicationExceptions
 *
 * Saves a query using the IContextManager defined in the constructor
 */
String saveQuery(String queryName,
    String componentName,
    Map parameters,
    boolean isDefault,
    boolean isShortCut)
    throws IOException {

  Map savedQueries = getSavedQueryList(componentName);

  if (savedQueries != null && savedQueries.containsValue(queryName)) {

    Iterator savedQueriesIter = savedQueries.keySet().iterator();
    while (savedQueriesIter.hasNext()) {
      String id  = (String) savedQueriesIter.next();
      String value = (String)savedQueries.get(id);
      if (value.equals(queryName)) {
        removeSavedQuery(componentName, id);
        break;
      }
    }
  }

  String getQueriesString = buildPropertyString(componentName,new String[] {S_QUERIES});
  QueryIdList idList = new QueryIdList((String) m_contextManager.getProperty(getQueriesString));
  String nextId = idList.nextAvailable();

  String queryDataString = encodeQueryDataMap(parameters);
  log.debug("Encoded Query Parameters="+queryDataString);

  Properties p = new Properties();
  p.put(buildPropertyString(componentName,(new String[] {S_QUERIES})), idList.toString());
  p.put(buildPropertyString(componentName,(new String[] {S_QUERY, nextId, S_NAME})), queryName);
  p.put(buildPropertyString(componentName,(new String[] {S_QUERY, nextId, S_DATA})), queryDataString);

  // Need to do default
  if(isDefault) {
    p.put(buildPropertyString(componentName,(new String[] {S_QUERY, S_DEFAULT})), nextId);
  }

  // Need to do shortcut
  if (isShortCut) {
    String queryShortCuts =
        buildPropertyString(null, new String[] {S_QUERY,S_SHORTCUTS});
    String shortCuts = (String)m_contextManager.getProperty(queryShortCuts);
    String thisShortCut = componentName + "." + S_QUERY + "." + nextId;
    if (shortCuts == null) {
      shortCuts = thisShortCut;
    } else {
      shortCuts = shortCuts + "," + thisShortCut;
    }
    p.put(buildPropertyString(null,(new String[] {S_QUERY, S_SHORTCUTS})), shortCuts);
  }

  m_contextManager.setUserPreferences(p);

  return nextId;
}
 
Example 18
Project: sunbird-lms-mw   File: OrganisationMetricsActor.java   View Source Code Vote up 4 votes
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;
    }
  }
  StringBuilder builder = new StringBuilder();
  builder.append("{\"request\":{\"rawQuery\":{\"query\":{\"filtered\":")
      .append("{\"query\":{\"bool\":{\"must\":[{\"query\":{\"range\":{\"")
      .append(operationMap.get("dateKey")).append("\":{\"gte\":\"")
      .append(dateMap.get(startDate) + "\",\"lte\":\"" + dateMap.get(endDate) + "\"}}}}")
      .append(",{\"bool\":{\"should\":[{\"match\":{\"contentType.raw\":\"Story\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"Worksheet\"}}")
      .append(",{\"match\":{\"contentType.raw\":\"Game\"}}")
      .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(startTimeMilis) + ",\"max\":")
        .append(dateMap.get(endTimeMilis) + "}}},\"");
  }
  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(startTimeMilis) + ",\"max\":").append(dateMap.get(endTimeMilis))
      .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
Project: fpm   File: RoadTagger.java   View Source Code Vote up 4 votes
public Map<String, String> tag(Feature feature) {
    Map<String, String> tags = newHashMap();

    Long id = feature.getLong("ID");
    tags.put("ref:tomtom", valueOf(id));
    tags.put("from:tomtom", valueOf(feature.getLong("F_JNCTID")));
    tags.put("to:tomtom", valueOf(feature.getLong("T_JNCTID")));
    tags.putAll(level(feature));

    addTagIf("name", feature.getString("NAME"), ofNullable(feature.getString("NAME")).isPresent(), tags);
    addTagIf("ref", feature.getString("SHIELDNUM"), ofNullable(feature.getString("SHIELDNUM")).isPresent(), tags);
    addTagIf("reversed:tomtom", "yes", isReversed(feature), tags);
    addTagIf("oneway", "yes", isOneway(feature), tags);

    tags.putAll(tolls.tag(id));

    Collection<TimeDomains> timeDomains = tdDbf.getTimeDomains(id);
    addTagIf("motor_vehicle", "no", "N".equals(feature.getString("ONEWAY")) && timeDomains.isEmpty(), tags);
    if (timeDomains != null && !timeDomains.isEmpty()){
        tagsTimeDomains(tags, timeDomains);
    }
    addTagIf("route", "ferry", feature.getInteger("FT").equals(1), tags);
    addTagIf("duration", () -> duration(feature), tags.containsValue("ferry"), tags);
    if (!tags.containsValue("ferry")) {
        tags.putAll(speedProfiles.getTags(feature));
        tags.putAll(speedRestriction.tag(feature));
        tags.putAll(highwayType(feature));
        tags.putAll(lanes.lanesFor(feature));
        tags.putAll(nameProvider.getAlternateNames(id));

        Integer sol = ofNullable(feature.getInteger("SOL")).orElse(0);
        tags.putAll(nameProvider.getAlternateRoadSideNames(id, sol));

        addTagIf("tunnel", "yes", TUNNEL.equals(feature.getInteger("PARTSTRUC")), tags);
        addTagIf("bridge", "yes", BRIDGE.equals(feature.getInteger("PARTSTRUC")), tags);
        addTagIf("junction", "roundabout", ROUNDABOUT.is(feature.getInteger("FOW")), tags);
        addTagIf("access", "private", ofNullable(feature.getInteger("PRIVATERD")).isPresent() && feature.getInteger("PRIVATERD") > 0, tags);
        addTagIf("mappy_length", () -> valueOf(feature.getDouble("METERS")), ofNullable(feature.getDouble("METERS")).isPresent(), tags);

        tags.putAll(signPosts.getTags(id, isOneway(feature), feature.getLong("F_JNCTID"), feature.getLong("T_JNCTID")));
    }
    return tags;
}
 
Example 20
Project: smockin   File: HttpClientServiceImpl.java   View Source Code Vote up 3 votes
void handleRequestData(final Request request, final Map<String, String> requestHeaders, final HttpClientCallDTO reqDto) {

        if (requestHeaders.containsValue(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {

            final List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

            if (reqDto.getBody() != null && reqDto.getBody().contains("&")) {

                final String[] formParameterPairsArray = reqDto.getBody().split("&");

                for (String pairStr : formParameterPairsArray) {

                    if (pairStr.contains("=")) {

                        final String[] pairArray = pairStr.split("=");

                        if (pairArray.length == 2) {
                            postParameters.add(new BasicNameValuePair(pairArray[0], pairArray[1]));
                        }

                    }

                }

            }

            request.bodyForm(postParameters);
            return;
        }

        request.bodyByteArray((reqDto.getBody() != null)?reqDto.getBody().getBytes():null);
    }