java.util.Map.Entry Java Examples

The following examples show how to use java.util.Map.Entry. 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: OperatorDiscoverer.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
private void addTagsToProperties(MethodInfo mi, JSONObject propJ) throws JSONException
{
  //create description object. description tag enables the visual tools to display description of keys/values
  //of a map property, items of a list, properties within a complex type.
  JSONObject descriptionObj = new JSONObject();
  if (mi.comment != null) {
    descriptionObj.put("$", mi.comment);
  }
  for (Map.Entry<String, String> descEntry : mi.descriptions.entrySet()) {
    descriptionObj.put(descEntry.getKey(), descEntry.getValue());
  }
  if (descriptionObj.length() > 0) {
    propJ.put("descriptions", descriptionObj);
  }

  //create useSchema object. useSchema tag is added to enable visual tools to be able to render a text field
  //as a dropdown with choices populated from the schema attached to the port.
  JSONObject useSchemaObj = new JSONObject();
  for (Map.Entry<String, String> useSchemaEntry : mi.useSchemas.entrySet()) {
    useSchemaObj.put(useSchemaEntry.getKey(), useSchemaEntry.getValue());
  }
  if (useSchemaObj.length() > 0) {
    propJ.put("useSchema", useSchemaObj);
  }
}
 
Example #2
Source File: ExportParametersTest.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDetermineFormat() throws JAXBException {
	ExportParameters params = createTestParams();
	String paramsStr = JaxbUtils.marshalToJsonString(params, false);
	String jsonParsStr = createLegacyJsonString(params);
	
	Map<String, Object> mapOfPars = GsonUtil.toMap2(jsonParsStr);
	Map<String, Object> mapOfPars2 = GsonUtil.toMap2(paramsStr);
	for(Entry<String, Object> e : mapOfPars2.entrySet()) {
		logger.info(e.getKey() + " -> " + e.getValue());
	}
	logger.debug("Legacy map class (should be String) = " + mapOfPars.get(CommonExportPars.PARAMETER_KEY).getClass());
	logger.debug("When reading the ExportParameters class (is a Gson object) = " + mapOfPars2.get(CommonExportPars.PARAMETER_KEY).getClass());

	Assert.assertFalse("Validation method erroneously accepted legacy object!", isExportParameterObject(jsonParsStr));
	Assert.assertTrue("Validation method erroneously rejected parameter object!", isExportParameterObject(paramsStr));
}
 
Example #3
Source File: AccessSignInterceptor.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
private String getRedirectUrl(String requestPath, Map<String, String> paramMap) {
	Set<Entry<String, String>> es = paramMap.entrySet();
	Iterator<Entry<String, String>> it = es.iterator();
	StringBuffer sb = new StringBuffer();
	sb.append(requestPath + "?");
	while (it.hasNext()) {
		@SuppressWarnings("rawtypes")
		Map.Entry entry = (Map.Entry) it.next();
		String k = (String) entry.getKey();
		String v = (String) entry.getValue();
		if (null != v && !"".equals(v) && !"null".equals(v) && !"sign".equals(k) && !"nickname".equals(k)
				&& !"key".equals(k)) {
			sb.append(k + "=" + v + "&");
		}
	}
	String redirectUrl = sb.toString();
	redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1);
	logger.info("---------------redirectUrl--------------" + redirectUrl);
	return redirectUrl;
}
 
Example #4
Source File: ApiJsonResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Manage query-continue in request.
 * 
 * @param root Root of the JSON tree.
 * @param queryContinue XPath query to the query-continue node.
 * @param properties Properties defining request.
 * @return True if request should be continued.
 */
protected boolean shouldContinue(
    JsonNode root, String queryContinue,
    Map<String, String> properties) {
  if ((root == null) || (queryContinue == null)) {
    return false;
  }
  boolean result = false;
  JsonNode continueNode = root.path("continue");
  if ((continueNode != null) && !continueNode.isMissingNode()) {
    Iterator<Entry<String, JsonNode>> continueIterator = continueNode.fields();
    while (continueIterator.hasNext()) {
      Entry<String, JsonNode> continueElement = continueIterator.next();
      String name = continueElement.getKey();
      String value = continueElement.getValue().asText();
      if ((name != null) && (value != null)) {
        properties.put(name, value);
        if (!"".equals(value)) {
          result = true;
        }
      }
    }
  }
  return result;
}
 
Example #5
Source File: Main.java    From DKO with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void printHelp() {
	System.err.println("ERROR: Unrecognized command.");
	System.err.println("Syntax: java -jar lib/dko.jar <command> [command_option...]");
	System.err.println("");
	System.err.println("Where <command> is one of the following:");
	for (Entry<String, Class<?>> e : commands.entrySet()) {
		System.err.print("  ");
		System.err.print(e.getKey());
		System.err.print(":\t");
		try {
			Method help = e.getValue().getDeclaredMethod("getDescription");
			System.err.println(help.invoke(null));
		} catch (Exception e1) {
			System.err.println("(no description available)");
		}
	}
	System.err.println("");
	System.err.println("For help on an individual command, run the command with '--help'.");
	System.err.println("");
}
 
Example #6
Source File: HttpClientUtils.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 向指定URL发送GET方法的请求
 *
 * @param url     发送请求的URL
 * @param map     请求Map参数,请求参数应该是 {"name1":"value1","name2":"value2"}的形式。
 * @param charset 发送和接收的格式
 * @return URL 所代表远程资源的响应结果
 */
public static String sendGet(String url, Map<String, Object> map, String charset) {
    StringBuffer sb = new StringBuffer();
    //构建请求参数
    if (map != null && map.size() > 0) {
        Iterator it = map.entrySet().iterator(); //定义迭代器
        while (it.hasNext()) {
            Entry er = (Entry) it.next();
            sb.append(er.getKey());
            sb.append("=");
            sb.append(er.getValue());
            sb.append("&");
        }
    }
    return sendGet(url, sb.toString(), charset);
}
 
Example #7
Source File: ConsumerOffsetManager.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
/**
 * 扫描数据被删除了的topic,offset记录也对应删除
 */
public void scanUnsubscribedTopic() {
    Iterator<Entry<String, ConcurrentMap<Integer, Long>>> it = this.offsetTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentMap<Integer, Long>> next = it.next();
        String topicAtGroup = next.getKey();
        String[] arrays = topicAtGroup.split(TOPIC_GROUP_SEPARATOR);
        if (arrays.length == 2) { //还是以前写法好  if (arrays != null && arrays.length == 2)
            String topic = arrays[0];
            String group = arrays[1];

          // 当前订阅关系里面没有group-topic订阅关系(消费端当前是停机的状态)并且offset落后很多,则删除消费进度
            if (null == brokerController.getConsumerManager().findSubscriptionData(group, topic)
                && this.offsetBehindMuchThanData(topic, next.getValue())) {
                it.remove();
                log.warn("remove topic offset, {}", topicAtGroup);
            }
        }
    }
}
 
Example #8
Source File: AbstractGesture.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method is called when the attached {@link IDomain} is reset to
 * <code>null</code> so that you can unregister previously registered event
 * listeners.
 */
protected void doDeactivate() {
	// remove scene change listeners
	for (Entry<ObservableValue<Scene>, ChangeListener<? super Scene>> entry : sceneChangeListeners
			.entrySet()) {
		ObservableValue<Scene> sceneProperty = entry.getKey();
		sceneProperty.removeListener(entry.getValue());
	}
	sceneChangeListeners.clear();

	// remove viewer focus change listeners
	for (final IViewer viewer : new ArrayList<>(
			viewerFocusChangeListeners.keySet())) {
		viewer.viewerFocusedProperty()
				.removeListener(viewerFocusChangeListeners.remove(viewer));
	}
	viewerFocusChangeListeners.clear();

	// unhook scenes
	for (Scene scene : hookedScenes) {
		unhookScene(scene);
	}
}
 
Example #9
Source File: HttpAdapterList.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a PortAddressResolver that maps portname to its address
 *
 * @param endpointImpl application endpoint Class that eventually serves the request.
 */
public PortAddressResolver createPortAddressResolver(final String baseAddress, final Class<?> endpointImpl) {
    return new PortAddressResolver() {
        @Override
        public String getAddressFor(@NotNull QName serviceName, @NotNull String portName) {
            String urlPattern = addressMap.get(new PortInfo(serviceName,portName, endpointImpl));
            if (urlPattern == null) {
                //if a WSDL defines more ports, urlpattern is null (portName does not match endpointImpl)
                //so fallback to the default behaviour where only serviceName/portName is checked
                for (Entry<PortInfo, String> e : addressMap.entrySet()) {
                    if (serviceName.equals(e.getKey().serviceName) && portName.equals(e.getKey().portName)) {
                            urlPattern = e.getValue();
                            break;
                    }
                }
            }
            return (urlPattern == null) ? null : baseAddress+urlPattern;
        }
    };
}
 
Example #10
Source File: HttpManagementConstantHeadersTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static ModelNode createConstantHeadersOperation(final Map<String, List<Map<String, String>>> constantHeadersValues) {
    ModelNode writeAttribute = new ModelNode();
    writeAttribute.get("address").set(INTERFACE_ADDRESS.toModelNode());
    writeAttribute.get("operation").set("write-attribute");
    writeAttribute.get("name").set("constant-headers");

    ModelNode constantHeaders = new ModelNode();
    for (Entry<String, List<Map<String, String>>> entry : constantHeadersValues.entrySet()) {
        for (Map<String, String> header: entry.getValue()) {
            constantHeaders.add(createHeaderMapping(entry.getKey(), header));
        }
    }

    writeAttribute.get("value").set(constantHeaders);

    return writeAttribute;
}
 
Example #11
Source File: BaseHibernateDao.java    From framework with Apache License 2.0 6 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @param paramMap <br>
 * @param query <br>
 * @throws DaoException <br>
 */
private void setParamMap(final Map<String, Object> paramMap, final Query query) throws DaoException {
    if (MapUtils.isNotEmpty(paramMap)) {
        for (Entry<String, Object> entry : paramMap.entrySet()) {
            Object obj = entry.getValue();

            // 这里考虑传入的参数是什么类型,不同类型使用的方法不同
            if (obj instanceof Collection<?>) {
                query.setParameterList(entry.getKey(), (Collection<?>) obj);
            }
            else if (obj != null && obj.getClass().isArray() && obj instanceof Object[]) {
                query.setParameterList(entry.getKey(), (Object[]) obj);
            }
            else {
                query.setParameter(entry.getKey(), obj);
            }
        }
    }

}
 
Example #12
Source File: QueryMacroFunction.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public String apply(String query) {
    for (String key : queryMacros.keySet()) {
        if (query.contains(key)) {
            // blah blah FOO:selector blah blah ".*("+key+":([\\S]+)).*"
            String patternOne = ".*(" + key + ":([\\S]+)).*";
            // blah blah FOO(selector1,selector2,...) blah blah ".*("+key+"\\(([\\S]+\\))).*"
            String patternTwo = ".*(" + key + "\\(([\\S]+)\\)).*";
            Pattern pattern = Pattern.compile(patternTwo);
            Matcher matcher = pattern.matcher(query);
            while (matcher.find()) {
                String replacementPart = queryMacros.get(key);
                Map<String,String> selectorMap = getSelectorMap(matcher.group(2));
                // replace the placeholders with the selectors
                for (Entry<String,String> entry : selectorMap.entrySet()) {
                    replacementPart = replacementPart.replaceAll(entry.getKey(), entry.getValue());
                }
                // then replace the macro with the replacement part
                query = query.replace(matcher.group(1), replacementPart);
                matcher = pattern.matcher(query);
            }
        }
    }
    return query;
}
 
Example #13
Source File: Transformer.java    From Diorite with MIT License 6 votes vote down vote up
private void addGlobalInjectInvokes()
{
    MethodNode codeBefore = new MethodNode();
    MethodNode codeAfter = new MethodNode();
    this.fillMethodInvokes(codeBefore, codeAfter, this.classData);
    for (Entry<MethodNode, TransformerInitMethodData> initEntry : this.inits.entrySet())
    {
        MethodNode init = initEntry.getKey();
        TransformerInitMethodData initPair = initEntry.getValue();
        MethodInsnNode superInvoke = initPair.superInvoke;

        if (codeAfter.instructions.size() > 0)
        {
            for (InsnNode node : initPair.returns)
            {
                init.instructions.insertBefore(node, codeAfter.instructions);
            }
        }
        if (codeBefore.instructions.size() > 0)
        {
            init.instructions.insert(superInvoke, codeBefore.instructions);
        }
    }
}
 
Example #14
Source File: JavaTypeTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param tokens
 * @param cu
 * @return
 */
private List<FullToken> getTypedTokens(
		final SortedMap<Integer, FullToken> tokens, final ASTNode cu) {
	final JavaApproximateTypeInferencer tInf = new JavaApproximateTypeInferencer(
			cu);
	tInf.infer();
	final Map<Integer, String> types = tInf.getVariableTypesAtPosition();

	final List<FullToken> typeTokenList = Lists.newArrayList();
	for (final Entry<Integer, FullToken> token : tokens.entrySet()) {
		final String type = types.get(token.getKey());
		if (type != null) {
			typeTokenList.add(new FullToken("var%" + type + "%", token
					.getValue().tokenType));
		} else {
			typeTokenList.add(new FullToken(token.getValue().token, token
					.getValue().tokenType));
		}
	}
	return typeTokenList;
}
 
Example #15
Source File: MorphlineHandlerImpl.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Event event) {
  Record record = new Record();
  for (Entry<String, String> entry : event.getHeaders().entrySet()) {
    record.put(entry.getKey(), entry.getValue());
  }
  byte[] bytes = event.getBody();
  if (bytes != null && bytes.length > 0) {
    record.put(Fields.ATTACHMENT_BODY, bytes);
  }    
  try {
    Notifications.notifyStartSession(morphline);
    if (!morphline.process(record)) {
      LOG.warn("Morphline {} failed to process record: {}", morphlineFileAndId, record);
    }
  } catch (RuntimeException t) {
    morphlineContext.getExceptionHandler().handleException(t, record);
  }
}
 
Example #16
Source File: FixDataDictionaryProvider.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private DataDictionary getDictionary() {
    DataDictionary localDataDictionary = dataDictionary;
    if (localDataDictionary == null) {
        synchronized(configureLock) {
            localDataDictionary = dataDictionary;
            if (localDataDictionary == null) {
                this.dataDictionary = localDataDictionary = new QFJDictionaryAdapter(dictionaryStructure);

                if(settingMap != null) {
                    for(Entry<DataDictionarySetting, Boolean> entry : settingMap.entrySet()) {
                        DataDictionarySetting setting = entry.getKey();
                        boolean flag = entry.getValue();
                        setting.set(localDataDictionary, flag);
                    }
                } else {
                    logger.warn("Data dictionary provider is not yet configured");
                }
            }
        }
    }

    return localDataDictionary;
}
 
Example #17
Source File: ControlCodes.java    From basicv2 with The Unlicense 5 votes vote down vote up
/**
 * Returns the place holder for a code
 * 
 * @param code the code
 * @return the place holder or null, if none can be found
 */
public static String getPlaceHolder(int code) {
	for (Entry<String, Integer> en : placeHolder2code.entrySet()) {
		if (en.getValue() == code) {
			return "{" + en.getKey() + "}";
		}
	}
	return null;
}
 
Example #18
Source File: GTAggregateScanner.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Entry<byte[], MeasureAggregator[]>> iterator() {
    return new Iterator<Entry<byte[], MeasureAggregator[]>>() {
        @Override
        public boolean hasNext() {
            return !minHeap.isEmpty();
        }

        private void internalAggregate() {
            Entry<byte[], Integer> peekEntry = minHeap.poll();
            resultAggrs.aggregate(dumpCurrentValues.get(peekEntry.getValue()));
            enqueueFromDump(peekEntry.getValue());
        }

        @Override
        public Entry<byte[], MeasureAggregator[]> next() {
            // Use minimum heap to merge sort the keys,
            // also do aggregation for measures with same keys in different dumps
            resultAggrs.reset();

            byte[] peekKey = minHeap.peek().getKey();
            internalAggregate();

            while (!minHeap.isEmpty() && bytesComparator.compare(peekKey, minHeap.peek().getKey()) == 0) {
                internalAggregate();
            }

            return new SimpleEntry(peekKey, resultMeasureAggregators);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example #19
Source File: DateTimeFormatterBuilder.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
@Override
public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
    int length = parseText.length();
    if (position < 0 || position > length) {
        throw new IndexOutOfBoundsException();
    }
    TextStyle style = (context.isStrict() ? textStyle : null);
    Chronology chrono = context.getEffectiveChronology();
    Iterator<Entry<String, Long>> it;
    if (chrono == null || chrono == IsoChronology.INSTANCE) {
        it = provider.getTextIterator(field, style, context.getLocale());
    } else {
        it = provider.getTextIterator(chrono, field, style, context.getLocale());
    }
    if (it != null) {
        while (it.hasNext()) {
            Entry<String, Long> entry = it.next();
            String itText = entry.getKey();
            if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
                return context.setParsedField(field, entry.getValue(), position, position + itText.length());
            }
        }
        if (context.isStrict()) {
            return ~position;
        }
    }
    return numberPrinterParser().parse(context, parseText, position);
}
 
Example #20
Source File: Map.java    From oopsla15-artifact with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IMap compose(IMap other) {
	Map that = (Map) other;
	IMapWriter writer;

	if (this.getType().hasFieldNames() && that.getType().hasFieldNames()) {
		/*
		 * special treatment necessary if type contains labels
		 */
		Type newMapType = TypeFactory.getInstance().mapType(
				this.getType().getKeyType(), 
				this.getType().getKeyLabel(),
				that.getType().getValueType(),
				that.getType().getValueLabel());

		writer = ValueFactory.getInstance().mapWriter(newMapType);
	} else {
		writer = ValueFactory.getInstance().mapWriter(this.getType().getKeyType(), that.getType().getValueType());
	}		
			
	for (Iterator<Entry<IValue, IValue>> iterator = this.entryIterator(); iterator.hasNext();) {
		Entry<IValue, IValue> pair = iterator.next();
		
		if (that.containsKey(pair.getValue()))
			writer.put(pair.getKey(), that.get(pair.getValue()));
	}
	
	return writer.done();
}
 
Example #21
Source File: CityGMLImportManager.java    From importer-exporter with Apache License 2.0 5 votes vote down vote up
protected void delegateToADEImporter(AbstractGML object, long objectId, AbstractObjectType<?> objectType) throws CityGMLImportException, SQLException {
	// delegate import of ADE object to an ADE importer
	if (object instanceof ADEModelObject) {
		ADEModelObject adeObject = (ADEModelObject)object;

		ForeignKeys foreignKeys = (ForeignKeys)object.getLocalProperty(CoreConstants.FOREIGN_KEYS_SET);
		if (foreignKeys == null)
			foreignKeys = ForeignKeys.EMPTY_SET;

		getADEImportManager(adeObject).importObject(adeObject, objectId, objectType, foreignKeys);
	}

	// if the object is a CityGML feature or an ADE feature derived from a CityGML feature
	// then check for generic ADE properties and delegate their import to an ADE importer
	if (object instanceof AbstractFeature && object instanceof CityGMLModuleComponent) {
		AbstractFeature feature = (AbstractFeature)object;

		List<ADEModelObject> properties = propertyCollector.getADEProperties(feature);
		if (properties != null && !properties.isEmpty()) {
			IdentityHashMap<ADEImportManager, ADEPropertyCollection> groupedBy = new IdentityHashMap<>();
			for (ADEModelObject property : properties) {
				ADEImportManager adeImporter = getADEImportManager(property);
				ADEPropertyCollection collection = groupedBy.get(adeImporter);
				if (collection == null) {
					collection = new ADEPropertyCollection();
					groupedBy.put(adeImporter, collection);
				}

				collection.register(property);
			}

			for (Entry<ADEImportManager, ADEPropertyCollection> entry : groupedBy.entrySet())
				entry.getKey().importGenericApplicationProperties(entry.getValue(), feature, objectId, (FeatureType)objectType);
		}
	}
}
 
Example #22
Source File: StringObfuscationCipherVMT11.java    From zelixkiller with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Find and decrypt outer class(es) of class first
 */
private void treatAsInner(ClassNode node, Collection<ClassNode> values, HashMap<ClassNode, byte[]> isolatedJarCopy)
		throws Exception {
	ClassDefiner vm = new ClassDefiner(ClassLoader.getSystemClassLoader());
	for (Entry<ClassNode, byte[]> e : isolatedJarCopy.entrySet()) {
		vm.predefine(e.getKey().name.replace("/", "."), e.getValue());
	}
	inners++;
	int surroundings = 0;
	Outer: for (ClassNode cn : values) {
		for (MethodNode mn : cn.methods) {
			for (AbstractInsnNode ain : mn.instructions.toArray()) {
				if (ain.getOpcode() == INVOKESPECIAL) {
					MethodInsnNode min = (MethodInsnNode) ain;
					if (min.owner.equals(node.name) && min.name.equals("<init>")) {
						Class.forName(cn.name.replace("/", "."), true, vm);
						surroundings++;
						continue Outer;
					}
				}
			}
		}
	}
	if (surroundings > 1) {
		ZelixKiller.logger.log(Level.WARNING,
				"Inner class " + node.name + " has multiple surroundings (" + surroundings + ")");
	}
	Class<?> clazz = Class.forName(node.name.replace("/", "."), true, vm);
	replaceInvokedynamicCalls(clazz, node);
}
 
Example #23
Source File: HybridXMLWriter.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void writeResponse() throws IOException {
	writer.write(XML_PROCESSING_INSTR);

	final String stylesheet = req.getParams().get("stylesheet");
	if (isNotNullOrEmptyString(stylesheet)) {
		writer.write(XML_STYLESHEET);

		escapeAttributeValue(stylesheet, writer);
		
		writer.write(XML_STYLESHEET_END);
	}

	writer.write(RESPONSE_ROOT_ELEMENT_START);

	final NamedList<?> responseValues = rsp.getValues();
	if (req.getParams().getBool(CommonParams.OMIT_HEADER, false)) {
		responseValues.remove(RESPONSE_HEADER);
	} else {
		((NamedList)responseValues.get(RESPONSE_HEADER)).add(Names.QUERY, responseValues.remove(Names.QUERY).toString());
	}
	
	for (final Entry<String, ?> entry : responseValues) {
		writeValue(entry.getKey(), entry.getValue(), responseValues);			
	}

	writer.write(RESPONSE_ROOT_ELEMENT_END);
}
 
Example #24
Source File: AbstractLuceneMetaAlertUpdateDaoTest.java    From metron with Apache License 2.0 5 votes vote down vote up
protected Entry<Document, Optional<String>> findMetaEntry(
    Map<Document, Optional<String>> expected) {
  for (Entry<Document, Optional<String>> entry : expected.entrySet()) {
    if (entry.getKey().getSensorType().equals(METAALERT_TYPE)) {
      return entry;
    }
  }
  return null;
}
 
Example #25
Source File: PartyChartDataManagerImpl.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the max size view riksdagen vote data ballot party summary daily.
 *
 * @return the max size view riksdagen vote data ballot party summary daily
 */
private List<ViewRiksdagenVoteDataBallotPartySummaryDaily> getMaxSizeViewRiksdagenVoteDataBallotPartySummaryDaily() {
	initPartyMap();

	final Optional<Entry<String, List<ViewRiksdagenVoteDataBallotPartySummaryDaily>>> first = partyMap.entrySet()
			.stream().sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size())

	).findFirst();

	if (first.isPresent()) {
		return first.get().getValue();
	} else {
		return new ArrayList<>();
	}
}
 
Example #26
Source File: RocksDBCheckpointIterator.java    From bravo with Apache License 2.0 5 votes vote down vote up
private void updateCurrentIterator() {
	IOUtils.closeQuietly(currentIterator);
	if (iteratorQueue.isEmpty()) {
		currentIterator = null;
		currentName = null;
		return;
	} else {
		Entry<String, RocksIteratorWrapper> e = iteratorQueue.pop();
		currentName = e.getKey();
		currentIterator = e.getValue();
	}
}
 
Example #27
Source File: SimpleCommandMap.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void registerServerAliases() {
    Map<String, List<String>> values = this.server.getCommandAliases();
    for (Map.Entry<String, List<String>> entry : values.entrySet()) {
        String alias = entry.getKey();
        List<String> commandStrings = entry.getValue();
        if (alias.contains(" ") || alias.contains(":")) {
            this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.command.alias.illegal", alias));
            continue;
        }
        List<String> targets = new ArrayList<>();

        String bad = "";

        for (String commandString : commandStrings) {
            String[] args = commandString.split(" ");
            Command command = this.getCommand(args[0]);

            if (command == null) {
                if (bad.length() > 0) {
                    bad += ", ";
                }
                bad += commandString;
            } else {
                targets.add(commandString);
            }
        }

        if (bad.length() > 0) {
            this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.command.alias.notFound", new String[]{alias, bad}));
            continue;
        }

        if (!targets.isEmpty()) {
            this.knownCommands.put(alias.toLowerCase(), new FormattedCommandAlias(alias.toLowerCase(), targets));
        } else {
            this.knownCommands.remove(alias.toLowerCase());
        }
    }
}
 
Example #28
Source File: SimpleSectionAdapter.java    From adapter-kit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the actual index of the object in the data source linked to the this list item.
 * 
 * @param position List item position in the {@link ListView}.
 * @return Index of the item in the wrapped list adapter's data source.
 */
public int getIndexForPosition(int position) {
    int nSections = 0;

    Set<Entry<String, Integer>> entrySet = mSections.entrySet();
    for(Entry<String, Integer> entry : entrySet) {
        if(entry.getValue() < position) {
            nSections++;
        }
    }

    return position - nSections;
}
 
Example #29
Source File: SolutionCandidateFinderTester.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testThatASolutionEventIsEmittedInSimpleCall() throws InterruptedException, AlgorithmExecutionCanceledException, TimeoutException, AlgorithmException, AlgorithmCreationException {
	for (Entry<Object, Collection<?>> problem : this.reducedProblemsWithOriginalSolutions.entrySet()) {
		ISolutionCandidateIterator<Object, Object> algorithm = (ISolutionCandidateIterator<Object, Object>) this.getAlgorithm(problem.getKey());
		this.solveProblemViaCall(problem, algorithm);
	}
}
 
Example #30
Source File: DefaultHeaders.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
protected void addImpl(Headers<? extends K, ? extends V, ?> headers) {
    if (headers instanceof DefaultHeaders) {
        @SuppressWarnings("unchecked")
        final DefaultHeaders<? extends K, ? extends V, T> defaultHeaders =
                (DefaultHeaders<? extends K, ? extends V, T>) headers;
        HeaderEntry<? extends K, ? extends V> e = defaultHeaders.head.after;
        if (defaultHeaders.hashingStrategy == hashingStrategy &&
                defaultHeaders.nameValidator == nameValidator) {
            // Fastest copy
            while (e != defaultHeaders.head) {
                add0(e.hash, index(e.hash), e.key, e.value);
                e = e.after;
            }
        } else {
            // Fast copy
            while (e != defaultHeaders.head) {
                add(e.key, e.value);
                e = e.after;
            }
        }
    } else {
        // Slow copy
        for (Entry<? extends K, ? extends V> header : headers) {
            add(header.getKey(), header.getValue());
        }
    }
}