Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

In this page you can find the example usage for java.util Map putIfAbsent.

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java

/**
 * Adds a device to this registry./*from   ww  w.j a  v  a2 s. co m*/
 * 
 * @param tenantId The tenant the device belongs to.
 * @param deviceId The ID of the device to add.
 * @param data Additional data to register with the device (may be {@code null}).
 * @return The outcome of the operation indicating success or failure.
 */
public RegistrationResult addDevice(final String tenantId, final String deviceId, final JsonObject data) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);

    final JsonObject obj = data != null ? data : new JsonObject().put(FIELD_ENABLED, Boolean.TRUE);
    final Map<String, JsonObject> devices = getDevicesForTenant(tenantId);
    if (devices.size() < getConfig().getMaxDevicesPerTenant()) {
        if (devices.putIfAbsent(deviceId, obj) == null) {
            dirty = true;
            return RegistrationResult.from(HTTP_CREATED);
        } else {
            return RegistrationResult.from(HTTP_CONFLICT);
        }
    } else {
        return RegistrationResult.from(HTTP_FORBIDDEN);
    }
}

From source file:io.syndesis.rest.v1.handler.connection.ConnectionActionHandler.java

@POST
@Path(value = "/{id}")
@Produces(MediaType.APPLICATION_JSON)/*from www. j ava 2s.  c  om*/
@ApiOperation("Retrieves enriched action definition, that is an action definition that has input/output data shapes and property enums defined with respect to the given action properties")
@ApiResponses(@ApiResponse(code = 200, response = ActionDefinition.class, message = "A map of zero or more action property suggestions keyed by the property name"))
public ActionDefinition enrichWithMetadata(
        @PathParam("id") @ApiParam(required = true, example = "io.syndesis:salesforce-create-or-update:latest") final String id,
        final Map<String, String> properties) {

    final Action action = actions.stream().filter(a -> a.idEquals(id)).findAny()
            .orElseThrow(() -> new EntityNotFoundException("Action with id: " + id));

    final ActionDefinition defaultDefinition = action.getDefinition();

    if (!action.getTags().contains("dynamic")) {
        return defaultDefinition;
    }

    final String connectorId = connector.getId().get();

    final Map<String, String> parameters = new HashMap<>(
            Optional.ofNullable(properties).orElseGet(HashMap::new));
    // put all action parameters with `null` values
    defaultDefinition.getPropertyDefinitionSteps()
            .forEach(step -> step.getProperties().forEach((k, v) -> parameters.putIfAbsent(k, null)));

    // lastly put all connection properties
    parameters.putAll(connection.getConfiguredProperties());

    final Client client = createClient();
    final WebTarget target = client.target(
            String.format("http://%s/api/v1/connectors/%s/actions/%s", config.getService(), connectorId, id));

    final ActionDefinition.Builder enriched = new ActionDefinition.Builder().createFrom(defaultDefinition);
    final DynamicActionMetadata dynamicActionMetadata = target.request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(parameters, MediaType.APPLICATION_JSON), DynamicActionMetadata.class);

    final Map<String, List<DynamicActionMetadata.ActionPropertySuggestion>> actionPropertySuggestions = dynamicActionMetadata
            .properties();
    actionPropertySuggestions.forEach((k, vals) -> enriched.replaceConfigurationProperty(k, b -> b.addAllEnum(
            vals.stream().map(s -> ConfigurationProperty.PropertyValue.Builder.from(s))::iterator)));

    //Setting the defaultValue as suggested by the metadata
    for (Entry<String, List<ActionPropertySuggestion>> suggestions : actionPropertySuggestions.entrySet()) {
        if (suggestions.getValue().size() == 1) {
            for (DynamicActionMetadata.ActionPropertySuggestion suggestion : suggestions.getValue()) {
                enriched.replaceConfigurationProperty(suggestion.displayValue(),
                        v -> v.defaultValue(suggestion.value()));
            }
        }
    }

    final Object input = dynamicActionMetadata.inputSchema();
    if (shouldEnrichDataShape(defaultDefinition.getInputDataShape(), input)) {
        enriched.inputDataShape(new DataShape.Builder().type(typeFrom(input)).kind("json-schema")
                .specification(specificationFrom(input)).build());
    }

    final Object output = dynamicActionMetadata.outputSchema();
    if (shouldEnrichDataShape(defaultDefinition.getOutputDataShape(), output)) {
        enriched.outputDataShape(new DataShape.Builder().type(typeFrom(output)).kind("json-schema")
                .specification(specificationFrom(output)).build());
    }

    return enriched.build();
}

From source file:org.onosproject.bmv2.demo.app.wcmp.WcmpFabricApp.java

@Override
public List<FlowRule> generateLeafRules(DeviceId deviceId, Host srcHost, Collection<Host> dstHosts,
        Collection<DeviceId> availableSpines, Topology topo) throws FlowRuleGeneratorException {

    Set<PortNumber> hostPortNumbers = Sets.newHashSet();
    Set<PortNumber> fabricPortNumbers = Sets.newHashSet();
    deviceService.getPorts(deviceId)//from ww  w. j  av  a 2  s  .c  o  m
            .forEach(p -> (isFabricPort(p, topo) ? fabricPortNumbers : hostPortNumbers).add(p.number()));

    if (hostPortNumbers.size() != 1 || fabricPortNumbers.size() == 0) {
        log.error("Leaf switch has invalid port configuration: hostPorts={}, fabricPorts={}",
                hostPortNumbers.size(), fabricPortNumbers.size());
        throw new FlowRuleGeneratorException();
    }
    PortNumber hostPort = hostPortNumbers.iterator().next();

    TopologyGraph graph = topologyService.getGraph(topo);
    // Map key: spine device id, value: leaf switch ports which connect to spine in the key.
    Map<DeviceId, Set<PortNumber>> spineToPortsMap = Maps.newHashMap();
    graph.getEdgesFrom(new DefaultTopologyVertex(deviceId)).forEach(edge -> {
        spineToPortsMap.putIfAbsent(edge.dst().deviceId(), Sets.newHashSet());
        spineToPortsMap.get(edge.dst().deviceId()).add(edge.link().src().port());
    });

    double baseWeight = 1d / spineToPortsMap.size();

    int numSinglePorts = (int) spineToPortsMap.values().stream().filter(s -> s.size() == 1).count();
    int numMultiPorts = spineToPortsMap.size() - numSinglePorts;

    // Reduce weight portion assigned to multi-ports to mitigate flow assignment imbalance (measured empirically).
    double multiPortBaseWeight = baseWeight * MULTI_PORT_WEIGHT_COEFFICIENT;
    double excess = (baseWeight - multiPortBaseWeight) * numMultiPorts;
    double singlePortBaseWeight = baseWeight + (excess / numSinglePorts);

    Map<PortNumber, Double> weighedPortNumbers = Maps.newHashMap();
    spineToPortsMap.forEach((did, portSet) -> {
        double base = (portSet.size() == 1) ? singlePortBaseWeight : multiPortBaseWeight;
        double weight = base / portSet.size();
        portSet.forEach(portNumber -> weighedPortNumbers.put(portNumber, weight));
    });

    List<FlowRule> rules = Lists.newArrayList();

    Pair<ExtensionTreatment, List<FlowRule>> result = provisionWcmpTreatment(deviceId, weighedPortNumbers);
    ExtensionTreatment wcmpTreatment = result.getLeft();
    rules.addAll(result.getRight());

    // From src host to dst hosts, WCMP to all fabric ports.
    for (Host dstHost : dstHosts) {
        FlowRule rule = flowRuleBuilder(deviceId, TABLE0)
                .withSelector(DefaultTrafficSelector.builder().matchInPort(hostPort)
                        .matchEthType(IPV4.ethType().toShort()).matchEthSrc(srcHost.mac())
                        .matchEthDst(dstHost.mac()).build())
                .withTreatment(DefaultTrafficTreatment.builder().extension(wcmpTreatment, deviceId).build())
                .build();
        rules.add(rule);
    }

    // From fabric ports to src host.
    for (PortNumber port : fabricPortNumbers) {
        FlowRule rule = flowRuleBuilder(deviceId, TABLE0)
                .withSelector(DefaultTrafficSelector.builder().matchInPort(port)
                        .matchEthType(IPV4.ethType().toShort()).matchEthDst(srcHost.mac()).build())
                .withTreatment(DefaultTrafficTreatment.builder().setOutput(hostPort).build()).build();
        rules.add(rule);
    }

    return rules;
}

From source file:org.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

@Override
public Map<String, InfluxMetric> metricsByNodeId(NodeId nodeId) {
    Map<NodeId, Set<String>> nameMap = allMetricNames();
    Map<String, InfluxMetric> map = Maps.newHashMap();

    nameMap.get(nodeId).forEach(metricName -> {
        InfluxMetric value = metric(nodeId, metricName);
        if (value != null) {
            map.putIfAbsent(metricName, value);
        }//  w ww. jav  a2 s . co  m
    });

    return map;
}

From source file:com.github.pjungermann.config.types.json.JsonConverter.java

@SuppressWarnings("unchecked")
protected void addHierarchicalEntry(@NotNull final Map<String, Object> map, @NotNull final String key,
        final Object value) {
    final int index = key.indexOf(keyBuilder.getSeparator());
    if (index == -1) {
        map.put(key, value);//from w  w w .j a  v a2  s .  com
        return;
    }

    final String rootKey = key.substring(0, index);
    if (!map.containsKey(rootKey)) {
        map.putIfAbsent(rootKey, new HashMap<>());
    }

    addHierarchicalEntry((Map<String, Object>) map.get(rootKey), key.substring(index + 1), value);
}

From source file:com.thoughtworks.go.remote.work.ArtifactsPublisher.java

public Map<String, Map<ArtifactStore, List<ArtifactPlan>>> artifactStoresToPlugin(
        List<ArtifactPlan> artifactPlans) {
    final Map<String, Map<ArtifactStore, List<ArtifactPlan>>> artifactStoresToPlugin = new HashMap<>();
    final Map<String, List<ArtifactPlan>> artifactPlansToArtifactStore = artifactPlansToArtifactStore(
            artifactPlans);//from w w w . j  a v  a2s.  c o  m

    for (ArtifactStore artifactStore : artifactStores) {
        final String pluginId = artifactStore.getPluginId();
        artifactStoresToPlugin.putIfAbsent(pluginId, new HashMap<>());
        artifactStoresToPlugin.get(pluginId).put(artifactStore,
                artifactPlansToArtifactStore.get(artifactStore.getId()));
    }

    return artifactStoresToPlugin;
}

From source file:org.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

@Override
public Map<String, List<InfluxMetric>> metricsByNodeId(NodeId nodeId, int period, TimeUnit unit) {
    Map<NodeId, Set<String>> nameMap = allMetricNames();
    Map<String, List<InfluxMetric>> map = Maps.newHashMap();

    nameMap.get(nodeId).forEach(metricName -> {
        List<InfluxMetric> value = metric(nodeId, metricName, period, unit);
        if (value != null) {
            map.putIfAbsent(metricName, value);
        }/*from w  ww .j  av  a 2 s .c om*/
    });

    return map;
}

From source file:org.springframework.cloud.dataflow.server.service.impl.AppDeploymentRequestCreator.java

/**
 * Return a new app definition where definition-time and deploy-time properties have been
 * merged and short form parameters have been expanded to their long form (amongst the
 * whitelisted supported properties of the app) if applicable.
 *///from  ww w  .jav a2s .c om
/* default */ AppDefinition mergeAndExpandAppProperties(StreamAppDefinition original, Resource metadataResource,
        Map<String, String> appDeployTimeProperties) {
    Map<String, String> merged = new HashMap<>(original.getProperties());
    merged.putAll(appDeployTimeProperties);
    merged = this.whitelistProperties.qualifyProperties(merged, metadataResource);

    merged.putIfAbsent(StreamPropertyKeys.METRICS_PROPERTIES,
            "spring.application.name,spring.application.index,"
                    + "spring.cloud.application.*,spring.cloud.dataflow.*");
    merged.putIfAbsent(StreamPropertyKeys.METRICS_TRIGGER_INCLUDES, "integration**");

    return new AppDefinition(original.getName(), merged);
}

From source file:io.klerch.alexa.state.handler.AlexaSessionStateHandler.java

/**
 * {@inheritDoc}// w w  w .  j  a v a2  s .  c  o  m
 */
@Override
public Map<String, AlexaStateObject> readValues(Map<String, AlexaScope> idsInScope) throws AlexaStateException {
    final Map<String, AlexaStateObject> stateObjectMap = new HashMap<>();
    idsInScope.forEach((k, v) -> {
        // do for session-scoped keys only
        if (existsInSession(k, v)) {
            // read from session and wrap value in state object
            stateObjectMap.putIfAbsent(k, new AlexaStateObject(k, session.getAttribute(k), v));
        }
    });
    return stateObjectMap;
}

From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java

/**
 * Find the virtual machines matching to the given criteria. Look into virtual machine name and identifier.
 *
 * @param node/*from  w  ww  .j  ava  2s  .  co  m*/
 *            the node to be tested with given parameters.
 * @param criteria
 *            the search criteria. Case is insensitive.
 * @param uriInfo
 *            Additional subscription parameters.
 * @return virtual machines.
 * @throws Exception
 *             When AWS content cannot be read.
 */
@GET
@Path("{node:service:.+}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<AwsVm> findAllByNameOrId(@PathParam("node") final String node,
        @PathParam("criteria") final String criteria, @Context final UriInfo uriInfo) throws Exception {
    // Check the node exists
    if (nodeRepository.findOneVisible(node, securityHelper.getLogin()) == null) {
        return Collections.emptyList();
    }

    // Merge the node parameters to the node ones
    final Map<String, String> parameters = new HashMap<>(pvResource.getNodeParameters(node));
    uriInfo.getQueryParameters().forEach((p, v) -> parameters.putIfAbsent(p, v.get(0)));

    // Get all VMs and then filter by its name or id
    // Note : AWS does not support RegExp on tag
    return this.getDescribeInstances(parameters, "", this::toVm).stream()
            .filter(vm -> StringUtils.containsIgnoreCase(vm.getName(), criteria)
                    || StringUtils.containsIgnoreCase(vm.getId(), criteria))
            .sorted().collect(Collectors.toList());
}