Java Code Examples for java.util.Map.Entry

The following are top voted examples for showing how to use java.util.Map.Entry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sunbird-utils   File: ElasticSearchUtil.java   View source code 10 votes vote down vote up
private static RangeQueryBuilder createRangeQuery(String name, Map<String, Object> rangeOperation,
    Float boost) {

  RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(name+RAW_APPEND);
  for (Map.Entry<String, Object> it : rangeOperation.entrySet()) {
    if (it.getKey().equalsIgnoreCase(LTE)) {
      rangeQueryBuilder.lte(it.getValue());
    } else if (it.getKey().equalsIgnoreCase(LT)) {
      rangeQueryBuilder.lt(it.getValue());
    } else if (it.getKey().equalsIgnoreCase(GTE)) {
      rangeQueryBuilder.gte(it.getValue());
    } else if (it.getKey().equalsIgnoreCase(GT)) {
      rangeQueryBuilder.gt(it.getValue());
    }
  }
  if (isNotNull(boost)) {
    return rangeQueryBuilder.boost(boost);
  }
  return rangeQueryBuilder;
}
 
Example 2
Project: automat   File: WxPayment.java   View source code 7 votes vote down vote up
/**
 * 微信下单map to xml
 * 
 * @param params
 *            参数
 * @return String
 */
public static String toXml(Map<String, String> params) {
	StringBuilder xml = new StringBuilder();
	xml.append("<xml>");
	for (Entry<String, String> entry : params.entrySet()) {
		String key = entry.getKey();
		String value = entry.getValue();
		// 略过空值
		if (StringUtils.isBlank(value))
			continue;
		xml.append("<").append(key).append(">");
		xml.append(entry.getValue());
		xml.append("</").append(key).append(">");
	}
	xml.append("</xml>");
	return xml.toString();
}
 
Example 3
Project: x7   File: BeanMapUtil.java   View source code 7 votes vote down vote up
public static Map<String,Object> toJsonableMap(Map<String,Object> stringKeyMap){
	Map<String,Object> jsonableMap = new HashMap<String,Object>();
	for (Entry<String, Object> es : stringKeyMap.entrySet()){
		String stringKey = es.getKey();
		if (stringKey.contains(".")){
			stringKey = stringKey.replace(".", "->");
			String[] arr = stringKey.split("->");
			String jsonKey = arr[0];
			String propKey = arr[1];
			Object obj = jsonableMap.get(jsonKey);
			Map<String,Object> objMap = null;
			if (Objects.isNull(obj)){
				objMap = new HashMap<String,Object>();
				jsonableMap.put(jsonKey, objMap);
			}else {
				objMap = (Map<String,Object>) obj;
			}
			objMap.put(propKey, es.getValue());
		}else{
			jsonableMap.put(stringKey, es.getValue());
		}
	}
	return jsonableMap;
}
 
Example 4
Project: bot4j   File: ApiAiReceiveMessageFactoryImpl.java   View source code 6 votes vote down vote up
protected NlpContext createNlpContext(final Result aiResponseResult) {
	final NlpContext result = new NlpContext();

	if (aiResponseResult.getMetadata() != null) {
		final NlpIntent nlpIntent = createNlpIntent(aiResponseResult);
		result.addIntent(nlpIntent);
	}

	if (aiResponseResult.getParameters() != null) {
		for (final Entry<String, JsonElement> entry : aiResponseResult.getParameters().entrySet()) {
			final NlpNamedEntity nlpNamedEntity = createNamedEntity(entry);
			result.addNamedEntity(nlpNamedEntity);
		}
	}

	return result;
}
 
Example 5
Project: hadoop   File: QuorumCall.java   View source code 6 votes vote down vote up
static <KEY, RESULT> QuorumCall<KEY, RESULT> create(
    Map<KEY, ? extends ListenableFuture<RESULT>> calls) {
  final QuorumCall<KEY, RESULT> qr = new QuorumCall<KEY, RESULT>();
  for (final Entry<KEY, ? extends ListenableFuture<RESULT>> e : calls.entrySet()) {
    Preconditions.checkArgument(e.getValue() != null,
        "null future for key: " + e.getKey());
    Futures.addCallback(e.getValue(), new FutureCallback<RESULT>() {
      @Override
      public void onFailure(Throwable t) {
        qr.addException(e.getKey(), t);
      }

      @Override
      public void onSuccess(RESULT res) {
        qr.addResult(e.getKey(), res);
      }
    });
  }
  return qr;
}
 
Example 6
Project: AdvancedDataProfilingSeminar   File: Zigzag.java   View source code 6 votes vote down vote up
private Set<InclusionDependency> generateCandidatesForLevel(int i) {
  Set<ColumnIdentifier> unaryIndNodes = new HashSet<>();
  // INDs from one table (dep & ref from same table) generate invalid INDs
  if (INCLUDE_INDS_FROM_ONE_TABLE) {
      unaryIndNodes = unaryIndMap.keySet();
  } else {
      unaryIndNodes = unaryIndMap.entrySet().stream()
              .filter(e -> !e.getKey().getTableIdentifier().equals(e.getValue().getTableIdentifier()))
              .map(Entry::getKey)
              .collect(Collectors.toSet());
  }

  Set<Set<ColumnIdentifier>> indsForLevel = Sets.combinations(unaryIndNodes,i);
  System.out.println("Combinations for level " + i + " : " + indsForLevel.toString());
  return indsForLevel.stream()
      .map(this::nodeToInd)
      .collect(Collectors.toSet());
}
 
Example 7
Project: jpl-framework   File: DetermineApplicableAlgorithmsCommandTest.java   View source code 6 votes vote down vote up
/**
 * Checks if the given map contains all {@link ILearningAlgorithm}'s which are using relative
 * datasets.
 * 
 * @param datasetFileToLearningAlgorithmsMap the map resulting after execution of the
 *           {@link DetermineApplicableAlgorithmsCommand}
 */
private void assertCorrectEntriesInDatasetFileToLearningAlgorithmsMap(
      Map<DatasetFile, List<ILearningAlgorithm>> datasetFileToLearningAlgorithmsMap) {
   Assert.assertEquals(1, datasetFileToLearningAlgorithmsMap.size());

   Set<String> allLearningAlgorithmsForRelativeDataset = getAllLearningAlgorithmClassNamesUsingRelativeDataset();

   for (Entry<DatasetFile, List<ILearningAlgorithm>> entry : datasetFileToLearningAlgorithmsMap.entrySet()) {
      Assert.assertEquals(allLearningAlgorithmsForRelativeDataset.size(), entry.getValue().size());
      for (ILearningAlgorithm learningAlgorithm : entry.getValue()) {
         String learningAlgorithmName = learningAlgorithm.toString();
         if (allLearningAlgorithmsForRelativeDataset.contains(learningAlgorithmName)) {
            allLearningAlgorithmsForRelativeDataset.remove(learningAlgorithmName);
         } else {
            Assert.fail(String.format(ERROR_ALGORITHM_NOT_USES_DATASET_BUT_IS_APPLICABLE, learningAlgorithmName,
                  DefaultDataset.class.getSimpleName()));
         }
      }
   }
}
 
Example 8
Project: jsf-core   File: ZkSynToDBServiceImpl.java   View source code 6 votes vote down vote up
/**
 * 过滤一下:不符合标准的version, 含有: %
 * @return
 */
private Map<String, byte[]> filterGroupOrVersion(Map<String, byte[]> dbAdd) throws Exception {
    Map<String, byte[]> invalid = Maps.newHashMap();
    for (Entry<String, byte[]> entry: dbAdd.entrySet()) {
        try {
            URL url = URL.valueOf(entry.getKey());
            if (StringUtils.hasText(url.getParameter(Constants.VERSION_KEY))) {
                if(url.getParameter(Constants.VERSION_KEY).contains("%")){
                    logger.warn("节点{}的version包含不支持的字符, 过滤不同步到db", url.toFullString());
                    invalid.put(url.toFullString(), entry.getValue());
                }
            }
        } catch (Exception e) {
            logger.error("filterGroupOrVersion error, key:" + entry.getKey(), e);
            throw e;
        }
    }
    
    return Maps.difference(dbAdd, invalid).entriesOnlyOnLeft();
}
 
Example 9
Project: GitHub   File: ExceptionToResourceMapping.java   View source code 6 votes vote down vote up
/** Mapping without checking the cause (done in mapThrowable). */
protected Integer mapThrowableFlat(Throwable throwable) {
    Class<? extends Throwable> throwableClass = throwable.getClass();
    Integer resId = throwableToMsgIdMap.get(throwableClass);
    if (resId == null) {
        Class<? extends Throwable> closestClass = null;
        Set<Entry<Class<? extends Throwable>, Integer>> mappings = throwableToMsgIdMap.entrySet();
        for (Entry<Class<? extends Throwable>, Integer> mapping : mappings) {
            Class<? extends Throwable> candidate = mapping.getKey();
            if (candidate.isAssignableFrom(throwableClass)) {
                if (closestClass == null || closestClass.isAssignableFrom(candidate)) {
                    closestClass = candidate;
                    resId = mapping.getValue();
                }
            }
        }

    }
    return resId;
}
 
Example 10
Project: airgram   File: SimpleCache.java   View source code 6 votes vote down vote up
/**
 * Scans all of the cached spans in the in-memory representation, removing any for which files
 * no longer exist.
 */
private void removeStaleSpans() {
  Iterator<Entry<String, TreeSet<CacheSpan>>> iterator = cachedSpans.entrySet().iterator();
  while (iterator.hasNext()) {
    Entry<String, TreeSet<CacheSpan>> next = iterator.next();
    Iterator<CacheSpan> spanIterator = next.getValue().iterator();
    boolean isEmpty = true;
    while (spanIterator.hasNext()) {
      CacheSpan span = spanIterator.next();
      if (!span.file.exists()) {
        spanIterator.remove();
        if (span.isCached) {
          totalSpace -= span.length;
        }
        notifySpanRemoved(span);
      } else {
        isEmpty = false;
      }
    }
    if (isEmpty) {
      iterator.remove();
    }
  }
}
 
Example 11
Project: OpenJSharp   File: DateTimeTextProvider.java   View source code 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param valueTextMap  the map of values to text to store, assigned and not altered, not null
 */
LocaleStore(Map<TextStyle, Map<Long, String>> valueTextMap) {
    this.valueTextMap = valueTextMap;
    Map<TextStyle, List<Entry<String, Long>>> map = new HashMap<>();
    List<Entry<String, Long>> allList = new ArrayList<>();
    for (Map.Entry<TextStyle, Map<Long, String>> vtmEntry : valueTextMap.entrySet()) {
        Map<String, Entry<String, Long>> reverse = new HashMap<>();
        for (Map.Entry<Long, String> entry : vtmEntry.getValue().entrySet()) {
            if (reverse.put(entry.getValue(), createEntry(entry.getValue(), entry.getKey())) != null) {
                // TODO: BUG: this has no effect
                continue;  // not parsable, try next style
            }
        }
        List<Entry<String, Long>> list = new ArrayList<>(reverse.values());
        Collections.sort(list, COMPARATOR);
        map.put(vtmEntry.getKey(), list);
        allList.addAll(list);
        map.put(null, allList);
    }
    Collections.sort(allList, COMPARATOR);
    this.parsable = map;
}
 
Example 12
Project: KUtils-master   File: ExceptionToResourceMapping.java   View source code 6 votes vote down vote up
/** Mapping without checking the cause (done in mapThrowable). */
protected Integer mapThrowableFlat(Throwable throwable) {
    Class<? extends Throwable> throwableClass = throwable.getClass();
    Integer resId = throwableToMsgIdMap.get(throwableClass);
    if (resId == null) {
        Class<? extends Throwable> closestClass = null;
        Set<Entry<Class<? extends Throwable>, Integer>> mappings = throwableToMsgIdMap.entrySet();
        for (Entry<Class<? extends Throwable>, Integer> mapping : mappings) {
            Class<? extends Throwable> candidate = mapping.getKey();
            if (candidate.isAssignableFrom(throwableClass)) {
                if (closestClass == null || closestClass.isAssignableFrom(candidate)) {
                    closestClass = candidate;
                    resId = mapping.getValue();
                }
            }
        }

    }
    return resId;
}
 
Example 13
Project: IJPay   File: PaymentKit.java   View source code 6 votes vote down vote up
/**
 * 微信下单map to xml
 * 
 * @param params
 *            参数
 * @return {String}
 */
public static String toXml(Map<String, String> params) {
	StringBuilder xml = new StringBuilder();
	xml.append("<xml>");
	for (Entry<String, String> entry : params.entrySet()) {
		String key = entry.getKey();
		String value = entry.getValue();
		// 略过空值
		if (StrKit.isBlank(value))
			continue;
		xml.append("<").append(key).append(">");
		xml.append(entry.getValue());
		xml.append("</").append(key).append(">");
	}
	xml.append("</xml>");
	return xml.toString();
}
 
Example 14
Project: dooo   File: BeanAbstractFieldValidator.java   View source code 6 votes vote down vote up
@Override
public boolean accept(Object object, FailedReason failedReason) {
    if (null == object) {
        return false;
    }
    for (Entry<String, List<AbstractConditionValidator>> validators : validatorsMap.entrySet()) {
        List<AbstractConditionValidator> cs = validators.getValue();
        String fieldName = validators.getKey();
        Object fieldValue = fields.get(fieldName).get(object);
        for (AbstractConditionValidator abstractConditionValidator : cs) {
            if (!abstractConditionValidator.accept(fieldValue)) {
                failedReason.setReason(abstractConditionValidator.refuseReason()).setFieldName(fieldName);
                return false;
            }
        }
    }
    return true;
}
 
Example 15
Project: googles-monorepo-demo   File: MultimapAsMapTester.java   View source code 6 votes vote down vote up
public void testAsMapGet() {
  for (K key : sampleKeys()) {
    List<V> expectedValues = new ArrayList<V>();
    for (Entry<K, V> entry : getSampleElements()) {
      if (entry.getKey().equals(key)) {
        expectedValues.add(entry.getValue());
      }
    }

    Collection<V> collection = multimap().asMap().get(key);
    if (expectedValues.isEmpty()) {
      assertNull(collection);
    } else {
      assertEqualIgnoringOrder(expectedValues, collection);
    }
  }
}
 
Example 16
Project: WirelessRedstone   File: RedstoneEtherServerAddons.java   View source code 6 votes vote down vote up
public void tickTriangs() {
    for (Entry<String, AddonPlayerInfo> entry : playerInfos.entrySet()) {
        EntityPlayer player = ServerUtils.getPlayer(entry.getKey());

        for (Integer freq : entry.getValue().triangSet) {
            double spinto;
            if (!RedstoneEther.server().isFreqOn(freq)) {
                spinto = -1;
            } else if (isRemoteOn(player, freq)) {
                spinto = -2;
            } else {
                Vector3 strengthvec = getBroadcastVector(player, freq);
                if (strengthvec == null)//in another dimension
                {
                    spinto = -2;//spin to a random place
                } else {
                    spinto = (player.rotationYaw + 180) * MathHelper.torad - Math.atan2(-strengthvec.x, strengthvec.z);//spin to the transmitter vec
                }
            }
            WRServerPH.sendTriangAngleTo(player, freq, (float) spinto);
        }
    }
}
 
Example 17
Project: openjdk-jdk10   File: RequestContext.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void mergeRequestHeaders(Packet packet) {
    //for bug 12883765
    //retrieve headers which is set in soap message
    Headers packetHeaders = (Headers) packet.invocationProperties.get(HTTP_REQUEST_HEADERS);
    //retrieve headers from request context
    Map<String, List<String>> myHeaders = (Map<String, List<String>>) asMap().get(HTTP_REQUEST_HEADERS);
    if ((packetHeaders != null) && (myHeaders != null)) {
        //update the headers set in soap message with those in request context
        for (Entry<String, List<String>> entry : myHeaders.entrySet()) {
            String key = entry.getKey();
            if (key != null && key.trim().length() != 0) {
                List<String> listFromPacket = packetHeaders.get(key);
                //if the two headers contain the same key, combine the value
                if (listFromPacket != null) {
                    listFromPacket.addAll(entry.getValue());
                } else {
                    //add the headers  in request context to those set in soap message
                    packetHeaders.put(key, myHeaders.get(key));
                }
            }
        }
        // update headers in request context with those set in soap message since it may contain other properties..
        asMap().put(HTTP_REQUEST_HEADERS, packetHeaders);
    }
}
 
Example 18
Project: letv   File: o.java   View source code 6 votes vote down vote up
private boolean a(Map<String, Object> map) {
    if (map == null || map.isEmpty()) {
        bv.f("map is null or empty in onEvent");
        return false;
    }
    for (Entry entry : map.entrySet()) {
        if (!a((String) entry.getKey())) {
            return false;
        }
        if (entry.getValue() == null) {
            return false;
        }
        if ((entry.getValue() instanceof String) && !b(entry.getValue().toString())) {
            return false;
        }
    }
    return true;
}
 
Example 19
Project: L2J-Global   File: NpcData.java   View source code 6 votes vote down vote up
public Set<String> getClansByIds(Set<Integer> clanIds)
{
	final Set<String> result = new HashSet<>();
	if (clanIds == null)
	{
		return result;
	}
	for (Entry<String, Integer> record : _clans.entrySet())
	{
		for (int id : clanIds)
		{
			if (record.getValue() == id)
			{
				result.add(record.getKey());
			}
		}
	}
	return result;
}
 
Example 20
Project: stewie   File: Stewie.java   View source code 6 votes vote down vote up
private SwaggerDefinitions swaggerDefinitions(Definitions definitions)
{
    SwaggerDefinitions result = new SwaggerDefinitions();

    for (TypeDefinition typeDefinition : definitions)
    {
        com.mauriciotogneri.jsonschema.JsonSchema jsonSchema = new com.mauriciotogneri.jsonschema.JsonSchema(typeDefinition);
        JsonObject schema = jsonSchema.schema();

        JsonObject schemaDefinitions = schema.get("definitions").getAsJsonObject();

        for (Entry<String, JsonElement> entry : schemaDefinitions.entrySet())
        {
            result.put(entry.getKey(), entry.getValue().getAsJsonObject());
        }
    }

    return result;
}
 
Example 21
Project: letv   File: FileProvider.java   View source code 6 votes vote down vote up
public Uri getUriForFile(File file) {
    try {
        String rootPath;
        String path = file.getCanonicalPath();
        Entry<String, File> mostSpecific = null;
        for (Entry<String, File> root : this.mRoots.entrySet()) {
            rootPath = ((File) root.getValue()).getPath();
            if (path.startsWith(rootPath) && (mostSpecific == null || rootPath.length() > ((File) mostSpecific.getValue()).getPath().length())) {
                mostSpecific = root;
            }
        }
        if (mostSpecific == null) {
            throw new IllegalArgumentException("Failed to find configured root that contains " + path);
        }
        rootPath = ((File) mostSpecific.getValue()).getPath();
        if (rootPath.endsWith("/")) {
            path = path.substring(rootPath.length());
        } else {
            path = path.substring(rootPath.length() + 1);
        }
        return new Builder().scheme(WidgetRequestParam.REQ_PARAM_COMMENT_CONTENT).authority(this.mAuthority).encodedPath(Uri.encode((String) mostSpecific.getKey()) + LetvUtils.CHARACTER_BACKSLASH + Uri.encode(path, "/")).build();
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
    }
}
 
Example 22
Project: boohee_v5.6   File: PersistentCookieStore.java   View source code 6 votes vote down vote up
public boolean clearExpired(Date date) {
    boolean clearedAny = false;
    Editor prefsWriter = this.cookiePrefs.edit();
    for (Entry<String, Cookie> entry : this.cookies.entrySet()) {
        String name = (String) entry.getKey();
        if (((Cookie) entry.getValue()).isExpired(date)) {
            this.cookies.remove(name);
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);
            clearedAny = true;
        }
    }
    if (clearedAny) {
        prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet()));
    }
    prefsWriter.commit();
    return clearedAny;
}
 
Example 23
Project: Babler   File: FingerPrint.java   View source code 6 votes vote down vote up
/**
 * reads a FingerPrint from the passed InputStream
 * 
 * @param is
 *            InputStream to be read
 */
private void loadFingerPrintFromInputStream(InputStream is) {
	entries = new TreeSet<Entry<String, Integer>>(
			new NGramEntryComparator());
	MyProperties properties = new MyProperties();
	properties.load(is);
	for (Entry<String, String> entry : properties.entrySet()) {
		try {
			this.put(entry.getValue(), Integer.parseInt(entry.getKey()));
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	entries.addAll(this.entrySet());
}
 
Example 24
Project: myfaces-trinidad   File: CopyOnWriteArrayMap.java   View source code 6 votes vote down vote up
@Override
public boolean equals(Object o)
{
  if (o == this)
    return true;

  if (o instanceof Entry)
  {
    Entry otherEntry = (Entry)o;

    if (getKey().equals(otherEntry.getKey()))
    {
      Object otherValue = otherEntry.getValue();
      V value = _value;

      return (value != null) ? value.equals(otherValue) : otherValue == null;
    }
  }

  return false;
}
 
Example 25
Project: Pogamut3   File: NavMeshVertex.java   View source code 5 votes vote down vote up
public NavMeshVertex(
		final int id,
		Location location,
		final Map<Integer,Integer> polygonIdToVertexIndexMap,
		final List<Integer> edgeIds,
		boolean isOnWalkableAreaEdge,
		final NodeConstructionCoordinator constructionCoordinator
) {
	this.id = id;
	this.location = location;
	this.isOnWalkableAreaEdge = isOnWalkableAreaEdge;
	initializeConstCollections();
	
	constructionCoordinator.addDeferredConstructor(
		new IDeferredConstructor() {
			@Override
			public void construct() {
				for ( Entry<Integer, Integer> entry : polygonIdToVertexIndexMap.entrySet() ) {
					polygonToVertexIndexMap.put(
						constructionCoordinator.getPolygonById( entry.getKey() ),
						entry.getValue()
					);
				}
				
				for ( Integer edgeId : edgeIds ) {
					edges.add( constructionCoordinator.getEdgeById(edgeId) );
				}
			}
		}
	);
}
 
Example 26
Project: s-store   File: HStoreConf.java   View source code 5 votes vote down vote up
private void setDefaultValues() {
    // Set the default values for the parameters based on their annotations
    for (Entry<Field, ConfigProperty> e : this.getConfigProperties().entrySet()) {
        Field f = e.getKey();
        ConfigProperty cp = e.getValue();
        Object value = getDefaultValue(f, cp);
        
        try {
            if (value != null) f.set(this, value);
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Failed to set default value '%s' for field '%s'", value, f.getName()), ex);
        }
        if (trace.val) LOG.trace(String.format("%-20s = %s", f.getName(), value));
    } // FOR   
}
 
Example 27
Project: alevin-svn2   File: SuccessfullyEmbeddingPartitionsNodesRatio.java   View source code 5 votes vote down vote up
public double calculate(NetworkStack stack) {
	double sumSNodes = 0;
	
	Map<ClusterHead, List<VirtualNetwork>> map = counter.numberOfVNRsSuccessfullyEmbeddedPerPartition;

	for (Entry<ClusterHead, List<VirtualNetwork>> e : map.entrySet()) {
		sumSNodes += ((((double) e.getKey().cluster.getVertexCount()) * 100.0d)
				/ (double) stack.getSubstrate().getVertexCount())
				* (double) e.getValue().size();
	}
	
	double result = (sumSNodes / ((double) (stack.size() - 1)));
	return result;
}
 
Example 28
Project: openjdk-jdk10   File: XmlPolicyModelMarshaller.java   View source code 5 votes vote down vote up
/**
 * Write default prefixes onto the given TypedXmlWriter
 *
 * @param model The policy source model. May not be null.
 * @param writer The TypedXmlWriter. May not be null.
 * @throws PolicyException If the creation of the prefix to namespace URI map failed.
 */
private void marshalDefaultPrefixes(final PolicySourceModel model, final TypedXmlWriter writer) throws PolicyException {
    final Map<String, String> nsMap = model.getNamespaceToPrefixMapping();
    if (!marshallInvisible && nsMap.containsKey(PolicyConstants.SUN_POLICY_NAMESPACE_URI)) {
        nsMap.remove(PolicyConstants.SUN_POLICY_NAMESPACE_URI);
    }
    for (Map.Entry<String, String> nsMappingEntry : nsMap.entrySet()) {
        writer._namespace(nsMappingEntry.getKey(), nsMappingEntry.getValue());
    }
}
 
Example 29
Project: guava-mock   File: MapEntrySetTester.java   View source code 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testSetValue() {
  for (Entry<K, V> entry : getMap().entrySet()) {
    if (entry.getKey().equals(k0())) {
      assertEquals("entry.setValue() should return the old value", v0(), entry.setValue(v3()));
      break;
    }
  }
  expectReplacement(entry(k0(), v3()));
}
 
Example 30
Project: plugin-bt-jira   File: JiraUpdateDao.java   View source code 5 votes vote down vote up
/**
 * Associate custom field values to a given issue.
 */
@SuppressWarnings("unchecked")
private int associateCutomFieldValues(final Map<String, CustomFieldEditor> customFields,
		final JdbcOperations jdbcTemplate, final int nextId, final JiraIssueRow issueRow) {
	int nextIdl = nextId;
	for (final Entry<String, Object> entry : issueRow.getCustomFields().entrySet()) {
		final String cfName = entry.getKey();
		final CustomField customField = customFields.get(cfName);
		final int cfId = customField.getId();
		final Object cfValue = entry.getValue();

		// Determine the right 'customfieldvalue' column
		final String column = JiraDao.MANAGED_TYPE.get(customField.getFieldType()).getCustomColumn();
		final Collection<Object> values;
		if (cfValue instanceof Collection) {
			// Multi-values
			values = (Collection<Object>) cfValue;
		} else {
			// Single value
			values = new ArrayList<>(1);
			values.add(cfValue);
		}
		nextIdl = associateCustomFieldValue(jdbcTemplate, issueRow.getId(), nextIdl, cfId, column, values);

	}
	return nextIdl;
}
 
Example 31
Project: angel   File: WorkerManager.java   View source code 5 votes vote down vote up
/**
 * get the number of worker groups that are not finish
 * @return int the number of worker groups that are not finish
 */
public int getActiveWorkerGroupNumber() {
  try{
    readLock.lock();
    int number = 0;
    for (Entry<WorkerGroupId, AMWorkerGroup> entry : workerGroupMap.entrySet()) {
      if (!entry.getValue().isFinished()) {
        number++;
      }
    }
    return number;
  } finally {
    readLock.unlock();
  }
}
 
Example 32
Project: openvisualtraceroute   File: ControlPanel.java   View source code 5 votes vote down vote up
private void start() {
	final long ts = System.currentTimeMillis();
	if (ts < _ts + 500) {
		return;
	}
	_ts = ts;
	if (!_running) {
		final Set<Protocol> pt = new HashSet<>();
		for (final Entry<Protocol, JCheckBox> entry : _packets.entrySet()) {
			if (entry.getValue().isSelected()) {
				pt.add(entry.getKey());
			}
		}
		String port = null;
		if (!_allPortCheck.isSelected()) {
			port = _portTF.getText();
		}
		if (pt.isEmpty()) {
			JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(ControlPanel.this), Resources.getLabel("protocol.ports.empty"),
					Resources.getLabel("protocol.ports.empty"), JOptionPane.INFORMATION_MESSAGE);
			return;
		}
		_running = true;
		String host = _hostIpTextField.getText();
		if (host.contains(Resources.getLabel("sniffer.host.tooltip"))) {
			host = null;
		}
		_sniffer.startCapture(pt, port, _filterPacketLengthCheck.isSelected(), Integer.parseInt(_filterLengthTF.getText().replace(",", "")), host,
				Integer.parseInt(_capturePeriod.getText()));
	} else {
		_sniffer.endCapture();
		_running = false;
	}
}
 
Example 33
Project: lazycat   File: UpgradeUtil.java   View source code 5 votes vote down vote up
private static List<Transformation> createTransformations(List<Extension> negotiatedExtensions) {

		TransformationFactory factory = TransformationFactory.getInstance();

		LinkedHashMap<String, List<List<Extension.Parameter>>> extensionPreferences = new LinkedHashMap<String, List<List<Extension.Parameter>>>();

		// Result will likely be smaller than this
		List<Transformation> result = new ArrayList<Transformation>(negotiatedExtensions.size());

		for (Extension extension : negotiatedExtensions) {
			List<List<Extension.Parameter>> preferences = extensionPreferences.get(extension.getName());

			if (preferences == null) {
				preferences = new ArrayList<List<Extension.Parameter>>();
				extensionPreferences.put(extension.getName(), preferences);
			}

			preferences.add(extension.getParameters());
		}

		for (Map.Entry<String, List<List<Extension.Parameter>>> entry : extensionPreferences.entrySet()) {
			Transformation transformation = factory.create(entry.getKey(), entry.getValue(), true);
			if (transformation != null) {
				result.add(transformation);
			}
		}
		return result;
	}
 
Example 34
Project: reading-and-annotate-rocketmq-3.4.6   File: RouteInfoManager.java   View source code 5 votes vote down vote up
public void scanNotActiveBroker() {
    Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, BrokerLiveInfo> next = it.next();
        long last = next.getValue().getLastUpdateTimestamp();
        //本地 brokerLiveTable 默认2分钟过期
        if ((last + BrokerChannelExpiredTime) < System.currentTimeMillis()) {
            RemotingUtil.closeChannel(next.getValue().getChannel());
            it.remove();
            log.warn("The broker channel expired, {} {}ms", next.getKey(), BrokerChannelExpiredTime);
            this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
        }
    }
}
 
Example 35
Project: teamcity-autotools-plugin   File: AutotoolsTestsReporter.java   View source code 5 votes vote down vote up
/**
 * Handles all tests results files.
 */
void doTestsReport(){
  for (final Entry<String, File> entry : myTestsTrsFiles.entrySet()){
    parseTrsTestResults(entry.getKey(), entry.getValue());
  }
  for (final File file : myTestsXmlFiles){
    myXmlParser.handleXmlResults(file);
  }
}
 
Example 36
Project: monarch   File: AdminImpl.java   View source code 5 votes vote down vote up
private String[] listTableNames(boolean isFTables) {
  String[] names = null;
  List<String> tableNames = new ArrayList<String>();
  try {
    Region<String, TableDescriptor> metaRegion =
        (Region<String, TableDescriptor>) monarchCacheImpl
            .getRegion(MTableUtils.AMPL_META_REGION_NAME);

    Set<Entry<String, TableDescriptor>> entries;
    if (monarchCacheImpl.isClient()) {
      Map<String, TableDescriptor> values = metaRegion.getAll(metaRegion.keySetOnServer());
      entries = values.entrySet();
    } else {
      entries = metaRegion.entrySet();
    }
    final Iterator<Entry<String, TableDescriptor>> itr = entries.iterator();
    while (itr.hasNext()) {
      final Entry<String, TableDescriptor> entry = itr.next();
      if (isFTables) {
        if (entry.getValue() instanceof FTableDescriptor) {
          tableNames.add(entry.getKey());
        }
      } else {
        if (entry.getValue() instanceof MTableDescriptor) {
          tableNames.add(entry.getKey());
        }
      }
    }
    names = new String[tableNames.size()];
    tableNames.toArray(names);
  } catch (GemFireException ge) {
    MTableUtils.checkSecurityException(ge);
    logger.error("Table Listing Failed");
    throw new MCacheInternalErrorException("Table Listing Failed", ge);
  }
  return names;
}
 
Example 37
Project: calcite-avatica   File: KerberosConnection.java   View source code 5 votes vote down vote up
/**
 * Logout and log back in with the Kerberos identity.
 */
void renew() {
  try {
    // Lock on the instance of KerberosUtil
    synchronized (utilInstance) {
      Entry<LoginContext, Subject> pair = utilInstance.login(context, conf, subject);
      context = pair.getKey();
      subject = pair.getValue();
    }
  } catch (Exception e) {
    throw new RuntimeException("Failed to perform kerberos login");
  }
}
 
Example 38
Project: googles-monorepo-demo   File: AbstractMapBasedMultimap.java   View source code 5 votes vote down vote up
Map.Entry<K, Collection<V>> pollAsMapEntry(Iterator<Entry<K, Collection<V>>> entryIterator) {
  if (!entryIterator.hasNext()) {
    return null;
  }
  Entry<K, Collection<V>> entry = entryIterator.next();
  Collection<V> output = createCollection();
  output.addAll(entry.getValue());
  entryIterator.remove();
  return Maps.immutableEntry(entry.getKey(), unmodifiableCollectionSubclass(output));
}
 
Example 39
Project: Abacus-Lightweight-Stream-API   File: Stream.java   View source code 5 votes vote down vote up
public <K, V> EntryStream<K, V> mapToEntry(final Function<? super T, K> keyMapper, final Function<? super T, V> valueMapper) {
    return new EntryStream<>(this.map(new Function<T, Map.Entry<K, V>>() {
        @Override
        public Entry<K, V> apply(T t) {
            return new AbstractMap.SimpleImmutableEntry<>(keyMapper.apply(t), valueMapper.apply(t));
        }
    }));
}
 
Example 40
Project: S2X   File: ResultMessage.java   View source code 5 votes vote down vote up
/**
    * Adds the results to the given map
    * 
    * @param map
    *            The map where the results are added to
    * @param toAdd
    *            Results to add
    */
   private void addResultsToMap(
    Map<CompositeKeyNodeAttr, List<ResultValue>> map,
    Map<CompositeKeyNodeAttr, List<ResultValue>> toAdd) {
for (Entry<CompositeKeyNodeAttr, List<ResultValue>> results : toAdd
	.entrySet()) {
    // There is a list for this key
    if (map.containsKey(results.getKey())) {
	map.get(results.getKey()).addAll(results.getValue());
    } else {
	// No list existing
	map.put(results.getKey(), results.getValue());
    }
}
   }