List of usage examples for java.util Map forEach
default void forEach(BiConsumer<? super K, ? super V> action)
From source file:com.okta.swagger.codegen.AbstractOktaJavaClientCodegen.java
protected void buildDiscriminationMap(Swagger swagger) { swagger.getDefinitions().forEach((name, model) -> { ObjectNode discriminatorMapExtention = (ObjectNode) model.getVendorExtensions() .get("x-openapi-v3-discriminator"); if (discriminatorMapExtention != null) { String propertyName = discriminatorMapExtention.get("propertyName").asText(); ObjectNode mapping = (ObjectNode) discriminatorMapExtention.get("mapping"); ObjectMapper mapper = new ObjectMapper(); Map<String, String> result = mapper.convertValue(mapping, Map.class); result = result.entrySet().stream().collect(Collectors .toMap(e -> e.getValue().substring(e.getValue().lastIndexOf('/') + 1), e -> e.getKey())); result.forEach((key, value) -> { reverseDiscriminatorMap.put(key, name); });//from w ww . j a v a 2 s .com discriminatorMap.put(name, new Discriminator(name, propertyName, result)); } }); }
From source file:org.hswebframework.web.service.authorization.simple.SimpleAuthorizationSettingService.java
@Override public Authentication initUserAuthorization(String userId) { if (null == userId) { return null; }/*from w w w . j ava 2 s .c o m*/ UserEntity userEntity = userService.selectByPk(userId); if (userEntity == null) { return null; } SimpleAuthentication authentication = new SimpleAuthentication(); // ? authentication.setUser(SimpleUser.builder().id(userId).username(userEntity.getUsername()) .name(userEntity.getName()).type("default").build()); // authentication.setRoles(userService.getUserRole(userId).stream() .map(role -> new SimpleRole(role.getId(), role.getName())).collect(Collectors.toList())); List<String> settingIdList = getUserSetting(userId).stream().map(AuthorizationSettingEntity::getId) .collect(Collectors.toList()); if (settingIdList.isEmpty()) { authentication.setPermissions(new ArrayList<>()); return authentication; } // where status=1 and setting_id in (?,?,?) List<AuthorizationSettingDetailEntity> detailList = DefaultDSLQueryService .createQuery(authorizationSettingDetailDao).where(status, STATE_OK).and() .in(settingId, settingIdList).listNoPaging(); //??id? List<String> permissionIds = detailList.stream().map(AuthorizationSettingDetailEntity::getPermissionId) .distinct().collect(Collectors.toList()); //??? Map<String, PermissionEntity> permissionEntityCache = permissionService.selectByPk(permissionIds).stream() .collect(Collectors.toMap(PermissionEntity::getId, Function.identity())); //? detailList = detailList.stream().filter(detail -> { PermissionEntity entity = permissionEntityCache.get(detail.getPermissionId()); if (entity == null || !STATUS_ENABLED.equals(entity.getStatus())) { return false; } List<String> allActions = entity.getActions().stream().map(ActionEntity::getAction) .collect(Collectors.toList()); if (isNotEmpty(entity.getActions()) && isNotEmpty(detail.getActions())) { detail.setActions( detail.getActions().stream().filter(allActions::contains).collect(Collectors.toSet())); } if (isEmpty(entity.getSupportDataAccessTypes())) { detail.setDataAccesses(new java.util.ArrayList<>()); } else if (isNotEmpty(detail.getDataAccesses()) && !entity.getSupportDataAccessTypes().contains("*")) { //????????,??? detail.setDataAccesses(detail.getDataAccesses().stream().filter(access -> //????? //???CUSTOM_SCOPE_ORG_SCOPE //??CUSTOM_SCOPE entity.getSupportDataAccessTypes().stream().anyMatch(type -> type.startsWith(access.getType()))) .collect(Collectors.toList())); } return true; }).collect(Collectors.toList()); //?? Map<String, List<AuthorizationSettingDetailEntity>> settings = detailList.stream() .collect(Collectors.groupingBy(AuthorizationSettingDetailEntity::getPermissionId)); List<Permission> permissions = new ArrayList<>(); //????? Map<String, List<ParentPermission>> parentsPermissions = permissionEntityCache.values().stream() .map(PermissionEntity::getParents).filter(Objects::nonNull).flatMap(Collection::stream) .collect(Collectors.groupingBy(ParentPermission::getPermission)); settings.forEach((permissionId, details) -> { SimplePermission permission = new SimplePermission(); permission.setId(permissionId); Set<String> actions = new HashSet<>(); Set<DataAccessConfig> dataAccessConfigs = new HashSet<>(); //?,?? Collections.sort(details); for (AuthorizationSettingDetailEntity detail : details) { //????,?? if (Boolean.FALSE.equals(detail.getMerge())) { actions.clear(); dataAccessConfigs.clear(); } // actions if (null != detail.getActions()) { actions.addAll(detail.getActions()); } // ???? if (null != detail.getDataAccesses()) { dataAccessConfigs.addAll(detail.getDataAccesses().stream().map(dataAccessFactory::create) .collect(Collectors.toSet())); } } //?????? List<ParentPermission> parents = parentsPermissions.get(permissionId); if (parents != null) { actions.addAll(parents.stream().map(ParentPermission::getActions).filter(Objects::nonNull) .flatMap(Collection::stream).collect(Collectors.toSet())); parentsPermissions.remove(permissionId); } permission.setActions(actions); permission.setDataAccesses(dataAccessConfigs); permissions.add(permission); }); //??? parentsPermissions.forEach((per, all) -> { SimplePermission permission = new SimplePermission(); permission.setId(per); permission.setActions(all.stream().map(ParentPermission::getActions).filter(Objects::nonNull) .flatMap(Collection::stream).collect(Collectors.toSet())); permissions.add(permission); }); authentication.setPermissions(permissions); return authentication; }
From source file:org.apache.tinkerpop.gremlin.process.graph.traversal.step.sideEffect.GroupSideEffectStep.java
@Override protected void sideEffect(final Traverser.Admin<S> traverser) { final Map<K, Collection<V>> groupMap = null == this.tempGroupByMap ? traverser.sideEffects(this.sideEffectKey) : this.tempGroupByMap; // for nested traversals and not !starts.hasNext() final K key = TraversalUtil.applyNullable(traverser, keyTraversal); final V value = TraversalUtil.applyNullable(traverser, valueTraversal); Collection<V> values = groupMap.get(key); if (null == values) { values = new BulkSet<>(); groupMap.put(key, values);/*from w w w . j av a 2s. c om*/ } TraversalHelper.addToCollectionUnrollIterator(values, value, traverser.bulk()); //////// reducer for OLTP if (!this.onGraphComputer && null != this.reduceTraversal && !this.starts.hasNext()) { this.tempGroupByMap = groupMap; final Map<K, R> reduceMap = new HashMap<>(); groupMap.forEach((k, vv) -> reduceMap.put(k, TraversalUtil.applyNullable(vv, this.reduceTraversal))); traverser.sideEffects(this.sideEffectKey, reduceMap); } }
From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java
@Override public Map<Integer, Long> count(String indName, String groupByDimName, Map<String, List<Integer>> filterDims) { try {//from www . j a v a 2 s . c om Set<String> cubeIds = cubeIds(); // Do execute List<Map<Integer, Long>> results = execute(new Count2(indName, groupByDimName, filterDims), cubeIds, hzExecutorTimeout); LOGGER.debug("Group counting {} on {} with filter {} results is {}", indName, cubeIds, filterDims, results); Map<Integer, Long> result = new HashMap<Integer, Long>(); results.stream().forEach(new Consumer<Map<Integer, Long>>() { @Override public void accept(Map<Integer, Long> t) { t.forEach((k, v) -> result.merge(k, v, Long::sum)); } }); LOGGER.debug("Count {} on {} with filter {} results is {}", indName, cubeIds, filterDims, result); return result; } finally { AGG_CONTEXT.remove(); } }
From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java
@Override public Map<Integer, BigDecimal> sum(String indName, String groupByDimName, Map<String, List<Integer>> filterDims) { try {/*from ww w . ja v a 2 s.co m*/ Set<String> cubeIds = cubeIds(); // Do execute List<Map<Integer, BigDecimal>> results = execute(new Sum2(indName, groupByDimName, filterDims), cubeIds, hzExecutorTimeout); LOGGER.debug("Group {} on {} with filter {} results is {}", indName, cubeIds, filterDims, results); Map<Integer, BigDecimal> result = new HashMap<Integer, BigDecimal>(); results.stream().forEach(new Consumer<Map<Integer, BigDecimal>>() { @Override public void accept(Map<Integer, BigDecimal> t) { t.forEach((k, v) -> result.merge(k, v, BigDecimal::add)); } }); LOGGER.debug("Sum {} on {} with filter {} results is {}", indName, cubeIds, filterDims, result); return result; } finally { AGG_CONTEXT.remove(); } }
From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java
@Override public Map<Integer, RoaringBitmap> distinct(String distinctName, boolean isDim, String groupByDimName, Map<String, List<Integer>> filterDims) { try {/* w ww . j ava 2 s . c om*/ Set<String> cubeIds = cubeIds(); // Do execute List<Map<Integer, RoaringBitmap>> results = execute( new Distinct(distinctName, isDim, groupByDimName, filterDims), cubeIds, hzExecutorTimeout); LOGGER.debug("Distinct {} on {} with filter {} results is {}", distinctName, cubeIds, filterDims, results); Map<Integer, RoaringBitmap> result = new HashMap<Integer, RoaringBitmap>(results.size()); results.stream().forEach(new Consumer<Map<Integer, RoaringBitmap>>() { @Override public void accept(Map<Integer, RoaringBitmap> t) { t.forEach((k, v) -> result.merge(k, v, new BiFunction<RoaringBitmap, RoaringBitmap, RoaringBitmap>() { @Override public RoaringBitmap apply(RoaringBitmap t, RoaringBitmap u) { return RoaringBitmap.or(t, u); } })); } }); LOGGER.debug("Distinct {} on {} with filter {} results is {}", distinctName, cubeIds, filterDims, result); return result; } finally { AGG_CONTEXT.remove(); } }
From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java
/** * Execute HTTP request using GET method. * * @param path URL path (relative to base) * @param payload Map of payload values (will be converted to JSON) * @return HTTP response/*from www.j av a2 s .c o m*/ * @throws VaultConnectorException on connection error * @throws URISyntaxException on invalid URI syntax */ private String requestGet(final String path, final Map<String, String> payload) throws VaultConnectorException, URISyntaxException { /* Add parameters to URI */ URIBuilder uriBuilder = new URIBuilder(baseURL + path); payload.forEach(uriBuilder::addParameter); /* Initialize request */ HttpGet get = new HttpGet(uriBuilder.build()); /* Set X-Vault-Token header */ if (token != null) get.addHeader(HEADER_VAULT_TOKEN, token); return request(get, retries); }
From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder.java
/** * Filter out options in the step config to retain only the options provided in authentication options * @param authenticationOptions Authentication options to keep * @param stepConfig The step config to be modified *//*ww w . j a v a 2 s . c om*/ protected void filterOptions(Map<String, Map<String, String>> authenticationOptions, StepConfig stepConfig) { Map<String, Set<String>> filteredOptions = new HashMap<>(); authenticationOptions.forEach((id, option) -> { String idp = option.get(FrameworkConstants.JSAttributes.IDP); String authenticator = option.get(FrameworkConstants.JSAttributes.AUTHENTICATOR); if (StringUtils.isNotBlank(authenticator) && StringUtils.isBlank(idp)) { // If Idp is not set, but authenticator is set, idp is assumed as local idp = FrameworkConstants.LOCAL_IDP_NAME; } if (StringUtils.isNotBlank(idp)) { filteredOptions.putIfAbsent(idp, new HashSet<>()); if (StringUtils.isNotBlank(authenticator)) { filteredOptions.get(idp).add(authenticator); } } }); if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Set<String>> entry : filteredOptions.entrySet()) { sb.append('\n').append(entry.getKey()).append(" : "); sb.append(StringUtils.join(entry.getValue(), ",")); } log.debug("Authenticator options: " + sb.toString()); } Set<AuthenticatorConfig> authenticatorsToRemove = new HashSet<>(); Map<String, AuthenticatorConfig> idpsToRemove = new HashMap<>(); stepConfig.getAuthenticatorList() .forEach(authenticatorConfig -> authenticatorConfig.getIdps().forEach((idpName, idp) -> { Set<String> authenticators = filteredOptions.get(idpName); boolean removeOption = false; if (authenticators == null) { if (log.isDebugEnabled()) { log.debug(String .format("Authentication options didn't include idp: %s. Hence excluding from " + "options list", idpName)); } removeOption = true; } else if (!authenticators.isEmpty()) { // Both idp and authenticator present, but authenticator is given by display name due to the fact // that it is the one available at UI. Should translate the display name to actual name, and // keep/remove option removeOption = true; if (FrameworkConstants.LOCAL_IDP_NAME.equals(idpName)) { List<LocalAuthenticatorConfig> localAuthenticators = ApplicationAuthenticatorService .getInstance().getLocalAuthenticators(); for (LocalAuthenticatorConfig localAuthenticatorConfig : localAuthenticators) { if (authenticatorConfig.getName().equals(localAuthenticatorConfig.getName()) && authenticators.contains(localAuthenticatorConfig.getDisplayName())) { removeOption = false; break; } } if (log.isDebugEnabled()) { if (removeOption) { log.debug(String.format( "Authenticator options don't match any entry for local" + "authenticator: %s. Hence removing the option", authenticatorConfig.getName())); } else { log.debug(String.format( "Authenticator options contained a match for local " + "authenticator: %s. Hence keeping the option", authenticatorConfig.getName())); } } } else { for (FederatedAuthenticatorConfig federatedAuthConfig : idp .getFederatedAuthenticatorConfigs()) { if (authenticatorConfig.getName().equals(federatedAuthConfig.getName()) && authenticators.contains(federatedAuthConfig.getDisplayName())) { removeOption = false; break; } } if (log.isDebugEnabled()) { if (removeOption) { log.debug(String.format( "Authenticator options don't match any entry for idp: %s, " + "authenticator: %s. Hence removing the option", idpName, authenticatorConfig.getName())); } else { log.debug(String.format( "Authenticator options contained a match for idp: %s, " + "authenticator: %s. Hence keeping the option", idpName, authenticatorConfig.getName())); } } } } else { if (log.isDebugEnabled()) { log.debug(String.format( "No authenticator filters for idp %s, hence keeping it as an option", idpName)); } } if (removeOption) { if (authenticatorConfig.getIdps().size() > 1) { idpsToRemove.put(idpName, authenticatorConfig); } else { authenticatorsToRemove.add(authenticatorConfig); } } })); if (stepConfig.getAuthenticatorList().size() > authenticatorsToRemove.size()) { idpsToRemove.forEach((idp, authenticatorConfig) -> { int index = stepConfig.getAuthenticatorList().indexOf(authenticatorConfig); stepConfig.getAuthenticatorList().get(index).getIdps().remove(idp); stepConfig.getAuthenticatorList().get(index).getIdpNames().remove(idp); if (log.isDebugEnabled()) { log.debug("Removed " + idp + " option from " + authenticatorConfig.getName() + " as it " + "doesn't match the provided authenticator options"); } }); // If all idps are removed from the authenticator the authenticator should be removed. stepConfig.getAuthenticatorList().forEach(authenticatorConfig -> { if (authenticatorConfig.getIdps().isEmpty()) { authenticatorsToRemove.add(authenticatorConfig); } }); stepConfig.getAuthenticatorList().removeAll(authenticatorsToRemove); if (log.isDebugEnabled()) { log.debug("Removed " + authenticatorsToRemove.size() + " options which doesn't match the " + "provided authenticator options"); } } else { log.warn("The filtered authenticator list is empty, hence proceeding without filtering"); } }
From source file:org.apache.nifi.processors.standard.util.BaseStrictSyslog5424ParserTest.java
@Test public void testRFC5424WithVersion() { final String pri = "34"; final String version = "1"; final String stamp = "2003-10-11T22:14:15.003Z"; final String host = "mymachine.example.com"; final String appName = "su"; final String procId = "-"; final String msgId = "ID17"; final String structuredData = "-"; final String body = "BOM'su root' failed for lonvick on /dev/pts/8"; final String message = "<" + pri + ">" + version + " " + stamp + " " + host + " " + appName + " " + procId + " " + msgId + " " + "-" + " " + body; final byte[] bytes = message.getBytes(CHARSET); final ByteBuffer buffer = ByteBuffer.allocate(bytes.length); buffer.clear();/*from w w w . j a v a 2s .c o m*/ buffer.put(bytes); final Syslog5424Event event = parser.parseEvent(buffer); Assert.assertNotNull(event); Assert.assertTrue(event.isValid()); Assert.assertFalse(event.getFieldMap().isEmpty()); Map<String, String> fieldMap = event.getFieldMap(); Assert.assertEquals(pri, fieldMap.get(SyslogAttributes.PRIORITY.key())); Assert.assertEquals("2", fieldMap.get(SyslogAttributes.SEVERITY.key())); Assert.assertEquals("4", fieldMap.get(SyslogAttributes.FACILITY.key())); Assert.assertEquals(version, fieldMap.get(SyslogAttributes.VERSION.key())); Assert.assertEquals(stamp, fieldMap.get(SyslogAttributes.TIMESTAMP.key())); Assert.assertEquals(host, fieldMap.get(SyslogAttributes.HOSTNAME.key())); Assert.assertEquals(appName, fieldMap.get(Syslog5424Attributes.APP_NAME.key())); validateForPolicy(procId, fieldMap.get(Syslog5424Attributes.PROCID.key())); Assert.assertEquals(msgId, fieldMap.get(Syslog5424Attributes.MESSAGEID.key())); Pattern structuredPattern = new StrictSyslog5424Parser.NifiKeyProvider() .getStructuredElementIdParamNamePattern(); fieldMap.forEach((key, value) -> { if (!StringUtils.isBlank(value)) { Assert.assertFalse(structuredPattern.matcher(value).matches()); } }); Assert.assertEquals(body, fieldMap.get(SyslogAttributes.BODY.key())); Assert.assertEquals(message, event.getFullMessage()); Assert.assertNull(event.getSender()); }
From source file:org.springframework.jms.annotation.JmsListenerAnnotationBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { if (!this.nonAnnotatedClasses.contains(bean.getClass())) { Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> { Set<JmsListener> listenerMethods = AnnotatedElementUtils .getMergedRepeatableAnnotations(method, JmsListener.class, JmsListeners.class); return (!listenerMethods.isEmpty() ? listenerMethods : null); });/*from ww w . j ava2 s . c o m*/ if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(bean.getClass()); if (logger.isTraceEnabled()) { logger.trace("No @JmsListener annotations found on bean type: " + bean.getClass()); } } else { // Non-empty set of methods annotatedMethods.forEach((method, listeners) -> listeners .forEach(listener -> processJmsListener(listener, method, bean))); if (logger.isDebugEnabled()) { logger.debug(annotatedMethods.size() + " @JmsListener methods processed on bean '" + beanName + "': " + annotatedMethods); } } } return bean; }