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

The following are Jave code examples for showing how to use computeIfAbsent() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-servicecomb-java-chassis   File: InstanceCache.java   View Source Code Vote up 7 votes
protected Map<String, List<CacheEndpoint>> createTransportMap() {
  Map<String, List<CacheEndpoint>> transportMap = new HashMap<>();
  for (MicroserviceInstance instance : instanceMap.values()) {
    // 过滤到不可用实例
    if (instance.getStatus() != MicroserviceInstanceStatus.UP) {
      continue;
    }
    for (String endpoint : instance.getEndpoints()) {
      try {
        URI uri = URI.create(endpoint);
        String transportName = uri.getScheme();

        List<CacheEndpoint> cacheEndpointList = transportMap.computeIfAbsent(transportName, k -> new ArrayList<>());
        cacheEndpointList.add(new CacheEndpoint(endpoint, instance));
      } catch (Exception e) {
        LOGGER.warn("unrecognized address find, ignore " + endpoint);
      }
    }
  }
  return transportMap;
}
 
Example 2
Project: Higher-Cloud-Computing-Project   File: ResultAndUpdates.java   View Source Code Vote up 6 votes
/**
 * Sum collection of ResultAndUpdate into one: results are reduced by specified binary operator and updates are merged.
 *
 * @param reducer Reducer used to combine computation results.
 * @param resultsAndUpdates ResultAndUpdates to be combined with.
 * @param <R> Type of computation result.
 * @return Sum of collection ResultAndUpdate objects.
 */
@SuppressWarnings("unchecked")
static <R> ResultAndUpdates<R> sum(IgniteFunction<List<R>, R> reducer,
    Collection<ResultAndUpdates<R>> resultsAndUpdates) {
    Map<String, Map> allUpdates = new HashMap<>();

    for (ResultAndUpdates<R> ru : resultsAndUpdates) {
        for (String cacheName : ru.updates.keySet()) {
            allUpdates.computeIfAbsent(cacheName, s -> new HashMap());

            allUpdates.get(cacheName).putAll(ru.updates.get(cacheName));
        }
    }

    List<R> results = resultsAndUpdates.stream().map(ResultAndUpdates::result).collect(Collectors.toList());

    return new ResultAndUpdates<>(reducer.apply(results), allUpdates);
}
 
Example 3
Project: shuffleboard   File: Maps.java   View Source Code Vote up 6 votes
/**
 * An unsafe version of {@link Map#computeIfAbsent(Object, Function) Map.computeIfAbsent} that may throw a checked
 * exception.
 *
 * @param map      the map to modify
 * @param key      the key to get
 * @param function the compute function
 * @param <K>      the type of keys in the map
 * @param <V>      the type of values in the map
 * @param <X>      the type of exception that the compute function may throw
 *
 * @return
 *
 * @throws X if the compute function threw an exception
 */
public static <K, V, X extends Throwable> V computeIfAbsent(
    Map<K, V> map, K key, ThrowingFunction<? super K, ? extends V, ? extends X> function) throws X {
  Throwable[] exception = {null};
  final Object none = new Object();
  V value = map.computeIfAbsent(key, k -> {
    try {
      return function.apply(k);
    } catch (Throwable e) {
      exception[0] = e;
      return (V) none;
    }
  });
  if (value == none) { // NOPMD reference equality check
    throw (X) exception[0];
  } else {
    return value;
  }
}
 
Example 4
Project: killbill-easytax-plugin   File: EasyTaxTaxCalculator.java   View Source Code Vote up 6 votes
private String productNameForInvoiceItem(final InvoiceItem invoiceItem,
        final Map<String, String> planToProductCache, final UUID kbTenantId) {
    final String planName = invoiceItem.getPlanName();
    if (planName == null) {
        return null;
    }

    return planToProductCache.computeIfAbsent(planName, k -> {
        try {
            StaticCatalog catalog = killbillApi.getCatalogUserApi().getCurrentCatalog(null,
                    new EasyTaxTenantContext(kbTenantId, invoiceItem.getAccountId()));
            Plan plan = catalog.findCurrentPlan(planName);
            return (plan != null && plan.getProduct() != null ? plan.getProduct().getName()
                    : null);
        } catch (CatalogApiException e) {
            return null;
        }
    });
}
 
Example 5
Project: openjdk-jdk10   File: ModuleLayer.java   View Source Code Vote up 6 votes
/**
 * Checks a configuration and the module-to-loader mapping to ensure that
 * no two modules mapped to the same class loader have the same package.
 * It also checks that no two automatic modules have the same package.
 *
 * @throws LayerInstantiationException
 */
private static void checkForDuplicatePkgs(Configuration cf,
                                          Function<String, ClassLoader> clf)
{
    // HashMap allows null keys
    Map<ClassLoader, Set<String>> loaderToPackages = new HashMap<>();
    for (ResolvedModule resolvedModule : cf.modules()) {
        ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
        ClassLoader loader = clf.apply(descriptor.name());

        Set<String> loaderPackages
            = loaderToPackages.computeIfAbsent(loader, k -> new HashSet<>());

        for (String pkg : descriptor.packages()) {
            boolean added = loaderPackages.add(pkg);
            if (!added) {
                throw fail("More than one module with package %s mapped" +
                           " to the same class loader", pkg);
            }
        }
    }
}
 
Example 6
Project: incubator-servicecomb-saga   File: JpaPersistentStore.java   View Source Code Vote up 6 votes
@Override
public Map<String, List<EventEnvelope>> findPendingSagaEvents() {
  List<SagaEventEntity> events = repo.findIncompleteSagaEventsGroupBySagaId();

  Map<String, List<EventEnvelope>> pendingEvents = new HashMap<>();
  for (SagaEventEntity event : events) {
    pendingEvents.computeIfAbsent(event.sagaId(), id -> new LinkedList<>());
    pendingEvents.get(event.sagaId()).add(
        new EventEnvelope(
            event.id(),
            event.creationTime(),
            sagaEventFormat.toSagaEvent(event.sagaId(), event.type(), event.contentJson())));
  }

  return pendingEvents;
}
 
Example 7
Project: hashsdn-controller   File: RpcFacade.java   View Source Code Vote up 5 votes
public Rpcs mapRpcs() {

        final Map<String, Map<String, ModuleRpcs>> map = new HashMap<>();

        for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService
                .getModuleMXBeanEntryMap().entrySet()) {

            Map<String, ModuleRpcs> namespaceToModules = map.computeIfAbsent(namespaceToModuleEntry.getKey(),
                k -> new HashMap<>());

            for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue()
                    .entrySet()) {

                ModuleRpcs rpcMapping = namespaceToModules.computeIfAbsent(moduleEntry.getKey(),
                    k -> new ModuleRpcs(yangStoreService.getEnumResolver()));

                final ModuleMXBeanEntry entry = moduleEntry.getValue();

                for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
                    rpcMapping.addNameMapping(runtimeEntry);
                    for (final RuntimeBeanEntry.Rpc rpc : runtimeEntry.getRpcs()) {
                        rpcMapping.addRpc(runtimeEntry, rpc);
                    }
                }
            }
        }

        return new Rpcs(map);
    }
 
Example 8
Project: arez   File: MemoizeCache.java   View Source Code Vote up 5 votes
/**
 * Retrieve the computed value for specified parameters, creating it if necessary.
 *
 * @param args the arguments passed to the memoized function.
 */
@SuppressWarnings( "unchecked" )
private ComputedValue<T> getComputedValue( @Nonnull final Object... args )
{
  apiInvariant( () -> args.length == _argCount,
                () -> "MemoizeCache.getComputedValue called with " + args.length + " arguments but expected " +
                      _argCount + " arguments." );
  Map<Object, Object> map = _cache;
  final int size = args.length - 1;
  for ( int i = 0; i < size; i++ )
  {
    map = (Map<Object, Object>) map.computeIfAbsent( args[ i ], v -> new HashMap<>() );
  }
  return (ComputedValue<T>) map.computeIfAbsent( args[ size ], v -> createComputedValue( args ) );
}
 
Example 9
Project: openjdk-jdk10   File: ClassTree.java   View Source Code Vote up 5 votes
/**
 * Adjust the Class Tree. Add the class interface  in to it's super classes
 * or super interface's sub-interface set.
 *
 * @param map the entire map.
 * @param superclass java.lang.Object or the super-interface.
 * @param typeElement sub-interface to be mapped.
 * @returns boolean true if class added, false if class already processed.
 */
private boolean add(Map<TypeElement, SortedSet<TypeElement>> map, TypeElement superclass, TypeElement typeElement) {
    SortedSet<TypeElement> sset = map.computeIfAbsent(superclass, s ->  new TreeSet<>(comparator));
    if (sset.contains(typeElement)) {
        return false;
    } else {
        sset.add(typeElement);
    }
    return true;
}
 
Example 10
Project: launcher-backend   File: MissionControlValidator.java   View Source Code Vote up 5 votes
public void validateGitHubRepositoryExists(UIValidationContext context, String repository) {
    Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
    String validationMessage = (String) attributeMap.computeIfAbsent("validate_repo_" + repository, key -> {
        List<String> authList = (List<String>) attributeMap.get(HttpHeaders.AUTHORIZATION);
        String authHeader = (authList == null || authList.isEmpty()) ? null : authList.get(0);
        return missionControlFacade.validateGitHubRepositoryExists(authHeader, repository);
    });
    if (validationMessage != null && !MissionControl.VALIDATION_MESSAGE_OK.equals(validationMessage)) {
        context.addValidationError(context.getCurrentInputComponent(), validationMessage);
    }
}
 
Example 11
Project: launcher-backend   File: MissionControlValidator.java   View Source Code Vote up 5 votes
public void validateOpenShiftProjectExists(UIValidationContext context, String project, String cluster) {
    Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
    String validationMessage = (String) attributeMap.computeIfAbsent("validate_project_" + project, key -> {
        List<String> authList = (List<String>) attributeMap.get(HttpHeaders.AUTHORIZATION);
        String authHeader = (authList == null || authList.isEmpty()) ? null : authList.get(0);
        return missionControlFacade.validateOpenShiftProjectExists(authHeader, project, cluster);
    });
    if (validationMessage != null && !MissionControl.VALIDATION_MESSAGE_OK.equals(validationMessage)) {
        context.addValidationWarning(context.getCurrentInputComponent(), validationMessage);
    }
}
 
Example 12
Project: plugin-prov-aws   File: ProvAwsPriceImportResource.java   View Source Code Vote up 5 votes
/**
 * Install a new region.
 */
private ProvLocation installRegion(final Map<String, ProvLocation> regions, final String region, final Node node) {
	return regions.computeIfAbsent(region, r -> {
		final ProvLocation location = new ProvLocation();
		location.setNode(node);
		location.setName(r);
		locationRepository.saveAndFlush(location);
		return location;
	});
}
 
Example 13
Project: r8   File: MethodNameMinifier.java   View Source Code Vote up 5 votes
private void addStatesToGlobalMapForMethod(
    DexEncodedMethod method, Set<NamingState<DexProto>> collectedStates,
    Map<Wrapper<DexMethod>, Set<NamingState<DexProto>>> globalStateMap,
    Map<Wrapper<DexMethod>, Set<DexMethod>> sourceMethodsMap,
    Map<Wrapper<DexMethod>, NamingState<DexProto>> originStates, DexType originInterface) {
  Wrapper<DexMethod> key = equivalence.wrap(method.method);
  Set<NamingState<DexProto>> stateSet =
      globalStateMap.computeIfAbsent(key, k -> new HashSet<>());
  stateSet.addAll(collectedStates);
  sourceMethodsMap.computeIfAbsent(key, k -> new HashSet<>()).add(method.method);
  originStates.putIfAbsent(key, states.get(originInterface));
}
 
Example 14
Project: AptSpring   File: DefinitionContentInspector.java   View Source Code Vote up 5 votes
/**
 * Inspects the instance graph for cycles, any cycle is printed as an error.   The nameToEntity parameter doesn't list expected
 * instances, any instances that are not found in the nameToInstances map (they are looked for because they are referenced as a
 * dependency by an instance in the map) and are not found by name in the definition's expectedInstances are treated as errors
 * as well.
 * 
 * @param definition definition being processed.  Will uses it's expected list, any instances references as dependencies but
 *     not found, not listed as expected in this DefinitionModel, will be treated as errors.
 * @param nameToEntity name to unique instanceModels, verified before call.
 * @param errorListner accepts and displays all errors produced by analyzing the models
 * @return true if an error occurred, false otherwise
 */
private boolean detectCyclesInEntityGraph(final DefinitionModel definition, final Map<String, InstanceModel> nameToEntity,
    final Consumer<ErrorModel> errorListener) {
  final Map<String, ExpectedModel> missing = new HashMap<>();
  final DirectedGraph<BaseInstanceModel, DefaultEdge> entityGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
  for (BaseInstanceModel entity : nameToEntity.values()) {
    if (!entityGraph.containsVertex(entity)) {
      entityGraph.addVertex(entity);
    }
    if (InstanceModel.class.isAssignableFrom(entity.getClass())) {
      InstanceModel instanceModel = (InstanceModel) entity;
      for (InstanceDependencyModel instanceDependency : instanceModel.getDependencies()) {
        BaseInstanceModel dependency = nameToEntity.get(instanceDependency.getIdentity());
        if (dependency == null) {
          dependency = missing.computeIfAbsent(instanceDependency.getIdentity(), s -> new ExpectedModel(s));
          missing.get(instanceDependency.getIdentity())
            .addDefinitionReferenceToType(instanceModel.getIdentity(), instanceDependency.getType());
        }
        if (!entityGraph.containsVertex(dependency)) {
          entityGraph.addVertex(dependency);
        }
        entityGraph.addEdge(entity, dependency);
      }
    }
  }
  
  boolean errored = errorsForCycles(errorListener, entityGraph);
  errored = testAllMissingEntitiesAreExpected(definition, errorListener, missing, entityGraph) || errored;
  errored = errorUnusedExpectedsOnDefinition(definition, errorListener, missing) || errored;
  return errored;
}
 
Example 15
Project: elasticsearch_my   File: SearchPhaseControllerTests.java   View Source Code Vote up 5 votes
private Suggest reducedSuggest(AtomicArray<QuerySearchResultProvider> results) {
    Map<String, List<Suggest.Suggestion<CompletionSuggestion.Entry>>> groupedSuggestion = new HashMap<>();
    for (AtomicArray.Entry<QuerySearchResultProvider> entry : results.asList()) {
        for (Suggest.Suggestion<?> suggestion : entry.value.queryResult().suggest()) {
            List<Suggest.Suggestion<CompletionSuggestion.Entry>> suggests =
                groupedSuggestion.computeIfAbsent(suggestion.getName(), s -> new ArrayList<>());
            suggests.add((Suggest.Suggestion<CompletionSuggestion.Entry>) suggestion);
        }
    }
    return new Suggest(groupedSuggestion.values().stream().map(CompletionSuggestion::reduceTo)
        .collect(Collectors.toList()));
}
 
Example 16
Project: aws-request-signing-apache-interceptor   File: AWSRequestSigningApacheInterceptor.java   View Source Code Vote up 5 votes
/**
 *
 * @param params list of HTTP query params as NameValuePairs
 * @return a multimap of HTTP query params
 */
private static Map<String, List<String>> nvpToMapParams(final List<NameValuePair> params) {
    Map<String, List<String>> parameterMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    for (NameValuePair nvp : params) {
        List<String> argsList =
                parameterMap.computeIfAbsent(nvp.getName(), k -> new ArrayList<>());
        argsList.add(nvp.getValue());
    }
    return parameterMap;
}
 
Example 17
Project: TOSCAna   File: Pod.java   View Source Code Vote up 5 votes
public static List<Pod> getPods(Collection<NodeStack> stacks) {
    //Group Node Stacks
    Map<Compute, List<NodeStack>> stackMap = new HashMap<>();
    for (NodeStack stack : stacks) {
        Compute computeNode = stack.getComputeNode();
        stackMap.computeIfAbsent(computeNode, k -> new ArrayList<>());
        stackMap.get(computeNode).add(stack);
    }

    //Convert NodeStacks to Pods
    List<Pod> pods = new ArrayList<>();
    stackMap.forEach((k, v) -> pods.add(new Pod(v)));
    return pods;
}
 
Example 18
Project: koryphe   File: ReflectionUtil.java   View Source Code Vote up 5 votes
/**
 * Get a map of simple class name to class, for all sub classes of a given class.
 * The results are cached.
 *
 * @param clazz the class to get simple class names for.
 * @return a map of simple class name to class
 */
public static Map<String, Set<Class>> getSimpleClassNames(final Class<?> clazz) {
    Map<String, Set<Class>> simpleClassNames = simpleClassNamesCache.get(clazz);
    if (null == simpleClassNames) {
        final Set<Class> subTypes = getSubTypes(clazz);
        simpleClassNames = new HashMap<>(subTypes.size());
        for (final Class subType : subTypes) {
            final Set<Class> simpleClasses = simpleClassNames.computeIfAbsent(subType.getSimpleName(), k -> new HashSet<>());
            simpleClasses.add(subType);
        }
        simpleClassNames = Collections.unmodifiableMap(simpleClassNames);
        simpleClassNamesCache.put(clazz, simpleClassNames);
    }
    return simpleClassNames;
}
 
Example 19
Project: martini-core   File: ScenarioScope.java   View Source Code Vote up 4 votes
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	Map<String, Object> scope = SCOPE_REF.get();
	return scope.computeIfAbsent(name, k -> objectFactory.getObject());
}
 
Example 20
Project: hashsdn-controller   File: ServiceReferenceRegistryImpl.java   View Source Code Vote up 4 votes
private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories,
        final LookupRegistry lookupRegistry,
        final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory,
        final boolean writable) {
    this.factories = factories;
    this.writable = writable;
    this.lookupRegistry = lookupRegistry;

    this.serviceReferenceRegistrator = serviceReferenceRegistratorFactory.create();

    Map<String, Set<String /* QName */>> modifiableFactoryNamesToQNames = new HashMap<>();
    Set<ServiceInterfaceAnnotation> allAnnotations = new HashSet<>();
    Set<String /* qName */> allQNameSet = new HashSet<>();

    for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
        if (!entry.getKey().equals(entry.getValue().getImplementationName())) {
            LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
            throw new IllegalArgumentException(
                    "Possible error in code: Mismatch between supplied and actual name of " + entry);
        }
        Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper
                .getServiceInterfaceAnnotations(entry.getValue());
        Set<String> names = InterfacesHelper.getQNames(siAnnotations);
        allAnnotations.addAll(siAnnotations);
        allQNameSet.addAll(names);
        modifiableFactoryNamesToQNames.put(entry.getKey(), names);
    }
    this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames);
    this.allQNames = ImmutableSet.copyOf(allQNameSet);
    // fill namespacesToAnnotations
    Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>>
        modifiableNamespacesToAnnotations = new HashMap<>();
    Map<String /* service qName */, ServiceInterfaceAnnotation>
        modifiableServiceQNamesToAnnotations = new HashMap<>();
    for (ServiceInterfaceAnnotation sia : allAnnotations) {
        Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations
                .computeIfAbsent(sia.namespace(), k -> new HashMap<>());
        if (ofNamespace.containsKey(sia.localName())) {
            LOG.error(
                    "Cannot construct namespacesToAnnotations map, conflict between local names in {},"
                    + " offending local name: {}, map so far {}",
                    sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
            throw new IllegalArgumentException(
                    "Conflict between local names in " + sia.namespace() + " : " + sia.localName());
        }
        ofNamespace.put(sia.localName(), sia);
        modifiableServiceQNamesToAnnotations.put(sia.value(), sia);
    }
    this.namespacesToAnnotations = ImmutableMap.copyOf(modifiableNamespacesToAnnotations);
    this.serviceQNamesToAnnotations = ImmutableMap.copyOf(modifiableServiceQNamesToAnnotations);
    LOG.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
}