Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

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

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:org.openhab.binding.isy.internal.ISYBinding.java

/**
 * Called by the SCR to activate the component with its configuration read from CAS
 * /*from  w  w w  . j a  v a2  s.co  m*/
 * @param bundleContext BundleContext of the Bundle that defines this component
 * @param configuration Configuration properties for this component obtained from the ConfigAdmin service
 */
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    this.bundleContext = bundleContext;

    // the configuration is guaranteed not to be null, because the component definition has the
    // configuration-policy set to require. If set to 'optional' then the configuration may be null

    if (configuration.containsKey("host")) {
        String host = configuration.get("host").toString().trim();
        int port = Integer.valueOf(configuration.getOrDefault("port", 80).toString().trim());
        String username = null;
        String password = null;
        if (configuration.containsKey("username") && configuration.containsKey("password")) {
            username = configuration.get("username").toString().trim();
            password = configuration.get("password").toString().trim();
        }

        isyClient = new ISYClient(host, port, username, password);
        isyClient.subscribe();
    }

    // to override the default refresh interval one has to add a 
    // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
    String refreshIntervalString = (String) configuration.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
    }

    // read further config parameters here ...      
    setProperlyConfigured(isyClient != null);
}

From source file:org.ligoj.app.plugin.vm.azure.VmAzurePluginResource.java

@Override
protected String buildUrl(final Map<String, String> parameters, final String resource) {
    return super.buildUrl(parameters, resource).replace("{vm}", parameters.getOrDefault(PARAMETER_VM, "-"));
}

From source file:org.ambraproject.rhino.rest.controller.ArticleCrudController.java

@Transactional(readOnly = true)
@RequestMapping(value = "/articles/page/{pageNumber}", method = RequestMethod.GET)
public ResponseEntity<?> listDois(@PathVariable(value = "pageNumber") int pageNumber,
        @RequestParam(value = "pageSize", required = false, defaultValue = "100") int pageSize,
        @RequestParam(value = "orderBy", required = false, defaultValue = "newest") String orderBy,
        @RequestParam(value = "since", required = false, defaultValue = "") String sinceRule)
        throws IOException {
    final ArticleCrudService.SortOrder sortOrder = ArticleCrudService.SortOrder
            .valueOf(StringUtils.upperCase(StringUtils.defaultString(orderBy, "newest" /* defaultStr */)));

    final Map<String, LocalDateTime> dateRange = calculateDateRange(sinceRule);
    final Optional<LocalDateTime> fromDate = Optional.ofNullable(dateRange.getOrDefault(FROM_DATE, null));
    final Optional<LocalDateTime> toDate = Optional.ofNullable(dateRange.getOrDefault(TO_DATE, null));
    final Collection<String> articleDois = articleCrudService.getArticleDoisForDateRange(pageNumber, pageSize,
            sortOrder, fromDate, toDate);
    return ServiceResponse.serveView(articleDois).asJsonResponse(entityGson);
}

From source file:org.lightjason.examples.pokemon.CConfiguration.java

/**
 * loads the configuration from a file/*w  ww .  ja  v a2  s. c o m*/
 *
 * @param p_input YAML configuration file
 * @return instance
 *
 * @throws IOException on io errors
 * @throws URISyntaxException on URI syntax error
 */
@SuppressWarnings("unchecked")
public final CConfiguration load(final String p_input) throws IOException, URISyntaxException {
    final URL l_path = CCommon.getResourceURL(p_input);

    // read configuration
    final Map<String, Object> l_data = (Map<String, Object>) new Yaml().load(l_path.openStream());
    m_configurationpath = FilenameUtils.getPath(l_path.toString());

    // get initial values
    m_stacktrace = (boolean) l_data.getOrDefault("stacktrace", false);
    m_threadsleeptime = (int) l_data.getOrDefault("threadsleeptime", 0);
    m_simulationstep = (int) l_data.getOrDefault("steps", Integer.MAX_VALUE);
    if (!(boolean) l_data.getOrDefault("logging", false))
        LogManager.getLogManager().reset();

    m_windowweight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("weight", 800);
    m_windowheight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("height", 600);
    m_zoomspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("zoomspeed", 2) / 100f;
    m_zoomspeed = m_zoomspeed <= 0 ? 0.02f : m_zoomspeed;
    m_dragspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("dragspeed", 100) / 1000f;
    m_dragspeed = m_dragspeed <= 0 ? 1f : m_dragspeed;

    m_screenshot = new ImmutableTriple<>(
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("file", ""),
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("format", ""),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("step", -1));

    // create static objects - static object are needed by the environment
    final List<IItem> l_static = new LinkedList<>();
    this.createStatic((List<Map<String, Object>>) l_data.getOrDefault("element",
            Collections.<Map<String, Object>>emptyList()), l_static);
    m_staticelements = Collections.unmodifiableList(l_static);

    // create environment - static items must be exists
    m_environment = new CEnvironment(
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("rows", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("columns", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("cellsize", -1),
            ERoutingFactory.valueOf(((String) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("routing", "")).trim().toUpperCase())
                    .get(),
            m_staticelements);

    // create executable object list and check number of elements - environment must be exists
    final List<IAgent> l_agents = new LinkedList<>();
    this.createAgent((Map<String, Object>) l_data.getOrDefault("agent", Collections.<String, Object>emptyMap()),
            l_agents, (boolean) l_data.getOrDefault("agentprint", true));
    m_agents = Collections.unmodifiableList(l_agents);

    if (m_agents.size() + m_staticelements.size() > m_environment.column() * m_environment.row() / 2)
        throw new IllegalArgumentException(MessageFormat.format(
                "number of simulation elements are very large [{0}], so the environment size is too small, the environment "
                        + "[{1}x{2}] must define a number of cells which is greater than the two-time number of elements",
                m_agents.size(), m_environment.row(), m_environment.column()));

    // create evaluation
    m_evaluation = new CEvaluation(m_agents.parallelStream());

    // run initialization processes
    m_environment.initialize();

    return this;
}

From source file:org.apache.servicecomb.swagger.engine.SwaggerEnvironment.java

public SwaggerProducer createProducer(Object producerInstance, Class<?> swaggerIntf,
        Map<String, Operation> swaggerOperationMap) {
    Class<?> producerCls = BeanUtils.getImplClassFromBean(producerInstance);
    Map<String, Method> visibleProducerMethods = retrieveVisibleMethods(producerCls);

    SwaggerProducer producer = new SwaggerProducer();
    producer.setProducerCls(producerCls);
    producer.setSwaggerIntf(swaggerIntf);
    for (Method swaggerMethod : swaggerIntf.getMethods()) {
        String methodName = swaggerMethod.getName();
        // producer??swagger?
        Method producerMethod = visibleProducerMethods.getOrDefault(methodName, null);
        if (producerMethod == null) {
            // producer?
            String msg = String.format("swagger method %s not exist in producer %s.", methodName,
                    producerInstance.getClass().getName());
            throw new Error(msg);
        }/* w  ww .  j  a  v a 2 s .  c  om*/

        ArgumentsMapperConfig config = new ArgumentsMapperConfig();
        config.setSwaggerMethod(swaggerMethod);
        config.setProviderMethod(producerMethod);
        config.setSwaggerOperation(swaggerOperationMap.get(methodName));
        config.setSwaggerGeneratorContext(compositeSwaggerGeneratorContext.selectContext(producerCls));

        ProducerArgumentsMapperFactory argumentsMapperFactory = selectProducerArgumentsMapperFactory(config);
        ProducerArgumentsMapper argsMapper = argumentsMapperFactory.createArgumentsMapper(config);
        ProducerResponseMapper responseMapper = producerResponseMapperFactorys.createResponseMapper(
                swaggerMethod.getGenericReturnType(), producerMethod.getGenericReturnType());

        SwaggerProducerOperation op = new SwaggerProducerOperation();
        op.setName(methodName);
        op.setProducerClass(producerCls);
        op.setProducerInstance(producerInstance);
        op.setProducerMethod(producerMethod);
        op.setSwaggerMethod(swaggerMethod);
        op.setArgumentsMapper(argsMapper);
        op.setResponseMapper(responseMapper);

        producer.addOperation(op);
    }

    return producer;
}

From source file:org.eclipse.rdf4j.sail.federation.AbstractFederationConnection.java

private TupleExpr optimize(TupleExpr parsed, Dataset dataset, BindingSet bindings, boolean includeInferred,
        EvaluationStrategy strategy) throws SailException {
    LOGGER.trace("Incoming query model:\n{}", parsed);

    // Clone the tuple expression to allow for more aggressive optimisations
    TupleExpr query = new QueryRoot(parsed.clone());

    new BindingAssigner().optimize(query, dataset, bindings);
    new ConstantOptimizer(strategy).optimize(query, dataset, bindings);
    new CompareOptimizer().optimize(query, dataset, bindings);
    new ConjunctiveConstraintSplitter().optimize(query, dataset, bindings);
    new DisjunctiveConstraintOptimizer().optimize(query, dataset, bindings);
    new SameTermFilterOptimizer().optimize(query, dataset, bindings);
    new QueryModelPruner().optimize(query, dataset, bindings);

    new QueryMultiJoinOptimizer().optimize(query, dataset, bindings);
    // new FilterOptimizer().optimize(query, dataset, bindings);

    // prepare bloom filters
    RepositoryBloomFilter defaultBloomFilter = new AccurateRepositoryBloomFilter(includeInferred);
    Map<Repository, RepositoryBloomFilter> bloomFilters = federation.getBloomFilters();
    java.util.function.Function<Repository, RepositoryBloomFilter> bloomFilterFunction = c -> bloomFilters
            .getOrDefault(c, defaultBloomFilter);

    new EmptyPatternOptimizer(members, bloomFilterFunction).optimize(query, dataset, bindings);
    boolean distinct = federation.isDistinct();
    PrefixHashSet local = federation.getLocalPropertySpace();
    new FederationJoinOptimizer(members, distinct, local, bloomFilterFunction).optimize(query, dataset,
            bindings);//from  w w w .  j av a  2 s. co  m
    new OwnedTupleExprPruner().optimize(query, dataset, bindings);
    new QueryModelPruner().optimize(query, dataset, bindings);
    new QueryMultiJoinOptimizer().optimize(query, dataset, bindings);

    new PrepareOwnedTupleExpr().optimize(query, dataset, bindings);

    LOGGER.trace("Optimized query model:\n{}", query);
    return query;
}

From source file:io.github.retz.scheduler.RetzScheduler.java

@Override
public void resourceOffers(SchedulerDriver driver, List<Protos.Offer> offers) {
    LOG.debug("Resource offer: {}", offers.size());

    // Merge fresh offers from Mesos and offers in stock here, declining duplicate offers
    Stanchion.schedule(() -> {//w w  w . j  av a  2 s .com
        List<Protos.Offer> available = new LinkedList<>();
        synchronized (OFFER_STOCK) {
            // TODO: cleanup this code, optimize for max.stock = 0 case
            Map<String, List<Protos.Offer>> allOffers = new HashMap<>();
            for (Protos.Offer offer : OFFER_STOCK.values()) {
                String key = offer.getSlaveId().getValue();
                List<Protos.Offer> list = allOffers.getOrDefault(key, new LinkedList<>());
                list.add(offer);
                allOffers.put(offer.getSlaveId().getValue(), list);
            }
            for (Protos.Offer offer : offers) {
                String key = offer.getSlaveId().getValue();
                List<Protos.Offer> list = allOffers.getOrDefault(key, new LinkedList<>());
                list.add(offer);
                allOffers.put(offer.getSlaveId().getValue(), list);
            }

            int declined = 0;
            for (Map.Entry<String, List<Protos.Offer>> e : allOffers.entrySet()) {
                if (e.getValue().size() == 1) {
                    available.add(e.getValue().get(0));
                } else {
                    for (Protos.Offer dup : e.getValue()) {
                        driver.declineOffer(dup.getId(), filters);
                        declined += 1;
                    }
                }
            }
            if (conf.fileConfig.getMaxStockSize() > 0) {
                LOG.info("Offer stock renewal: {} offers available ({} declined from stock)", available.size(),
                        declined);
            }
            OFFER_STOCK.clear();
        }

        ResourceQuantity total = new ResourceQuantity();
        for (Protos.Offer offer : available) {
            LOG.debug("offer: {}", offer);
            Resource resource = ResourceConstructor.decode(offer.getResourcesList());
            total.add(resource);
        }

        // TODO: change findFit to consider not only CPU and Memory, but GPUs and Ports
        List<Job> jobs = JobQueue.findFit(PLANNER.orderBy(), total);
        handleAll(available, jobs, driver);
        // As this section is whole serialized by Stanchion, it is safe to do fetching jobs
        // from database and updating database state change from queued => starting at
        // separate transactions
    });
}

From source file:org.apache.storm.utils.Utils.java

/**
 * Get a map of version to classpath from the conf Config.SUPERVISOR_WORKER_VERSION_CLASSPATH_MAP
 * @param conf what to read it out of//from  www.  j  a v a 2 s. c om
 * @param currentCP the current classpath for this version of storm (not included in the conf, but returned by this)
 * @return the map
 */
public static NavigableMap<SimpleVersion, List<String>> getConfiguredClasspathVersions(Map<String, Object> conf,
        List<String> currentCP) {
    TreeMap<SimpleVersion, List<String>> ret = new TreeMap<>();
    Map<String, String> fromConf = (Map<String, String>) conf
            .getOrDefault(Config.SUPERVISOR_WORKER_VERSION_CLASSPATH_MAP, Collections.emptyMap());
    for (Map.Entry<String, String> entry : fromConf.entrySet()) {
        ret.put(new SimpleVersion(entry.getKey()), Arrays.asList(entry.getValue().split(File.pathSeparator)));
    }
    ret.put(VersionInfo.OUR_VERSION, currentCP);
    return ret;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Service.java

default String getResourceYaml(AccountDeploymentDetails<KubernetesAccount> details,
        GenerateService.ResolvedConfiguration resolvedConfiguration) {
    ServiceSettings settings = resolvedConfiguration.getServiceSettings(getService());
    SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings();
    String namespace = getNamespace(settings);

    List<ConfigSource> configSources = stageConfig(details, resolvedConfiguration);

    List<SidecarConfig> sidecarConfigs = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getSidecars().getOrDefault(getService().getServiceName(), new ArrayList<>());

    List<String> initContainers = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getInitContainers().getOrDefault(getService().getServiceName(), new ArrayList<>()).stream()
            .map(o -> {//  ww w .j a  v a 2 s. c  o m
                try {
                    return getObjectMapper().writeValueAsString(o);
                } catch (JsonProcessingException e) {
                    throw new HalException(Problem.Severity.FATAL,
                            "Invalid init container format: " + e.getMessage(), e);
                }
            }).collect(Collectors.toList());

    if (initContainers.isEmpty()) {
        initContainers = null;
    }

    List<String> hostAliases = details.getDeploymentConfiguration().getDeploymentEnvironment().getHostAliases()
            .getOrDefault(getService().getServiceName(), new ArrayList<>()).stream().map(o -> {
                try {
                    return getObjectMapper().writeValueAsString(o);
                } catch (JsonProcessingException e) {
                    throw new HalException(Problem.Severity.FATAL,
                            "Invalid host alias format: " + e.getMessage(), e);
                }
            }).collect(Collectors.toList());

    if (hostAliases.isEmpty()) {
        hostAliases = null;
    }

    configSources.addAll(sidecarConfigs
            .stream().filter(c -> StringUtils.isNotEmpty(c.getMountPath())).map(c -> new ConfigSource()
                    .setMountPath(c.getMountPath()).setId(c.getName()).setType(ConfigSource.Type.emptyDir))
            .collect(Collectors.toList()));

    Map<String, String> env = configSources.stream().map(ConfigSource::getEnv).map(Map::entrySet)
            .flatMap(Collection::stream).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

    List<String> volumes = configSources.stream()
            .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream()
            .map(this::getVolumeYaml).collect(Collectors.toList());

    volumes.addAll(settings.getKubernetes().getVolumes().stream()
            .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream()
            .map(this::getVolumeYaml).collect(Collectors.toList()));

    volumes.addAll(
            sidecarConfigs.stream().map(SidecarConfig::getConfigMapVolumeMounts).flatMap(Collection::stream)
                    .map(c -> new ConfigSource().setMountPath(c.getMountPath()).setId(c.getConfigMapName())
                            .setType(ConfigSource.Type.configMap))
                    .map(this::getVolumeYaml).collect(Collectors.toList()));

    env.putAll(settings.getEnv());

    Integer targetSize = settings.getTargetSize();
    CustomSizing customSizing = details.getDeploymentConfiguration().getDeploymentEnvironment()
            .getCustomSizing();
    if (customSizing != null) {
        Map componentSizing = customSizing.getOrDefault(getService().getServiceName(), new HashMap());
        targetSize = (Integer) componentSizing.getOrDefault("replicas", targetSize);
    }

    String primaryContainer = buildContainer(getService().getCanonicalName(), details, settings, configSources,
            env);
    List<String> sidecarContainers = getSidecars(runtimeSettings).stream().map(SidecarService::getService)
            .map(s -> buildContainer(s.getCanonicalName(), details, runtimeSettings.getServiceSettings(s),
                    configSources, env))
            .collect(Collectors.toList());

    sidecarContainers
            .addAll(sidecarConfigs.stream().map(this::buildCustomSidecar).collect(Collectors.toList()));

    List<String> containers = new ArrayList<>();
    containers.add(primaryContainer);
    containers.addAll(sidecarContainers);

    TemplatedResource podSpec = new JinjaJarResource("/kubernetes/manifests/podSpec.yml")
            .addBinding("containers", containers).addBinding("initContainers", initContainers)
            .addBinding("hostAliases", hostAliases)
            .addBinding("imagePullSecrets", settings.getKubernetes().getImagePullSecrets())
            .addBinding("serviceAccountName", settings.getKubernetes().getServiceAccountName())
            .addBinding("terminationGracePeriodSeconds", terminationGracePeriodSeconds())
            .addBinding("volumes", volumes);

    String version = makeValidLabel(details.getDeploymentConfiguration().getVersion());
    if (version.isEmpty()) {
        version = "unknown";
    }

    return new JinjaJarResource("/kubernetes/manifests/deployment.yml")
            .addBinding("name", getService().getCanonicalName()).addBinding("namespace", namespace)
            .addBinding("replicas", targetSize).addBinding("version", version)
            .addBinding("podAnnotations", settings.getKubernetes().getPodAnnotations())
            .addBinding("podSpec", podSpec.toString()).toString();
}