Java Code Examples for java.util.Map
The following examples show how to use
java.util.Map. These examples are extracted from open source projects.
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 Project: TencentKona-8 Source File: HttpURLConnection.java License: GNU General Public License v2.0 | 6 votes |
/** * Returns an unmodifiable Map of general request * properties for this connection. The Map keys * are Strings that represent the request-header * field names. Each Map value is a unmodifiable List * of Strings that represents the corresponding * field values. * * @return a Map of the general request properties for this connection. * @throws IllegalStateException if already connected * @since 1.4 */ @Override public synchronized Map<String, List<String>> getRequestProperties() { if (connected) throw new IllegalStateException("Already connected"); // exclude headers containing security-sensitive info if (setUserCookies) { return requests.getHeaders(EXCLUDE_HEADERS); } /* * The cookies in the requests message headers may have * been modified. Use the saved user cookies instead. */ Map<String, List<String>> userCookiesMap = null; if (userCookies != null || userCookies2 != null) { userCookiesMap = new HashMap<>(); if (userCookies != null) { userCookiesMap.put("Cookie", Arrays.asList(userCookies)); } if (userCookies2 != null) { userCookiesMap.put("Cookie2", Arrays.asList(userCookies2)); } } return requests.filterAndAddHeaders(EXCLUDE_HEADERS2, userCookiesMap); }
Example 2
Source Project: netbeans Source File: ListCompletionView.java License: Apache License 2.0 | 6 votes |
public @Override void paint(Graphics g) { Object value = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N Map renderingHints = (value instanceof Map) ? (java.util.Map)value : null; if (renderingHints != null && g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; RenderingHints oldHints = g2d.getRenderingHints(); g2d.setRenderingHints(renderingHints); try { super.paint(g2d); } finally { g2d.setRenderingHints(oldHints); } } else { super.paint(g); } }
Example 3
Source Project: AndrOBD Source File: PvList.java License: GNU General Public License v3.0 | 6 votes |
/** * handle a set/map of data attributes with specified notification action * * @param data Map of new data attributes to handle * @param action PvChangeEvent-Action code to be used for notifications * @param allowChildEvents are child events (for each attribute) allowed? * @return previous value of corresponding data item */ @SuppressWarnings("rawtypes") private synchronized Object handleData(Map data, int action, boolean allowChildEvents) { Object result = null; if (data.containsKey(getKeyAttribute())) { // remember flag for event creation boolean oldAllowEvents = allowEvents; // set flag for event creation allowEvents = allowChildEvents; ProcessVar dataset = (ProcessVar) get(data.get(getKeyAttribute())); if (dataset == null) { dataset = new ProcessVar(); dataset.setKeyAttribute(getKeyAttribute()); } dataset.putAll(data, action, allowChildEvents); // restore flag for event creation allowEvents = oldAllowEvents; result = put(dataset.getKeyValue(), dataset, action); } return (result); }
Example 4
Source Project: fqueue Source File: JVMMonitor.java License: Apache License 2.0 | 6 votes |
public static Map<String, MemoryUsage> getMemoryPoolCollectionUsage() { Map<String, MemoryUsage> gcMemory = new HashMap<String, MemoryUsage>(); for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { String name = memoryPoolMXBean.getName(); if (edenSpace.contains(name)) { gcMemory.put("eden", memoryPoolMXBean.getCollectionUsage()); } else if (survivorSpace.contains(name)) { gcMemory.put("survivor", memoryPoolMXBean.getCollectionUsage()); } else if (oldSpace.contains(name)) { gcMemory.put("old", memoryPoolMXBean.getCollectionUsage()); } else if (permSpace.contains(name)) { gcMemory.put("perm", memoryPoolMXBean.getCollectionUsage()); } else if (codeCacheSpace.contains(name)) { gcMemory.put("codeCache", memoryPoolMXBean.getCollectionUsage()); } } return gcMemory; }
Example 5
Source Project: titus-control-plane Source File: TaskCacheEventListener.java License: Apache License 2.0 | 6 votes |
@Override public void onAssignment(TaskAssignmentResult taskAssignmentResult) { V3QueueableTask request = (V3QueueableTask) taskAssignmentResult.getRequest(); Map<String, String> taskContext = request.getTask().getTaskContext(); if (taskContext.containsKey(TASK_ATTRIBUTES_IP_ALLOCATION_ID)) { taskCache.addTaskIpAllocation(taskAssignmentResult.getTaskId(), taskContext.get(TASK_ATTRIBUTES_IP_ALLOCATION_ID)); } int opportunisticCpus = request.getOpportunisticCpus(); if (request.isCpuOpportunistic() && opportunisticCpus > 0) { String machineId = taskAssignmentResult.getHostname(); Optional<String> allocationId = opportunisticCpuCache.findAvailableOpportunisticCpus(machineId) .map(OpportunisticCpuAvailability::getAllocationId); if (!allocationId.isPresent()) { codeInvariants().inconsistent("Task assigned to opportunistic CPUs on machine %s that can not be found", machineId); } taskCache.addOpportunisticCpuAllocation(new OpportunisticCpuAllocation( taskAssignmentResult.getTaskId(), machineId, allocationId.orElse(UNKNOWN_ALLOCATION_ID), opportunisticCpus )); } }
Example 6
Source Project: kbear Source File: ConsumerTest.java License: Apache License 2.0 | 6 votes |
protected void commitSync( java.util.function.BiConsumer<Consumer<String, String>, Map<TopicPartition, OffsetAndMetadata>> committer) throws InterruptedException { produceMessages(); try (Consumer<String, String> consumer = createConsumerWithoutAutoCommit()) { consumer.subscribe(_topics); pollDurationTimeout(consumer); OffsetAndMetadata committed = consumer.committed(_topicPartition); System.out.println("committed: " + committed); OffsetAndMetadata committed2 = new OffsetAndMetadata(committed.offset() + _messageCount, committed.metadata()); System.out.println("committed2: " + committed2); Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>(); offsetMap.put(_topicPartition, committed2); committer.accept(consumer, offsetMap); OffsetAndMetadata committed3 = consumer.committed(_topicPartition); System.out.println("committed3: " + committed3); Assert.assertEquals(committed2.offset(), committed3.offset()); } }
Example 7
Source Project: hudi Source File: UtilHelpers.java License: Apache License 2.0 | 6 votes |
/*** * call spark function get the schema through jdbc. * The code logic implementation refers to spark 2.4.x and spark 3.x. * @param options * @return * @throws Exception */ public static Schema getJDBCSchema(Map<String, String> options) throws Exception { Connection conn = createConnectionFactory(options); String url = options.get(JDBCOptions.JDBC_URL()); String table = options.get(JDBCOptions.JDBC_TABLE_NAME()); boolean tableExists = tableExists(conn, options); if (tableExists) { JdbcDialect dialect = JdbcDialects.get(url); try (PreparedStatement statement = conn.prepareStatement(dialect.getSchemaQuery(table))) { statement.setQueryTimeout(Integer.parseInt(options.get("queryTimeout"))); try (ResultSet rs = statement.executeQuery()) { StructType structType; if (Boolean.parseBoolean(options.get("nullable"))) { structType = JdbcUtils.getSchema(rs, dialect, true); } else { structType = JdbcUtils.getSchema(rs, dialect, false); } return AvroConversionUtils.convertStructTypeToAvroSchema(structType, table, "hoodie." + table); } } } else { throw new HoodieException(String.format("%s table does not exists!", table)); } }
Example 8
Source Project: agile-service-old Source File: SiteMsgUtil.java License: Apache License 2.0 | 6 votes |
public void issueSolve(List<Long> userIds, String userName, String summary, String url, Long assigneeId, Long projectId) { NoticeSendDTO noticeSendDTO = new NoticeSendDTO(); noticeSendDTO.setCode("issueSolve"); Map<String, Object> params = new HashMap<>(); params.put(ASSIGNEENAME, userName); params.put(SUMMARY, summary); params.put(URL, url); noticeSendDTO.setParams(params); List<NoticeSendDTO.User> userList = new ArrayList<>(); for (Long id : userIds) { NoticeSendDTO.User user = new NoticeSendDTO.User(); user.setId(id); userList.add(user); } noticeSendDTO.setTargetUsers(userList); NoticeSendDTO.User fromUser = new NoticeSendDTO.User(); fromUser.setId(assigneeId); noticeSendDTO.setFromUser(fromUser); noticeSendDTO.setSourceId(projectId); try { notifyFeignClient.postNotice(noticeSendDTO); } catch (Exception e) { LOGGER.error("完成issue消息发送失败", e); } }
Example 9
Source Project: smarthome Source File: HueBridgeHandler.java License: Eclipse Public License 2.0 | 6 votes |
/** * This method is called whenever the connection to the {@link HueBridge} is resumed. * * @throws ApiException if the physical device does not support this API call * @throws IOException if the physical device could not be reached */ private void onConnectionResumed() throws IOException, ApiException { logger.debug("Bridge connection resumed. Updating thing status to ONLINE."); if (!propertiesInitializedSuccessfully) { FullConfig fullConfig = hueBridge.getFullConfig(); Config config = fullConfig.getConfig(); if (config != null) { Map<String, String> properties = editProperties(); properties.put(PROPERTY_SERIAL_NUMBER, config.getMACAddress().replaceAll(":", "").toLowerCase()); properties.put(PROPERTY_FIRMWARE_VERSION, config.getSoftwareVersion()); updateProperties(properties); propertiesInitializedSuccessfully = true; } } updateStatus(ThingStatus.ONLINE); }
Example 10
Source Project: qpid-broker-j Source File: DtxStart.java License: Apache License 2.0 | 6 votes |
@Override public Map<String,Object> getFields() { Map<String,Object> result = new LinkedHashMap<String,Object>(); if ((packing_flags & 256) != 0) { result.put("xid", getXid()); } if ((packing_flags & 512) != 0) { result.put("join", getJoin()); } if ((packing_flags & 1024) != 0) { result.put("resume", getResume()); } return result; }
Example 11
Source Project: onetwo Source File: ReflectUtils.java License: Apache License 2.0 | 6 votes |
public static Object getPropertyValue(Object element, String propName, Closure2<String, Exception> errorHandler) { if (element instanceof Map) { return getValue((Map) element, propName); } try{ // Intro<?> info = getIntro(getObjectClass(element)); // PropertyDescriptor pd = info.getProperty(propName); // return info.getPropertyValue(element, pd); return getIntro(getObjectClass(element)).getPropertyValue(element, propName); }catch(Exception e){ /*logger.error("get ["+element+"] property["+propName+"] error: " + e.getMessage()); if(throwIfError) throw new BaseException("get ["+element+"] property["+propName+"] error", e);*/ errorHandler.execute(propName, e); } return null; }
Example 12
Source Project: kfs Source File: CustomerLoadVOGenerator.java License: GNU Affero General Public License v3.0 | 6 votes |
public static final Map<String, String> getValidAddressVOTemplate() { Map<String, String> fields = new HashMap<String, String>(); fields.put("customerAddressName", ""); fields.put("customerLine1StreetAddress", ""); fields.put("customerLine2StreetAddress", ""); fields.put("customerCityName", ""); fields.put("customerStateCode", ""); fields.put("customerZipCode", ""); fields.put("customerCountryCode", ""); fields.put("customerAddressInternationalProvinceName", ""); fields.put("customerInternationalMailCode", ""); fields.put("customerEmailAddress", ""); fields.put("customerAddressTypeCode", ""); fields.put("customerAddressEndDate", ""); return fields; }
Example 13
Source Project: spacewalk Source File: RebootActionCleanup.java License: GNU General Public License v2.0 | 6 votes |
/** * {@inheritDoc} */ public void execute(JobExecutionContext arg0In) throws JobExecutionException { List<Map<String, Long>> failedRebootActions = lookupRebootActionCleanup(); for (Map<String, Long> fa : failedRebootActions) { Long sid = fa.get("server_id"); Long aid = fa.get("action_id"); List<Long> fAids = invalidateActionRecursive(sid, aid); for (Long fAid : fAids) { invalidateKickstartSession(sid, fAid); } } if (failedRebootActions.size() > 0) { log.info("Set " + failedRebootActions.size() + " reboot action(s) to failed. Running longer than 6 hours."); } }
Example 14
Source Project: ambiverse-nlu Source File: RealRunningTimeTracker.java License: Apache License 2.0 | 6 votes |
private TimingInfo getTrackedInfoImpl(Map<String, Map<Integer, Long>> start, Map<String, Map<Integer, Long>> end) { TimingInfo timingInfo = new TimingInfo(); for (Entry<String, Integer> e : moduleLevelStart.entrySet()) { String module = e.getKey(); int level = e.getValue(); double totalTime = 0.0; double maxTime = 0.0; for (Integer uniqueId : end.get(module).keySet()) { Long finish = end.get(module).get(uniqueId); assert start.containsKey(module) : "No start for end."; Long begin = start.get(module).get(uniqueId); Long dur = finish - begin; totalTime += dur; if (dur > maxTime) { maxTime = dur; } } double avgTime = totalTime / end.get(module).size(); timingInfo.addModule(new Module(module, level, end.get(module).size(), avgTime, maxTime)); } timingInfo.setTotalExecutionTime(overallEndTime - overallStartTime); return timingInfo; }
Example 15
Source Project: sakai Source File: CourseGradeComparator.java License: Educational Community License v2.0 | 5 votes |
public CourseGradeComparator(final GradebookInformation gradebookInformation) { final Map<String, Double> gradeMap = gradebookInformation.getSelectedGradingScaleBottomPercents(); this.ascendingGrades = new ArrayList<>(gradeMap.keySet()); this.ascendingGrades.sort(new Comparator<String>() { @Override public int compare(final String a, final String b) { return new CompareToBuilder() .append(gradeMap.get(a), gradeMap.get(b)) .toComparison(); } }); }
Example 16
Source Project: netbeans Source File: SymfonyCommonLineAnnotationLineParserTest.java License: Apache License 2.0 | 5 votes |
public void testValidUseCase_01() throws Exception { AnnotationParsedLine parsedLine = parser.parse(" \"short_bio\" = {@Assert\\NotBlank(), @Assert\\MaxLength(limit = 100, "); assertNotNull(parsedLine); assertEquals("", parsedLine.getName()); assertEquals("\"short_bio\" = {@Assert\\NotBlank(), @Assert\\MaxLength(limit = 100,", parsedLine.getDescription()); assertFalse(parsedLine.startsWithAnnotation()); Map<OffsetRange, String> types = parsedLine.getTypes(); assertEquals(2, types.size()); String type1 = types.get(new OffsetRange(20, 35)); assertNotNull(type1); assertEquals("Assert\\NotBlank", type1); String type2 = types.get(new OffsetRange(40, 56)); assertNotNull(type2); assertEquals("Assert\\MaxLength", type2); }
Example 17
Source Project: arcusplatform Source File: Transformers.java License: Apache License 2.0 | 5 votes |
static void addOnOffAttrs(Model m, ImmutableMap.Builder<String, Object> attrs, Map<String, Object> params) { if(params == null) { params = ImmutableMap.of(); } assertCapability(m, SwitchCapability.NAMESPACE); Boolean on = (Boolean) params.get(Commands.OnOff.arg_on); if(on == null) { throw new ErrorEventException(Constants.Error.VALUE_OUT_OF_RANGE, Commands.OnOff.arg_on + " must be true or false"); } String newState = on ? SwitchCapability.STATE_ON : SwitchCapability.STATE_OFF; if(!Objects.equals(SwitchModel.getState(m), newState)) { attrs.put(SwitchCapability.ATTR_STATE, newState); } }
Example 18
Source Project: jdk8u_jdk Source File: PKIXRevocationChecker.java License: GNU General Public License v2.0 | 5 votes |
/** * Sets the OCSP responses. These responses are used to determine * the revocation status of the specified certificates when OCSP is used. * * @param responses a map of OCSP responses. Each key is an * {@code X509Certificate} that maps to the corresponding * DER-encoded OCSP response for that certificate. A deep copy of * the map is performed to protect against subsequent modification. */ public void setOcspResponses(Map<X509Certificate, byte[]> responses) { if (responses == null) { this.ocspResponses = Collections.<X509Certificate, byte[]>emptyMap(); } else { Map<X509Certificate, byte[]> copy = new HashMap<>(responses.size()); for (Map.Entry<X509Certificate, byte[]> e : responses.entrySet()) { copy.put(e.getKey(), e.getValue().clone()); } this.ocspResponses = copy; } }
Example 19
Source Project: parquet-mr Source File: TestReadWriteOldListBehavior.java License: Apache License 2.0 | 5 votes |
@Test public void testMapWithNulls() throws Exception { Schema schema = new Schema.Parser().parse( Resources.getResource("map_with_nulls.avsc").openStream()); File tmp = File.createTempFile(getClass().getSimpleName(), ".tmp"); tmp.deleteOnExit(); tmp.delete(); Path file = new Path(tmp.getPath()); Map<CharSequence, Integer> map = new HashMap<>(); try(AvroParquetWriter<GenericRecord> writer = new AvroParquetWriter<GenericRecord>(file, schema)) { // Write a record with a null value map.put(str("thirty-four"), 34); map.put(str("eleventy-one"), null); map.put(str("one-hundred"), 100); GenericData.Record record = new GenericRecordBuilder(schema) .set("mymap", map).build(); writer.write(record); } try(AvroParquetReader<GenericRecord> reader = new AvroParquetReader<>(testConf, file)) { GenericRecord nextRecord = reader.read(); assertNotNull(nextRecord); assertEquals(map, nextRecord.get("mymap")); } }
Example 20
Source Project: netbeans Source File: CompositeComponentLibrary.java License: Apache License 2.0 | 5 votes |
@Override public Map<String, Tag> getTags() { Map<String, Tag> map = new HashMap<>(); Collection<CompositeComponent> components = getCompositeComponentsMap().values(); for (CompositeComponent cc : components) { map.put(cc.getName(), new LazyLoadingTag(cc)); } return map; }
Example 21
Source Project: zeppelin Source File: JDBCInterpreterTest.java License: Apache License 2.0 | 5 votes |
@Test public void testStatementPrecodeWithAnotherPrefix() throws IOException, InterpreterException { Properties properties = new Properties(); properties.setProperty("anotherPrefix.driver", "org.h2.Driver"); properties.setProperty("anotherPrefix.url", getJdbcConnection()); properties.setProperty("anotherPrefix.user", ""); properties.setProperty("anotherPrefix.password", ""); properties.setProperty(String.format(STATEMENT_PRECODE_KEY_TEMPLATE, "anotherPrefix"), "set @v='statementAnotherPrefix'"); JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties); jdbcInterpreter.open(); Map<String, String> localProperties = new HashMap<>(); localProperties.put("db", "anotherPrefix"); InterpreterContext context = InterpreterContext.builder() .setAuthenticationInfo(new AuthenticationInfo("testUser")) .setInterpreterOut(new InterpreterOutput(null)) .setLocalProperties(localProperties) .build(); String sqlQuery = "select @v"; InterpreterResult interpreterResult = jdbcInterpreter.interpret(sqlQuery, context); assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code()); List<InterpreterResultMessage> resultMessages = context.out.toInterpreterResultMessage(); assertEquals(InterpreterResult.Type.TABLE, resultMessages.get(0).getType()); assertEquals("@V\nstatementAnotherPrefix\n", resultMessages.get(0).getData()); }
Example 22
Source Project: dhis2-core Source File: ListGrid.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Grid substituteMetaData( Map<? extends Object, ? extends Object> metaDataMap ) { if ( metaDataMap == null || headers == null || headers.isEmpty() ) { return this; } for ( int colIndex = 0; colIndex < headers.size(); colIndex++ ) { GridHeader header = headers.get( colIndex ); // Header Object headerMetaName = metaDataMap.get( header.getName() ); if ( headerMetaName != null ) { header.setName( String.valueOf( headerMetaName ) ); } if ( header.isMeta() ) { // Column cells substituteMetaData( colIndex, colIndex, metaDataMap ); } } return this; }
Example 23
Source Project: cosmic Source File: RegionManagerImpl.java License: Apache License 2.0 | 5 votes |
@Override public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { _name = name; final Properties dbProps = DbProperties.getDbProperties(); final String regionId = dbProps.getProperty("region.id"); _id = 1; if (regionId != null) { _id = Integer.parseInt(regionId); } return true; }
Example 24
Source Project: aptoide-client-v8 Source File: InstallAnalytics.java License: GNU General Public License v3.0 | 5 votes |
private void sendRakamInstallCanceledEvent(String packageName, int versionCode) { InstallEvent installEvent = cache.get(getKey(packageName, versionCode, RAKAM_INSTALL_EVENT)); if (installEvent != null) { Map<String, Object> data = installEvent.getData(); data.put(STATUS, "fail"); data.put(ERROR_TYPE, "canceled"); data.put(ERROR_MESSAGE, "The download was canceled"); analyticsManager.logEvent(data, RAKAM_INSTALL_EVENT, installEvent.getAction(), installEvent.getContext()); cache.remove(getKey(packageName, versionCode, RAKAM_INSTALL_EVENT)); } }
Example 25
Source Project: cloudbreak Source File: ClusterUpscaleActions.java License: Apache License 2.0 | 5 votes |
@Bean(name = "CLUSTER_MANAGER_INSTALL_COMPONENTS_STATE") public Action<?, ?> clusterManagerInstallComponentsAction() { return new AbstractClusterUpscaleAction<>(ClusterManagerInitComponentsResult.class) { @Override protected void doExecute(ClusterUpscaleContext context, ClusterManagerInitComponentsResult payload, Map<Object, Object> variables) { clusterUpscaleFlowService.reinstallClusterComponents(context.getStackId()); Map<String, String> components = getInstalledComponents(variables); ClusterManagerInstallComponentsRequest request = new ClusterManagerInstallComponentsRequest(context.getStackId(), context.getHostGroupName(), context.getPrimaryGatewayHostName(), components); sendEvent(context, request.selector(), request); } }; }
Example 26
Source Project: lucene-solr Source File: TestCloudJSONFacetSKGEquiv.java License: Apache License 2.0 | 5 votes |
public RelatednessFacet(final String foreQ, final String backQ, final Map<String,Object> options) { assert null != options; final String f = null == foreQ ? "$fore" : "{!v='"+foreQ+"'}"; final String b = null == backQ ? "$back" : "{!v='"+backQ+"'}"; jsonData.putAll(options); // we don't allow these to be overridden by options, so set them now... jsonData.put("type", "func"); jsonData.put("func", "relatedness("+f+","+b+")"); }
Example 27
Source Project: review-board-idea-plugin Source File: CommentsDiffTool.java License: Apache License 2.0 | 5 votes |
private void updateHighLights(Editor editor) { MarkupModel markup = editor.getMarkupModel(); for (RangeHighlighter customRangeHighlighter : newCommentHighlighters) { markup.removeHighlighter(customRangeHighlighter); } newCommentHighlighters.clear(); int lineCount = markup.getDocument().getLineCount(); Map<Integer, List<Comment>> lineComments = lineComments(comments); for (Map.Entry<Integer, List<Comment>> entry : lineComments.entrySet()) { if (entry.getKey() > lineCount) continue; boolean hasNewComments = false; for (Comment comment : entry.getValue()) { if (comment.id == null) { hasNewComments = true; break; } } TextAttributes attributes = new TextAttributes(); if (hasNewComments) attributes.setBackgroundColor(JBColor.PINK); else attributes.setBackgroundColor(JBColor.YELLOW); RangeHighlighter rangeHighlighter = markup .addLineHighlighter(entry.getKey() - 1, HighlighterLayer.SELECTION + (hasNewComments ? 2 : 1), attributes); rangeHighlighter.setGutterIconRenderer(new CommentGutterIconRenderer()); newCommentHighlighters.add(rangeHighlighter); } }
Example 28
Source Project: sftp-fs Source File: SFTPFileSystemTest.java License: Apache License 2.0 | 5 votes |
@Test public void testReadAttributesMapNoTypeBasicSize() throws IOException { Path foo = addFile("/foo"); setContents(foo, new byte[1024]); Map<String, Object> attributes = fileSystem.readAttributes(createPath("/foo"), "size"); Map<String, ?> expected = Collections.singletonMap("basic:size", Files.size(foo)); assertEquals(expected, attributes); }
Example 29
Source Project: distributedlog Source File: TestCountBasedStreamChooser.java License: Apache License 2.0 | 5 votes |
@Test(timeout = 60000) public void testHostsHaveDifferentNumberStreams() { Map<SocketAddress, Set<String>> streamDistribution = new HashMap<SocketAddress, Set<String>>(); Set<String> allStreams = new HashSet<String>(); int numHosts = 6; int maxStreamsPerHost = 4; int port = 1000; for (int i = 0; i < numHosts; i++) { int group = i / 2; int numStreamsThisGroup = maxStreamsPerHost - group; SocketAddress address = new InetSocketAddress("127.0.0.1", port + i); Set<String> streams = new HashSet<String>(); for (int j = 1; j <= numStreamsThisGroup; j++) { String streamName = "HostsHaveDifferentNumberStreams-" + i + "-" + j; streams.add(streamName); allStreams.add(streamName); } streamDistribution.put(address, streams); } Set<String> streamsChoosen = new HashSet<String>(); CountBasedStreamChooser chooser = new CountBasedStreamChooser(streamDistribution); for (int i = 0; i < allStreams.size(); i++) { String s = chooser.choose(); assertNotNull(s); streamsChoosen.add(s); } assertNull(chooser.choose()); assertEquals(allStreams.size(), streamsChoosen.size()); assertTrue(Sets.difference(allStreams, streamsChoosen).isEmpty()); }
Example 30
Source Project: feilong-taglib Source File: BreadCrumbUtil.java License: Apache License 2.0 | 5 votes |
/** * 按照父子关系排序好的 list. * * <ol> * <li>如果没有传递{@code currentPath},那么渲染全部的{@code List<BreadCrumbEntity<Object>>}, <br> * 但是如果此时的{@code List<BreadCrumbEntity<Object>>} 不是标准的面包屑树,即如果含有重复的parentId,那么会 throw {@link IllegalArgumentException}<br> * </li> * <li>如果设置了{@link BreadCrumbParams#setCurrentPath(String)}参数,如果没有找到{@code currentPath},什么都不会渲染;因为{@code currentPath}不在所有的面包屑中<br> * </li> * <li>如果设置了 {@link BreadCrumbParams#setCurrentPath(String)}参数,那么{@code currentPath} 路径,然后渲染到当前节点;<br> * </li> * </ol> * * @param <T> * the generic type * @param breadCrumbParams * the bread crumb params * @return the all parent site map entity list */ private static <T> List<BreadCrumbEntity<T>> lookUpCurrentBreadCrumbEntityTreeList(BreadCrumbParams breadCrumbParams){ String currentPath = breadCrumbParams.getCurrentPath(); List<BreadCrumbEntity<T>> breadCrumbEntityList = breadCrumbParams.getBreadCrumbEntityList(); //--------------------------------------------------------------- if (isNullOrEmpty(currentPath)){ //find all Map<T, Integer> groupCount = AggregateUtil.groupCount(breadCrumbEntityList, "parentId"); for (Map.Entry<T, Integer> entry : groupCount.entrySet()){ Integer value = entry.getValue(); Validate.isTrue(value <= 1, "currentPath isNullOrEmpty,but breadCrumbEntityList has repeat parentId data!"); } return sortOutAllParentBreadCrumbEntityList(breadCrumbEntityList); } //--------------------------------------------------------------- BreadCrumbEntity<T> currentBreadCrumbEntity = getBreadCrumbEntityByPath(currentPath, breadCrumbEntityList); if (isNullOrEmpty(currentBreadCrumbEntity)){ if (LOGGER.isWarnEnabled()){ LOGGER.warn("when currentPath:{},in breadCrumbEntityList:[{}],can't find", currentPath, JsonUtil.format(breadCrumbParams)); } return emptyList(); } //--------------------------------------------------------------- return sortOutAllParentBreadCrumbEntityList(currentBreadCrumbEntity, breadCrumbEntityList); }