Java Code Examples for java.util.Map#getOrDefault()

The following examples show how to use java.util.Map#getOrDefault() . 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: LuckPerms   File: LPNukkitPlugin.java    License: MIT License 6 votes vote down vote up
public void refreshAutoOp(Player player) {
    if (!getConfiguration().get(ConfigKeys.AUTO_OP)) {
        return;
    }

    User user = getUserManager().getIfLoaded(player.getUniqueId());
    boolean value;

    if (user != null) {
        Map<String, Boolean> permData = user.getCachedData().getPermissionData(this.contextManager.getQueryOptions(player)).getPermissionMap();
        value = permData.getOrDefault("luckperms.autoop", false);
    } else {
        value = false;
    }

    player.setOp(value);
}
 
Example 2
private void aggregate(QueueEvents events) {
  List<RqueueExecutionEvent> queueRqueueExecutionEvents = events.rqueueExecutionEvents;
  RqueueExecutionEvent queueRqueueExecutionEvent = queueRqueueExecutionEvents.get(0);
  Map<LocalDate, TasksStat> localDateTasksStatMap = new HashMap<>();
  for (RqueueExecutionEvent event : queueRqueueExecutionEvents) {
    LocalDate date = DateTimeUtils.localDateFromMilli(queueRqueueExecutionEvent.getTimestamp());
    TasksStat stat = localDateTasksStatMap.getOrDefault(date, new TasksStat());
    aggregate(event, stat);
    localDateTasksStatMap.put(date, stat);
  }
  QueueDetail queueDetail = (QueueDetail) queueRqueueExecutionEvent.getSource();
  String queueStatKey = rqueueConfig.getQueueStatisticsKey(queueDetail.getName());
  QueueStatistics queueStatistics = rqueueQStatsDao.findById(queueStatKey);
  if (queueStatistics == null) {
    queueStatistics = new QueueStatistics(queueStatKey);
  }
  LocalDate today = DateTimeUtils.today();
  queueStatistics.updateTime();
  for (Entry<LocalDate, TasksStat> entry : localDateTasksStatMap.entrySet()) {
    queueStatistics.update(entry.getValue(), entry.getKey().toString());
  }
  queueStatistics.pruneStats(today, rqueueWebConfig.getHistoryDay());
  rqueueQStatsDao.save(queueStatistics);
}
 
Example 3
private int loadCheckpoint() throws IOException {
  int lineNo = 0;
  Map<Integer, String> savedCheckpoints = _task.getCheckpoints();
  String cpString = savedCheckpoints.getOrDefault(PARTITION, null);
  if (cpString != null && !cpString.isEmpty()) {
    // Resume from last saved line number
    lineNo = Integer.parseInt(cpString);

    // Must skip line by line as we can't get the actual file position of the
    // last newline character due to the buffering done by BufferedReader.
    for (int i = 0; i < lineNo; i++) {
      _fileReader.readLine();
    }

    LOG.info("Resumed from line " + lineNo);
  } else {
    LOG.info("Resumed from beginning");
  }

  return lineNo + 1;
}
 
Example 4
private static void addEsQueryFilter(Map<String, Object> mergeDslMap, String dsl)
{
    //-------get query-----
    Map<String, Object> queryDsl;
    try {
        final Map<String, Object> dslMap = MAPPER.readValue(dsl, Map.class);
        queryDsl = (Map<String, Object>) dslMap.getOrDefault("query", dslMap);
    }
    catch (IOException e) {
        throw new PrestoException(ES_DSL_ERROR, e);
    }

    Map<String, Object> query = (Map<String, Object>) mergeDslMap.computeIfAbsent("query", k -> new HashMap<>());
    Map bool = (Map) query.computeIfAbsent("bool", k -> new HashMap<>());
    List must = (List) bool.computeIfAbsent("must", k -> new ArrayList<>());
    //--merge dsl--
    must.add(queryDsl);
}
 
Example 5
Source Project: allure-java   File: AllureJunitPlatform.java    License: Apache License 2.0 6 votes vote down vote up
private void startFixture(final String parentUuid,
                          final String type,
                          final Map<String, String> keyValue) {
    final String uuid = keyValue.get("uuid");
    if (Objects.isNull(uuid)) {
        return;
    }
    final String name = keyValue.getOrDefault("name", "Unknown");
    final FixtureResult result = new FixtureResult().setName(name);

    switch (type) {
        case PREPARE:
            getLifecycle().startPrepareFixture(parentUuid, uuid, result);
            return;
        case TEAR_DOWN:
            getLifecycle().startTearDownFixture(parentUuid, uuid, result);
            return;
        default:
            LOGGER.debug("unknown fixture type {}", type);
            break;
    }

}
 
Example 6
Source Project: pravega   File: BookKeeperLog.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reliably gets the LastAddConfirmed for the WriteLedger
 *
 * @param writeLedger       The WriteLedger to query.
 * @param lastAddsConfirmed A Map of LedgerIds to LastAddConfirmed for each known ledger id. This is used as a cache
 *                          and will be updated if necessary.
 * @return The LastAddConfirmed for the WriteLedger.
 */
@SneakyThrows(DurableDataLogException.class)
private long fetchLastAddConfirmed(WriteLedger writeLedger, Map<Long, Long> lastAddsConfirmed) {
    long ledgerId = writeLedger.ledger.getId();
    long lac = lastAddsConfirmed.getOrDefault(ledgerId, -1L);
    long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "fetchLastAddConfirmed", ledgerId, lac);
    if (lac < 0) {
        if (writeLedger.isRolledOver()) {
            // This close was not due to failure, rather a rollover - hence lastAddConfirmed can be relied upon.
            lac = writeLedger.ledger.getLastAddConfirmed();
        } else {
            // Ledger got closed. This could be due to some external factor, and lastAddConfirmed can't be relied upon.
            // We need to re-open the ledger to get fresh data.
            lac = Ledgers.readLastAddConfirmed(ledgerId, this.bookKeeper, this.config);
        }

        lastAddsConfirmed.put(ledgerId, lac);
        log.info("{}: Fetched actual LastAddConfirmed ({}) for LedgerId {}.", this.traceObjectId, lac, ledgerId);
    }

    LoggerHelpers.traceLeave(log, this.traceObjectId, "fetchLastAddConfirmed", traceId, ledgerId, lac);
    return lac;
}
 
Example 7
Source Project: cloudbreak   File: StackMatrixService.java    License: Apache License 2.0 5 votes vote down vote up
private ClouderaManagerStackDescriptorV4Response getCMStackDescriptor(DefaultCDHInfo stackInfo) {
    Map<String, RepositoryInfo> clouderaManagerRepoInfoEntries = defaultClouderaManagerRepoService.getEntries();
    ClouderaManagerStackDescriptorV4Response stackDescriptorV4 = converterUtil.convert(stackInfo, ClouderaManagerStackDescriptorV4Response.class);
    RepositoryInfo cmInfo = clouderaManagerRepoInfoEntries.getOrDefault(stackDescriptorV4.getMinCM(), new RepositoryInfo());
    ClouderaManagerInfoV4Response cmInfoJson = converterUtil.convert(cmInfo, ClouderaManagerInfoV4Response.class);
    stackDescriptorV4.setClouderaManager(cmInfoJson);
    for (ClouderaManagerProduct parcel : stackInfo.getParcels()) {
        stackDescriptorV4.getProducts().add(ClouderaManagerProductToClouderaManagerProductV4Response.convert(parcel));
    }
    return stackDescriptorV4;
}
 
Example 8
private static @NonNull Map<@NonNull String, @NonNull Object> applyEventStyleProperties(@NonNull Map<@NonNull String, @NonNull Object> styleMap, ITimeEvent event) {
    if (event.isPropertyActive(IFilterProperty.DIMMED)) {
        float opacity = (float) styleMap.getOrDefault(StyleProperties.OPACITY, 1.0f);
        styleMap.put(StyleProperties.OPACITY, opacity / DIMMED_ALPHA_COEFFICIENT);
        styleMap.put(ITimeEventStyleStrings.annotated(), Boolean.TRUE);
    }
    if (event.isPropertyActive(IFilterProperty.BOUND)) {
        styleMap.put(StyleProperties.BORDER_COLOR, HIGHLIGHTED_BOUND_COLOR);
        styleMap.put(StyleProperties.BORDER_WIDTH, HIGHLIGHTED_BOUND_WIDTH);
        styleMap.put(StyleProperties.BORDER_STYLE, BorderStyle.SOLID);
        styleMap.put(ITimeEventStyleStrings.annotated(), Boolean.FALSE);
    }
    return styleMap;
}
 
Example 9
Source Project: vertx-in-action   File: Gateway.java    License: MIT License 5 votes vote down vote up
@Override
public void start(Promise<Void> startPromise) throws Exception {
  Map<String, String> env = System.getenv();
  int httpPort = Integer.parseInt(env.getOrDefault("HTTP_PORT", "8080"));
  String targetDestination = env.getOrDefault("EB_UPDATE_DESTINATION", "heatsensor.updates");

  vertx.eventBus().<JsonObject>consumer(targetDestination, message -> {
    JsonObject json = message.body();
    String id = json.getString("id");
    data.put(id, json);
    logger.info("Received an update from sensor {}", id);
  });

  Router router = Router.router(vertx);
  router.get("/data").handler(this::handleRequest);
  router.get("/health").handler(this::healthCheck);

  router.route("/metrics")
    .handler(ctx -> {
      logger.info("Collecting metrics");
      ctx.next();
    })
    .handler(PrometheusScrapingHandler.create());

  vertx.createHttpServer()
    .requestHandler(router)
    .listen(httpPort, ar -> {
      if (ar.succeeded()) {
        logger.info("HTTP server listening on port {}", httpPort);
        startPromise.complete();
      } else {
        startPromise.fail(ar.cause());
      }
    });
}
 
Example 10
Source Project: Javacord   File: ServerChannelImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Permissionable & DiscordEntity> Permissions getOverwrittenPermissions(T permissionable) {
    Map<Long, Permissions> permissionsMap = Collections.emptyMap();
    if (permissionable instanceof User) {
        permissionsMap = overwrittenUserPermissions;
    } else if (permissionable instanceof Role) {
        permissionsMap = overwrittenRolePermissions;
    }
    return permissionsMap.getOrDefault(permissionable.getId(), PermissionsImpl.EMPTY_PERMISSIONS);
}
 
Example 11
Source Project: lucene-solr   File: Assign.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
private static boolean usePolicyFramework(Optional<DocCollection> collection, SolrCloudManager cloudManager) throws IOException, InterruptedException {
  boolean useLegacyAssignment = true;
  Map<String, Object> clusterProperties = cloudManager.getClusterStateProvider().getClusterProperties();
  if (clusterProperties.containsKey(CollectionAdminParams.DEFAULTS))  {
    Map<String, Object> defaults = (Map<String, Object>) clusterProperties.get(CollectionAdminParams.DEFAULTS);
    Map<String, Object> collectionDefaults = (Map<String, Object>) defaults.getOrDefault(CollectionAdminParams.CLUSTER, Collections.emptyMap());
    useLegacyAssignment = Boolean.parseBoolean(collectionDefaults.getOrDefault(CollectionAdminParams.USE_LEGACY_REPLICA_ASSIGNMENT, "true").toString());
  }

  if (!useLegacyAssignment) {
    // if legacy assignment is not selected then autoscaling is always available through the implicit policy/preferences
    return true;
  }

  // legacy assignment is turned on, which means we must look at the actual autoscaling config
  // to determine whether policy framework can be used or not for this collection

  AutoScalingConfig autoScalingConfig = cloudManager.getDistribStateManager().getAutoScalingConfig();
  // if no autoscaling configuration exists then obviously we cannot use the policy framework
  if (autoScalingConfig.getPolicy().isEmpty()) return false;
  // do custom preferences exist
  if (!autoScalingConfig.getPolicy().hasEmptyPreferences()) return true;
  // does a cluster policy exist
  if (!autoScalingConfig.getPolicy().getClusterPolicy().isEmpty()) return true;
  // finally we check if the current collection has a policy
  return !collection.isPresent() || collection.get().getPolicyName() != null;
}
 
Example 12
public Map<String, Integer> getWidgetsUsage() {
    Map<String, Integer> widgets = new HashMap<>();
    for (User user : users.values()) {
        for (DashBoard dashBoard : user.profile.dashBoards) {
            if (dashBoard.widgets != null) {
                for (Widget widget : dashBoard.widgets) {
                    Integer i = widgets.getOrDefault(widget.getClass().getSimpleName(), 0);
                    widgets.put(widget.getClass().getSimpleName(), ++i);
                }
            }
        }
    }
    return widgets;
}
 
Example 13
Source Project: hugegraph   File: NeighborRankTraverser.java    License: Apache License 2.0 5 votes vote down vote up
private void mergeSameLayerIncrRanks(Set<Id> sameLayerNodesV, double incr,
                                     Map<Id, Double> sameLayerIncrRanks) {
    for (Id node : sameLayerNodesV) {
        double oldRank = sameLayerIncrRanks.getOrDefault(node, 0.0);
        sameLayerIncrRanks.put(node, oldRank + incr);
    }
}
 
Example 14
@Override
public Map<String, Integer> getNumberOfTasksAdded() {
    Map<String, Integer> numberOfTasksAdded = new HashMap<>();
    for (TaskWrapper task : tasksAdded) {
        String queueName = task.getQueueName();

        int oldTaskCount = numberOfTasksAdded.getOrDefault(queueName, 0);
        numberOfTasksAdded.put(queueName, oldTaskCount + 1);
    }
    return numberOfTasksAdded;
}
 
Example 15
/**
 * Looks up the spacing of the specified {@link Port}.
 *
 * @param port
 * 		The port.
 * @return Additional spacing.
 */
public static int lookupPortSpacing(Port port) {
	Operator operator = port.getPorts().getOwner().getOperator();
	PortSpacingWrapper wrapper = (PortSpacingWrapper) operator.getUserData(KEY_PORT_SPACING);
	if (wrapper != null) {
		Map<Port, Integer> spacings = wrapper.get();
		// get spacing or no spacing
		return spacings.getOrDefault(port, 0);
	} else {
		// no spacing data available
		return 0;
	}
}
 
Example 16
@CacheEntryCreated
@CacheEntryModified
public void handle(CacheEntryEvent<String, EventAction> event) {
    String designId = event.getKey();
    EventAction action = event.getValue();
    ActionType type = action.getType();
    String id = action.getId();

    IEditingSessionExt session = sessions.get(designId);
    if (session != null && type != ActionType.CLOSE) {
        switch (type) {
            case SEND_TO_OTHERS:
                session.sendToOthers(action.toBaseOperation(), id);
                return;
            case SEND_TO_LIST:
                session.sendTo(id);
                return;
            case SEND_TO_EXECUTE:
                session.sendTo(action.getOps(), id);
                return;
            case CLOSE:
            case ROLLUP:
            default:
                break;
        }
    }

    // only do rollup once - on the event origin node
    if (type == ActionType.CLOSE && event.isOriginLocal()) {
        Map<String, Integer> map = counterCache.get(designId);
        int count = 0;
        // only count live nodes
        for (Address member : manager.getMembers()) {
            count += map.getOrDefault(member.toString(), 0);
        }
        if (count == 0) {
            try {
                rollup(designId);
            } finally {
                counterCache.remove(designId);
                eventActionCache.remove(designId);
            }
        }
    }
}
 
Example 17
Source Project: kafka-graphs   File: AdamicAdar.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public final void init(Map<String, ?> configs, InitCallback cb) {
    Map<String, Object> c = (Map<String, Object>) configs;
    conversionEnabled = (Boolean) c.getOrDefault(DISTANCE_CONVERSION, DISTANCE_CONVERSION_DEFAULT);
}
 
Example 18
Source Project: pulsar   File: AbstractMetrics.java    License: Apache License 2.0 4 votes vote down vote up
protected void populateAggregationMapWithSum(Map<String, Double> map, String mkey, double value) {
    Double val = map.getOrDefault(mkey, 0.0);
    map.put(mkey, val + value);
}
 
Example 19
public Object get(Map<String, Object> config) {
  return config.getOrDefault(param, defaultValue);
}
 
Example 20
Source Project: api-snippets   File: PagesMigrator.java    License: MIT License 4 votes vote down vote up
private boolean isErrorPageProcessed(String fileId) {
    Map<String, Object> o = (Map<String, Object>) config.get(fileId);
    return (o == null) ? false : (boolean) o.getOrDefault("done", false);
}