示例#1
1
  /**
   * Get all the commands available to this CommandManager. This is potentially expensive.
   *
   * @param startsWith Limit to commands that start with this string. "" or "?" will return all
   *     commands.
   * @param allowAdmin Allow admin-only commands?
   * @return Map of available commands.
   */
  public Map<String, Command> getAllCommands(final String startsWith, final boolean allowAdmin) {
    final String sw = startsWith.toLowerCase();
    final boolean allCommands = startsWith.isEmpty() || startsWith.equals("?");

    // First get our own commands
    final Map<String, Command> result =
        knownCommands
            .entrySet()
            .parallelStream()
            .filter(e -> allowAdmin || !e.getValue().isAdminOnly())
            .filter(
                e ->
                    allCommands
                        || e.getKey().startsWith(sw)
                        || e.getKey().startsWith(HIDDEN_PREFIX + sw))
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

    // Now all our submanagers' commands
    for (CommandManager subManager : subManagers) {
      result.putAll(
          subManager
              .getAllCommands(startsWith, allowAdmin)
              .entrySet()
              .parallelStream()
              .filter(entry -> !result.containsKey(entry.getKey()))
              .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
    }

    return result;
  }
 static {
   ID_TO_SUPPLIER =
       unmodifiableMap(
           Arrays.stream(ElasticsearchExceptionHandle.values())
               .collect(Collectors.toMap(e -> e.id, e -> e.constructor)));
   CLASS_TO_ELASTICSEARCH_EXCEPTION_HANDLE =
       unmodifiableMap(
           Arrays.stream(ElasticsearchExceptionHandle.values())
               .collect(Collectors.toMap(e -> e.exceptionClass, e -> e)));
 }
  private Artifact convertArtifact(
      final Target target, final org.eclipse.hawkbit.repository.model.Artifact localArtifact) {
    final Artifact artifact = new Artifact();

    artifact.setUrls(
        artifactUrlHandler
            .getUrls(
                new URLPlaceholder(
                    systemManagement.getTenantMetadata().getTenant(),
                    systemManagement.getTenantMetadata().getId(),
                    target.getControllerId(),
                    target.getId(),
                    new SoftwareData(
                        localArtifact.getSoftwareModule().getId(),
                        localArtifact.getFilename(),
                        localArtifact.getId(),
                        localArtifact.getSha1Hash())),
                ApiType.DMF)
            .stream()
            .collect(Collectors.toMap(e -> e.getProtocol(), e -> e.getRef())));

    artifact.setFilename(localArtifact.getFilename());
    artifact.setHashes(new ArtifactHash(localArtifact.getSha1Hash(), localArtifact.getMd5Hash()));
    artifact.setSize(localArtifact.getSize());
    return artifact;
  }
示例#4
0
  private static Map<Key<?>, Object> checkForInvalidSeedsAndCopy(
      Map<Key<?>, Object> seededObjects) {
    for (Map.Entry<Key<?>, Object> entry : seededObjects.entrySet()) {
      Key<?> key = entry.getKey();
      Object value = entry.getValue();
      if (value == null) {
        throw new IllegalArgumentException("Seeded objects contains null key. Key: " + key);
      }
      Class<?> rawType = key.getTypeLiteral().getRawType();
      if (!rawType.isInstance(value)) {
        if (!(value instanceof Key)) {
          throw new IllegalArgumentException(
              "Seeded object is not instance of key type. " + "Key: " + key + ". Value: " + value);
        }
        Class<?> valueRawType = ((Key) value).getTypeLiteral().getRawType();
        if (!rawType.isAssignableFrom(valueRawType)) {
          throw new IllegalArgumentException(
              "Chained value key type does not extend the key type. "
                  + "Key Key: "
                  + key
                  + ". Value Key: "
                  + value);
        }
      }
    }

    return seededObjects
        .entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  }
示例#5
0
 /**
  * Creates a {@link ResourceBag} from {@link IResourceAggregate}.
  *
  * @param aggregate {@link IResourceAggregate} to convert.
  * @return A {@link ResourceBag} instance.
  */
 public static ResourceBag bagFromAggregate(IResourceAggregate aggregate) {
   return new ResourceBag(
       aggregate
           .getResources()
           .stream()
           .collect(Collectors.toMap(RESOURCE_TO_TYPE, QUANTIFY_RESOURCE)));
 }
示例#6
0
 public static Map filterLoadedValuesLambda(Map<String, String> in) {
   return in.entrySet()
       .stream()
       .collect(
           Collectors.toMap(
               e -> e.getKey().toString(), e -> Float.valueOf(e.getValue().toString())));
 }
示例#7
0
 /**
  * This method does absolutely the same as {@link ServerHandler#queryToMap(String)} one, but uses
  * Java's 8 Stream API and lambda expressions
  *
  * <p>It's just as an example. Bu you can use it
  *
  * @param query the query to be parsed
  * @return the map, containing parsed key-value pairs from request
  */
 private Map<String, String> queryToMap2(String query) {
   return Stream.of(query.split(Constants.REQUEST_PARAMS_DELIMITER))
       .collect(
           Collectors.toMap(
               keyValuePair -> keyValuePair.split("=")[0],
               keyValuePair -> keyValuePair.split("=")[1]));
 }
 @Override
 public Map<TunnelId, ResourceConsumer> getTunnelInfos() {
   return tunnelInfoMap
       .entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().value()));
 }
示例#9
0
文件: To.java 项目: rapidoid/rapidoid
  public static <T, K, U> Collector<T, ?, Map<K, U>> linkedMap(
      Function<? super T, ? extends K> keyMapper,
      Function<? super T, ? extends U> valueMapper,
      BinaryOperator<U> mergeFunction) {

    return Collectors.toMap(keyMapper, valueMapper, mergeFunction, LinkedHashMap::new);
  }
 public void initComponents() {
   competitors =
       DB.getCompetitors(turniej.getId())
           .stream()
           .filter(c -> c.getGoesFinal())
           .collect(Collectors.toList());
   competitorMap = competitors.stream().collect(Collectors.toMap(c -> c.getId(), c -> c));
   singleGames =
       DB.getSingleGames(turniej.getId(), true)
           .stream()
           .filter(
               sg ->
                   competitorMap.containsKey(sg.getCompetitorW())
                       && competitorMap.containsKey(sg.getCompetitorB()))
           .collect(Collectors.toList());
   // filtrowanie powyżej, bo baza zwraca również gry,
   // gdzie grali (dostał się do finałów) vs (nie dostał się)
   // można to naprawić w bazie
   for (Competitor c : competitors) {
     competitorGames.put(c, new LinkedList<>());
   }
   for (SingleGame sg : singleGames) {
     competitorGames.get(competitorMap.get(sg.getCompetitorW())).add(sg);
     competitorGames.get(competitorMap.get(sg.getCompetitorB())).add(sg);
   }
   removeAll();
   table = new JTable(new MyTableModel());
   add(new JScrollPane(table));
   updateTables();
 }
 private Map<Blog, String> getPersonToBlogHomepage(List<Blog> blogsAddedSinceLastNewsletter) {
   return blogsAddedSinceLastNewsletter
       .stream()
       .collect(
           Collectors.toMap(
               Function.identity(), person -> getBlogHomepageFromRss(person.getRss())));
 }
 @SuppressWarnings("unchecked")
 private static <V> Map<String, V> propertiesToMap(final Properties properties) {
   return properties
       .entrySet()
       .stream()
       .collect(Collectors.toMap(e -> (String) e.getKey(), e -> (V) e.getValue()));
 }
  @Override
  public IPersonAttributes getPerson(final String uid) {
    final AttributeResolutionContext attributeResolutionContext = new AttributeResolutionContext();
    attributeResolutionContext.setPrincipal(uid);

    try {
      this.attributeResolver.resolveAttributes(attributeResolutionContext);
      final Map<String, List<Object>> attributes =
          attributeResolutionContext
              .getResolvedIdPAttributes()
              .entrySet()
              .stream()
              .collect(
                  Collectors.toMap(
                      Map.Entry::getKey,
                      p ->
                          p.getValue()
                              .getValues()
                              .stream()
                              .map(IdPAttributeValue::getValue)
                              .collect(Collectors.toList())));

      return new NamedPersonImpl(uid, attributes);
    } catch (final ResolutionException e) {
      throw Throwables.propagate(e);
    }
  }
 public static Map<KLabel, KLabel> collectionFor(Module m) {
   return stream(m.productions())
       .filter(p -> p.att().contains(Attribute.ASSOCIATIVE_KEY))
       .flatMap(
           p -> {
             Set<Tuple2<KLabel, KLabel>> set = new HashSet<>();
             set.add(Tuple2.apply(p.klabel().get(), p.klabel().get()));
             if (p.att().contains(Attribute.UNIT_KEY)) {
               set.add(
                   Tuple2.apply(
                       KLabel(p.att().<String>get(Attribute.UNIT_KEY).get()), p.klabel().get()));
             }
             if (p.att().contains("element")) {
               set.add(
                   Tuple2.apply(KLabel(p.att().<String>get("element").get()), p.klabel().get()));
             }
             if (p.att().contains("wrapElement")) {
               set.add(
                   Tuple2.apply(
                       KLabel(p.att().<String>get("wrapElement").get()), p.klabel().get()));
             }
             return set.stream();
           })
       .distinct()
       .collect(Collectors.toMap(Tuple2::_1, Tuple2::_2));
 }
 /**
  * Updates, creates or deletes UDI events using a given list of UDI Event DTOs.
  *
  * @param period {@link LocalDate} period for which UDI Events will be created/updated/deleted.
  * @param updatedUdiEvents {@link List} of {@link UdiEventDto}.
  */
 public void updateUdiEvents(LocalDate period, List<UdiEventDto> updatedUdiEvents) {
   LOGGER.debug("Updating udi events for period [{}]", period);
   // fetch existing udi events
   Map<String, UdiEvent> udiEventsPerId =
       udiEventRepository
           .findUdiEventsForPeriod(period)
           .stream()
           .collect(Collectors.toMap(UdiEvent::getId, Function.identity()));
   // 1. Update or create UdiEvents
   for (UdiEventDto udiEventDto : updatedUdiEvents) {
     if (!udiEventsPerId.containsKey(udiEventDto.getId())) {
       createUdiEventFromDto(udiEventDto, period);
     } else {
       updateUdiEventFromDto(udiEventsPerId.get(udiEventDto.getId()), udiEventDto);
     }
   }
   // 2. Delete udi events not present in the list anymore
   Set<String> updatedIds =
       updatedUdiEvents.stream().map(UdiEventDto::getId).collect(Collectors.toSet());
   udiEventsPerId
       .entrySet()
       .stream()
       .filter(udiEventPerId -> !updatedIds.contains(udiEventPerId.getKey()))
       .forEach(
           udiEventPerId -> {
             LOGGER.debug("Deleted udi event with id [{}]", udiEventPerId.getKey());
             udiEventRepository.delete(udiEventPerId.getValue());
           });
 }
示例#16
0
 @Override
 public VertexCover<V> getVertexCover(UndirectedGraph<V, E> graph) {
   Map<V, Double> vertexWeightMap =
       graph.vertexSet().stream().collect(Collectors.toMap(Function.identity(), vertex -> 1.0));
   weighted = false;
   return this.getVertexCover(graph, vertexWeightMap);
 }
示例#17
0
  public MetricsAreaFragment getMetricsArea(String title) {
    ////// add property
    By selector =
        By.xpath(
            ".//table[contains(@class, '"
                + PropUtils.get("metrics.container.class")
                + "')][.//h3[text()='"
                + title
                + "']]");
    WebElement element = null;
    try {
      element = getContentRoot().findElement(selector);
    } catch (NoSuchElementException exc) {
      return null;
    }
    MetricsAreaFragment area = Graphene.createPageFragment(MetricsAreaFragment.class, element);

    Map<String, String> metricGrid =
        element
            .findElement(By.className(PropUtils.get("metrics.grid.class")))
            .findElements(By.tagName("tr"))
            .stream()
            .collect(
                Collectors.toMap(
                    e ->
                        e.findElement(By.className(PropUtils.get("metrics.grid.nominal.class")))
                            .getText(),
                    e ->
                        e.findElement(By.className(PropUtils.get("metrics.grid.numerical.class")))
                            .getText()));

    area.setMetricGrid(metricGrid);

    return area;
  }
示例#18
0
  public static Map<EdamUri, Concept> load(String edamPath) throws OWLOntologyCreationException {

    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(edamPath));

    String prefix = ontology.getOntologyID().getOntologyIRI().get().toString();

    return ontology
        .classesInSignature()
        .filter(c -> EdamUri.isEdamUri(c.getIRI().toString(), prefix))
        .collect(
            Collectors.toMap(
                c -> new EdamUri(c.getIRI().toString(), prefix),
                c -> {
                  Concept concept = new Concept();
                  EntitySearcher.getAnnotations(c, ontology)
                      .forEachOrdered(
                          a -> {
                            if (a.getProperty().isLabel())
                              concept.setLabel(a.getValue().asLiteral().get().getLiteral());
                            else if (a.getProperty().isDeprecated()) concept.setObsolete(true);
                            else if (a.getProperty()
                                    .toStringID()
                                    .equals(
                                        "http://www.geneontology.org/formats/oboInOwl#hasExactSynonym")
                                && a.getValue().asLiteral().isPresent())
                              concept.addExactSynonym(a.getValue().asLiteral().get().getLiteral());
                            else if (a.getProperty()
                                    .toStringID()
                                    .equals(
                                        "http://www.geneontology.org/formats/oboInOwl#hasNarrowSynonym")
                                && a.getValue().asLiteral().isPresent())
                              concept.addNarrowSynonym(a.getValue().asLiteral().get().getLiteral());
                            else if (a.getProperty()
                                    .toStringID()
                                    .equals(
                                        "http://www.geneontology.org/formats/oboInOwl#hasBroadSynonym")
                                && a.getValue().asLiteral().isPresent())
                              concept.addBroadSynonym(a.getValue().asLiteral().get().getLiteral());
                            else if (a.getProperty()
                                    .toStringID()
                                    .equals(
                                        "http://www.geneontology.org/formats/oboInOwl#hasDefinition")
                                && a.getValue().asLiteral().isPresent())
                              concept.setDefinition(a.getValue().asLiteral().get().getLiteral());
                            else if (a.getProperty().isComment()
                                && a.getValue().asLiteral().isPresent())
                              concept.setComment(a.getValue().asLiteral().get().getLiteral());
                          });
                  if (concept.getLabel().isEmpty())
                    throw new IllegalStateException(
                        String.format("Label of concept %s is empty", c.getIRI()));
                  return concept;
                },
                (u, v) -> {
                  throw new IllegalStateException(String.format("Duplicate key %s", u));
                },
                LinkedHashMap::new));
  }
示例#19
0
 private Map<Player, Map<Integer, Row>> buildRows() {
   return players
       .stream()
       .collect(
           toMap(
               p -> p,
               p -> range(1, 4).boxed().collect(Collectors.toMap(rid -> rid, rid -> new Row()))));
 }
示例#20
0
  @Override
  public Map<String, OpsNode> getNodesByCode() {
    if (nodesByCode == null)
      nodesByCode =
          preOrderStream().collect(Collectors.toMap(OpsNode::getCode, Function.identity()));

    return Collections.unmodifiableMap(nodesByCode);
  }
 @RequestMapping
 public Object getLanguagesList() {
   return Imcms.getServices()
       .getDocumentLanguages()
       .getAll()
       .stream()
       .collect(Collectors.toMap(DocumentLanguage::getName, DocumentLanguage::getCode));
 }
示例#22
0
 private static Collector<Prediction, ?, Map<DateTime, Prediction>>
     groupByRoundedTimeKeepingNewest() {
   return Collectors.toMap(
       p -> toPredictionResolution(p.timestamp),
       Function.identity(),
       (a, b) -> a.timestamp.isAfter(b.timestamp) ? a : b,
       HashMap::new);
 }
示例#23
0
 /**
  * "key:value"という書式の文字列リストから、マップを生成します。
  *
  * @param list 文字列リスト
  * @return マップ(書式が妥当でないものは含まない)
  */
 public static Map<String, String> toMap(List<String> list) {
   return list.stream() // ListからStreamを生成。
       .filter(Objects::nonNull) // null以外の要素のみ対象とする。
       .map(string -> string.split(":", 2)) // コロンで2分割して、配列に変換する。
       .filter(pair -> pair.length == 2) // 2分割できたもののみ対象とする。
       .collect(
           Collectors.toMap(pair -> pair[0], pair -> pair[1])); // 配列の1つ目をキー、2つ目を値として、Mapに集計する。
 }
示例#24
0
 private Map<String, Integer> getBSSIDLevelMap(Sample sample) {
   return sample
       .getScanResults()
       .stream()
       .collect(
           Collectors.toMap(
               wifiScanResult -> wifiScanResult.BSSID, wifiScanResult -> wifiScanResult.level));
 }
示例#25
0
 private static Map<String, Object> getXenonTestArgs() {
   return System.getProperties()
       .entrySet()
       .stream()
       .filter(e -> e.getKey().toString().startsWith(CommandLineArgumentParser.PROPERTY_PREFIX))
       .filter(e -> !e.getKey().toString().equals(PROP_WRITE_REPORT))
       .collect(Collectors.toMap(e -> e.getKey().toString(), Entry::getValue));
 }
示例#26
0
文件: To.java 项目: rapidoid/rapidoid
  public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> map(
      Function<? super T, ? extends K> keyMapper,
      Function<? super T, ? extends U> valueMapper,
      BinaryOperator<U> mergeFunction,
      Supplier<M> mapSupplier) {

    return Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier);
  }
 @JsonApiFindAllWithIds
 public Iterable<Project> findAll(Iterable<Long> projectIds, QueryParams requestParams) {
   return REPOSITORY
       .entrySet()
       .stream()
       .filter(p -> Iterables.contains(projectIds, p.getKey()))
       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
       .values();
 }
示例#28
0
 @JsonAnyGetter
 Map<String, Map<String, List<SObjectNode>>> children() {
   return records
       .entrySet()
       .stream()
       .collect(
           Collectors.toMap(
               Map.Entry::getKey, e -> Collections.singletonMap("records", e.getValue())));
 }
示例#29
0
 public static <T, U, V extends Map<T, U>, W> V toMap(
     Function<W, T> keyMapper,
     Function<W, U> valueMapper,
     Supplier<V> mapSupplier,
     Stream<W> stream) {
   return stream.collect(
       Collectors.toMap(
           keyMapper::apply, valueMapper::apply, (value1, value2) -> value2, mapSupplier));
 }
 @Override
 public Map<Ticket, Map.Entry<DiscountType, BigDecimal>> getDiscount(
     User user, Event event, Date date) {
   List<Ticket> actualTickets = getActualTickets(user, event, date);
   return actualTickets
       .stream()
       .collect(
           Collectors.toMap(ticket -> ticket, discount -> calculateDiscount(user, event, date)));
 }