Esempio n. 1
1
 public <K, T> Dict putToMap(Prop<? extends Map<String, T>> key, K tok, T value) {
   if (key.toCannon().autoConstructor != null) {
     Map<K, T> c =
         (Map<K, T>) dictionary.computeIfAbsent(key, (k) -> key.toCannon().autoConstructor.get());
     c.put(tok, value);
     return this;
   } else {
     Map<K, T> c = (Map<K, T>) dictionary.computeIfAbsent(key, (k) -> new IdempotencyMap<T>(null));
     c.put(tok, value);
     return this;
   }
 }
Esempio n. 2
1
  public <T> Dict putToList(Prop<? extends Collection<T>> key, T value) {

    if (key.toCannon().autoConstructor != null) {
      Collection<T> c =
          (Collection<T>)
              dictionary.computeIfAbsent(key, (k) -> key.toCannon().autoConstructor.get());
      c.add(value);
      return this;
    } else {
      Collection<T> c = (Collection<T>) dictionary.computeIfAbsent(key, (k) -> new ArrayList<T>());
      c.add(value);
      return this;
    }
  }
Esempio n. 3
1
  public <T> Dict putToListMap(Prop<? extends LinkedHashMapAndArrayList<T>> key, T value) {

    if (key.toCannon().autoConstructor != null) {
      LinkedHashMapAndArrayList<T> c =
          (LinkedHashMapAndArrayList<T>)
              dictionary.computeIfAbsent(key, (k) -> key.toCannon().autoConstructor.get());
      c.add(value);
      return this;
    } else {
      LinkedHashMapAndArrayList<T> c =
          (LinkedHashMapAndArrayList<T>) dictionary.computeIfAbsent(key, (k) -> new ArrayList<T>());
      c.add(value);
      return this;
    }
  }
Esempio n. 4
1
    public static <T> Prop<T> cannonicalize(Prop<T> p) {
      Prop<T> prop = cannon.computeIfAbsent(p.name, x -> p);
      if (p.isCannon() && !prop.isCannon()) {
        cannon.put(p.name, p);
        prop = p;
      } else if (p.isCannon() && prop.isCannon() && p != prop) {
        // should be an Error?
        System.err.println(" WARNING: two competing canonical definitions of a Prop <" + p + ">");
        if (p.typeInformation != null && prop.typeInformation == null) {
          cannon.put(p.name, p);
          prop = p;
        } else if (p.typeInformation == null && prop.typeInformation != null) {

        } else if (p.typeInformation != null && prop.typeInformation != null) {
          if (!Conversions.typeInformationEquals(p.typeInformation, prop.typeInformation)) {
            System.err.println(
                " ERROR: the two competing canonical definitions of "
                    + p
                    + " have different type information");
            throw new IllegalArgumentException(
                p.typeInformation + " " + prop.typeInformation + " " + p + " " + prop);
          }
        }
      }
      prop.setCannon();
      return prop;
    }
Esempio n. 5
1
  public <T> T computeIfAbsent(Prop<T> k, Function<Prop<T>, T> def) {

    // this is redundant, but it makes sure we register a 'get'
    T t = get(k);
    if (t != null) return t;

    return (T) dictionary.computeIfAbsent(k, (x) -> def.apply(k));
  }
Esempio n. 6
1
  @SuppressWarnings("unchecked")
  public <T> T getOrConstruct(Prop<T> key) {

    Prop<T> cc = key.findCannon();
    if (cc != null && cc.autoConstructor != null) {
      return (T) dictionary.computeIfAbsent(key, k -> cc.autoConstructor.get());
    }
    return get(key);
  }
Esempio n. 7
0
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    for (int i = 0; i < 10; i++) {
      map.putIfAbsent(i, "val" + i);
    }
    map.forEach((id, val) -> System.out.println(val));

    map.computeIfPresent(3, (num, val) -> val + num);
    System.out.println(map.get(3)); // val33

    map.computeIfPresent(9, (num, val) -> null);
    System.out.println(map.containsKey(9)); // false

    map.computeIfAbsent(23, num -> "val" + num);
    System.out.println(map.containsKey(23)); // true

    map.computeIfAbsent(3, num -> "bam");
    System.out.println(map.get(3)); // val33

    map.remove(3, "val3");
    System.out.println(map.get(3)); // val33

    map.remove(3, "val33");
    System.out.println(map.get(3)); // null

    System.out.println(map.getOrDefault(42, "not found")); // not found

    map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
    System.out.println(map.get(9)); // val9

    map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
    System.out.println(map.get(9)); // val9concat
  }
  @Test
  public void functionTest() {
    Map<Integer, String> map = Maps.newHashMap();
    for (int i = 0; i < 10; i++) {
      map.putIfAbsent(i, "val" + i);
    }

    log.info("key 3 value:'{}'", map.get(3));

    log.info("map computeIfPresent:'{}'", map.computeIfPresent(9, (num, val) -> null));

    log.info("key 9 containsKey:'{}'", map.containsKey(9));

    log.info("computeIfAbsent 23 :'{}'", map.computeIfAbsent(23, num -> "val" + num));

    log.info("map.containsKey(23):'{}'", map.containsKey(23));

    log.info("computeIfAbsent 3:'{}'", map.computeIfAbsent(3, num -> "bam"));
    log.info("get 3:'{}'", map.get(3));

    map.remove(3, "val");

    log.info("remove get 3:'{}'", map.get(3));

    map.remove(3, "val3");

    log.info("remove get 3:'{}'", map.get(3));

    log.info("getDefault:'{}'", map.getOrDefault(43, "not found"));

    log.info("merge:'{}'", map.merge(9, "val9", (value, newValue) -> value.concat(newValue)));

    log.info("merge:'{}'", map.merge(9, "count", (value, newValue) -> value.concat(newValue)));
  }
 @Test
 public void computeInAbsentTest() {
   // adds an element with the value computed using the Key.
   Map<Integer, String> intMap = new HashMap<>();
   intMap.put(1, "Value1");
   intMap.put(2, "Value2");
   intMap.computeIfAbsent(3, e -> "" + "Value".length());
   intMap.computeIfAbsent(3, e -> "" + "Value1".length()); // ommit
   intMap.computeIfAbsent(5, e -> "" + "Value1".length());
   intMap.keySet().stream().forEach(s -> log.info("compute {} {}", s, intMap.get(s)));
 }
Esempio n. 10
0
 public static TableClassInfo of(AnnotationInfo columnAnnotationInfo) {
   Preconditions.checkArgument(
       columnAnnotationInfo.hasAnnotation(ColumnAnnotation.class)
           || columnAnnotationInfo.hasAnnotation(ForeignKeyAnnotation.class));
   TypeInfo tableTypeInfo = columnAnnotationInfo.enclosingTypeInfo().get();
   return qualifiedNameMap.computeIfAbsent(
       tableTypeInfo.qualifiedName(),
       qname -> {
         return TableClassInfo.builder()
             .tableName(TableNameAnnotationInfo.of(tableTypeInfo))
             .tableClassName(
                 columnAnnotationInfo
                     .enclosingSimpleTypeInfo()
                     .map(SimpleTypeInfo::className)
                     .get())
             .columnAnnotationClassList(
                 tableTypeInfo
                     .annotationInfo(ColumnAnnotationClassArray.class)
                     .flatMap(ann -> ann.simpleTypeInfoArrayValue("value"))
                     .get())
             .insertClassName(
                 tableTypeInfo
                     .annotationInfo(InsertClass.class)
                     .flatMap(ann -> ann.simpleTypeInfoValue("value"))
                     .map(SimpleTypeInfo::className)
                     .get())
             .primaryKeyList(
                 tableTypeInfo
                     .annotationInfo(PrimaryKeyClassArray.class)
                     .flatMap(ann -> ann.simpleTypeInfoArrayValue("value"))
                     .orElse(ImmutableList.of()))
             .build();
       });
 }
Esempio n. 11
0
  // -------------------------------------------------------------------------
  // loads a single fixing series CSV file
  private static ImmutableMap<ObservableId, LocalDateDoubleTimeSeries> parseSingle(
      CharSource resource) {
    Map<ObservableId, LocalDateDoubleTimeSeriesBuilder> builders = new HashMap<>();
    try {
      CsvFile csv = CsvFile.of(resource, true);
      for (CsvRow row : csv.rows()) {
        String referenceStr = row.getField(REFERENCE_FIELD);
        String dateStr = row.getField(DATE_FIELD);
        String valueStr = row.getField(VALUE_FIELD);

        Index index = LoaderUtils.findIndex(referenceStr);
        ObservableId id = IndexQuoteId.of(index);
        LocalDate date = LocalDate.parse(dateStr);
        double value = Double.parseDouble(valueStr);

        LocalDateDoubleTimeSeriesBuilder builder =
            builders.computeIfAbsent(id, k -> LocalDateDoubleTimeSeries.builder());
        builder.put(date, value);
      }
    } catch (RuntimeException ex) {
      throw new IllegalArgumentException(
          Messages.format("Error processing resource as CSV file: {}", resource), ex);
    }
    return MapStream.of(builders).mapValues(builder -> builder.build()).toMap();
  }
  private ItemIdValue processGDMResourceNode(final ResourceNode resourceNode) {

    final String resourceURI = resourceNode.getUri();

    return gdmResourceURIWikidataItemMap.computeIfAbsent(
        resourceURI,
        resourceURI1 -> {
          try {

            final List<MonolingualTextValue> labels = generateLabels(resourceURI);
            final List<MonolingualTextValue> descriptions = generateLabels(resourceURI);
            final List<MonolingualTextValue> aliases = new ArrayList<>();
            final List<StatementGroup> statementGroups = new ArrayList<>();
            final Map<String, SiteLink> siteLinkMap = new HashMap<>();

            // note: list of descriptions cannot be null
            // note: list of aliases cannot be null
            // note: list of statement groups cannot be null
            final ItemDocument wikidataItem =
                Datamodel.makeItemDocument(
                    null, labels, descriptions, aliases, statementGroups, siteLinkMap);

            return createWikidataItem(resourceURI1, wikidataItem);
          } catch (final WikidataImporterException e) {

            throw WikidataImporterError.wrap(e);
          }
        });
  }
Esempio n. 13
0
 @Nullable
 private String getOrCreateUrlForCommit(@Nonnull Commit commit) {
   if (commit.url == null) {
     return null;
   } else {
     return urlMapping.computeIfAbsent(commit.url, url -> generateAcmeCorpUrl(commit));
   }
 }
Esempio n. 14
0
 private String getOrCreateProject(@Nullable String projectName) {
   if (projectName == null) {
     return null;
   } else {
     return projectNameMapping.computeIfAbsent(
         projectName, name -> filenameGenerator.generateUniqueProjectName());
   }
 }
Esempio n. 15
0
 private Identity getOrCreateIdentity(@Nullable Commit.Identity identityToAnonymize) {
   if (identityToAnonymize == null) {
     return null;
   } else {
     return identityMapping.computeIfAbsent(
         identityToAnonymize, identity -> generator.generateIdentity());
   }
 }
Esempio n. 16
0
  public void serve(App app, HttpRequest request, HttpResponse response) {
    Path resourcePath;
    ZonedDateTime lastModifiedDate;
    try {
      if (request.isComponentStaticResourceRequest()) {
        // /public/components/...
        resourcePath = resolveResourceInComponent(app, request.getUriWithoutContextPath());
      } else if (request.isThemeStaticResourceRequest()) {
        // /public/themes/...
        resourcePath = resolveResourceInTheme(app, request.getUriWithoutContextPath());
      } else {
        // /public/...
        response.setContent(
            STATUS_BAD_REQUEST, "Invalid static resource URI '" + request.getUri() + "'.");
        return;
      }
      lastModifiedDate =
          resourcesLastModifiedDates.computeIfAbsent(resourcePath, this::getLastModifiedDate);
    } catch (IllegalArgumentException e) {
      // Invalid/incorrect static resource URI.
      response.setContent(STATUS_BAD_REQUEST, e.getMessage());
      return;
    } catch (ResourceNotFoundException e) {
      // Static resource file does not exists.
      response.setContent(
          STATUS_NOT_FOUND, "Requested resource '" + request.getUri() + "' does not exists.");
      return;
    } catch (Exception e) {
      // FileOperationException, IOException or any other Exception that might occur.
      LOGGER.error(
          "An error occurred when manipulating paths for static resource request '{}'.",
          request,
          e);
      response.setContent(
          STATUS_INTERNAL_SERVER_ERROR,
          "A server occurred while serving for static resource request '" + request + "'.");
      return;
    }

    if (lastModifiedDate == null) {
      /* Since we failed to read last modified date of 'resourcePath' file, we cannot set cache headers.
      Therefore just serve the file without any cache headers. */
      response.setStatus(STATUS_OK);
      response.setContent(resourcePath, getContentType(request, resourcePath));
      return;
    }
    ZonedDateTime ifModifiedSinceDate = getIfModifiedSinceDate(request);
    if ((ifModifiedSinceDate != null)
        && Duration.between(ifModifiedSinceDate, lastModifiedDate).isZero()) {
      // Resource is NOT modified since the last serve.
      response.setStatus(STATUS_NOT_MODIFIED);
      return;
    }

    setCacheHeaders(lastModifiedDate, response);
    response.setStatus(STATUS_OK);
    response.setContent(resourcePath, getContentType(request, resourcePath));
  }
 private NetworkTypes(final List<NodeInfo> nodeInfos) {
   final Map<String, AtomicInteger> transportTypes = new HashMap<>();
   final Map<String, AtomicInteger> httpTypes = new HashMap<>();
   for (final NodeInfo nodeInfo : nodeInfos) {
     final Settings settings = nodeInfo.getSettings();
     final String transportType =
         settings.get(
             NetworkModule.TRANSPORT_TYPE_KEY,
             NetworkModule.TRANSPORT_DEFAULT_TYPE_SETTING.get(settings));
     final String httpType =
         settings.get(
             NetworkModule.HTTP_TYPE_KEY, NetworkModule.HTTP_DEFAULT_TYPE_SETTING.get(settings));
     transportTypes.computeIfAbsent(transportType, k -> new AtomicInteger()).incrementAndGet();
     httpTypes.computeIfAbsent(httpType, k -> new AtomicInteger()).incrementAndGet();
   }
   this.transportTypes = Collections.unmodifiableMap(transportTypes);
   this.httpTypes = Collections.unmodifiableMap(httpTypes);
 }
  private void onElementAction(String action, NodeElement element) {
    myElementUpdate
        .computeIfAbsent(element, k -> new ElementEntry(element))
        .onElementAction(action);

    if (myElementUpdateHook != null) {
      myElementUpdateHook.onElementAction(action, element);
    }
  }
 synchronized RecoverySourceHandler addNewRecovery(
     StartRecoveryRequest request, String targetAllocationId, IndexShard shard) {
   final ShardRecoveryContext shardContext =
       ongoingRecoveries.computeIfAbsent(shard, s -> new ShardRecoveryContext());
   RecoverySourceHandler handler =
       shardContext.addNewRecovery(request, targetAllocationId, shard);
   shard.recoveryStats().incCurrentAsSource();
   return handler;
 }
Esempio n. 20
0
  @Override
  public Client filter(Client client) {
    ReadOnlyClient pseudoClient = new ReadOnlyClient(client);

    Map<Account, ReadOnlyAccount> account2pseudo = new HashMap<>();
    Set<Security> usedSecurities = new HashSet<>();

    for (Portfolio portfolio : portfolios) {
      ReadOnlyAccount pseudoAccount =
          account2pseudo.computeIfAbsent(
              portfolio.getReferenceAccount(),
              a -> {
                ReadOnlyAccount pa = new ReadOnlyAccount(a);
                pseudoClient.internalAddAccount(pa);
                return pa;
              });

      ReadOnlyPortfolio pseudoPortfolio = new ReadOnlyPortfolio(portfolio);
      pseudoPortfolio.setReferenceAccount(pseudoAccount);
      pseudoClient.internalAddPortfolio(pseudoPortfolio);

      adaptPortfolioTransactions(portfolio, pseudoPortfolio, usedSecurities);

      if (!accounts.contains(portfolio.getReferenceAccount()))
        collectDividends(portfolio, pseudoAccount, usedSecurities);
    }

    for (Account account : accounts) {
      ReadOnlyAccount pseudoAccount =
          account2pseudo.computeIfAbsent(
              account,
              a -> {
                ReadOnlyAccount pa = new ReadOnlyAccount(a);
                pseudoClient.internalAddAccount(pa);
                return pa;
              });

      adaptAccountTransactions(account, pseudoAccount, usedSecurities);
    }

    for (Security security : usedSecurities) pseudoClient.internalAddSecurity(security);

    return pseudoClient;
  }
Esempio n. 21
0
  @Nullable
  @Contract("null -> null; !null -> !null")
  public ThreadReferenceProxyImpl getThreadReferenceProxy(@Nullable ThreadReference thread) {
    DebuggerManagerThreadImpl.assertIsManagerThread();
    if (thread == null) {
      return null;
    }

    return myAllThreads.computeIfAbsent(thread, t -> new ThreadReferenceProxyImpl(this, t));
  }
Esempio n. 22
0
 @Override
 public IdBlock getIdBlock(String topic) {
   AtomicCounter counter =
       topicCounters.computeIfAbsent(
           topic, name -> storageService.atomicCounterBuilder().withName(name).build());
   Long blockBase =
       Tools.retryable(counter::getAndAdd, StorageException.class, MAX_TRIES, RETRY_DELAY_MS)
           .apply(DEFAULT_BLOCK_SIZE);
   return new IdBlock(blockBase, DEFAULT_BLOCK_SIZE);
 }
Esempio n. 23
0
 /**
  * Gets the {@link Room room} with the given ID.
  *
  * @param id The ID.
  * @return The room, or null if an error occurred.
  */
 public Room getRoom(String id) {
   try {
     if (rooms.containsKey(id)) return rooms.get(id);
     JSONObject o = requests().get("/rooms/" + id).asJson().getBody().getObject();
     return rooms.computeIfAbsent(id, i -> new RoomImpl(this, o));
   } catch (UnirestException e) {
     e.printStackTrace();
     return null;
   }
 }
 private void queueUpdate(UpdateEntry<K, V> event, Collection<NodeId> peers) {
   if (peers == null) {
     // we have no friends :(
     return;
   }
   peers.forEach(
       node ->
           senderPending
               .computeIfAbsent(node, unusedKey -> new EventAccumulator(node))
               .add(event));
 }
 public void accept(Stream<T> classes) {
   classes
       .collect(groupingBy(identity(), counting()))
       . //
       forEach(
           (clazz, count) -> {
             types
                 .computeIfAbsent(clazz, c -> new IntSummaryStatistics())
                 .accept(count.intValue());
           });
 }
Esempio n. 26
0
  public Matcher getMatcher(RegularExpression regex) {

    if (regex == Epsilon.getInstance()) return epsilonMatcher();

    if (regex instanceof Terminal) return getMatcher(((Terminal) regex).getRegularExpression());

    if (regex instanceof Character) return characterMatcher((Character) regex);

    if (regex instanceof CharacterRange) return characterRangeMatcher((CharacterRange) regex);

    return cache.computeIfAbsent(regex, DFAMatcher::new);
  }
Esempio n. 27
0
  public Matcher getBackwardsMatcher(RegularExpression regex) {

    if (regex instanceof Terminal)
      return getBackwardsMatcher(((Terminal) regex).getRegularExpression());

    if (regex instanceof Character) return characterBackwardsMatcher((Character) regex);

    if (regex instanceof CharacterRange)
      return characterRangeBackwardsMatcher((CharacterRange) regex);

    return cache.computeIfAbsent(regex, DFABackwardsMatcher::new);
  }
Esempio n. 28
0
  @Override
  protected int doHandle(final Request request, final Response response) {
    int result = super.doHandle(request, response);

    Map<String, Object> requestAttributes = request.getAttributes();
    Map<String, Object> responseAttributes = response.getAttributes();
    Series<Header> requestHeaders =
        (Series<Header>)
            requestAttributes.computeIfAbsent(
                "org.restlet.http.headers", key -> new Series<Header>(Header.class));
    Series<Header> responseHeaders =
        (Series<Header>)
            responseAttributes.computeIfAbsent(
                "org.restlet.http.headers", key -> new Series<Header>(Header.class));
    // TODO fix me
    responseHeaders.add("Access-Control-Allow-Origin", requestHeaders.getFirstValue("Origin"));
    responseHeaders.add("Access-Control-Allow-Credentials", "true");
    responseHeaders.add(
        "Access-Control-Allow-Methods", "HEAD, GET, PUT, POST, DELETE, OPTIONS, TRACE");
    responseHeaders.add("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
    return result;
  }
Esempio n. 29
0
  private synchronized void updatePools(Map<MemoryPoolId, Integer> queryCounts) {
    // Update view of cluster memory and pools
    List<MemoryInfo> nodeMemoryInfos =
        nodes
            .values()
            .stream()
            .map(RemoteNodeMemory::getInfo)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(toImmutableList());

    long totalClusterMemory =
        nodeMemoryInfos
            .stream()
            .map(MemoryInfo::getTotalNodeMemory)
            .mapToLong(DataSize::toBytes)
            .sum();
    clusterMemoryBytes.set(totalClusterMemory);

    Set<MemoryPoolId> activePoolIds =
        nodeMemoryInfos
            .stream()
            .flatMap(info -> info.getPools().keySet().stream())
            .collect(toImmutableSet());

    // Make a copy to materialize the set difference
    Set<MemoryPoolId> removedPools = ImmutableSet.copyOf(difference(pools.keySet(), activePoolIds));
    for (MemoryPoolId removed : removedPools) {
      unexport(pools.get(removed));
      pools.remove(removed);
    }
    for (MemoryPoolId id : activePoolIds) {
      ClusterMemoryPool pool =
          pools.computeIfAbsent(
              id,
              poolId -> {
                ClusterMemoryPool newPool = new ClusterMemoryPool(poolId);
                String objectName =
                    ObjectNames.builder(ClusterMemoryPool.class, newPool.getId().toString())
                        .build();
                try {
                  exporter.export(objectName, newPool);
                } catch (JmxException e) {
                  log.error(e, "Error exporting memory pool %s", poolId);
                }
                return newPool;
              });
      pool.update(nodeMemoryInfos, queryCounts.getOrDefault(pool.getId(), 0));
    }
  }
Esempio n. 30
0
 @Nullable
 private String getBranchForProject(@Nullable String projectName, @Nullable String branchName) {
   if (projectName != null && branchName != null) {
     if ("master".equals(branchName)) {
       return "master";
     } else {
       ProjectAndBranch key = new ProjectAndBranch(projectName, branchName);
       return branchNameMapping.computeIfAbsent(
           key, projectAndBranch -> "dev-" + (devBranchNameSuffix++));
     }
   } else {
     return null;
   }
 }