Java Code Examples for java.util.stream.Collectors

The following are top voted examples for showing how to use java.util.stream.Collectors. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: uis   File: StudentAllStudyPlansController.java   View source code 6 votes vote down vote up
@GetMapping(params = "id")
private String getStudyplanDetailsView(@RequestParam(value = "id") Long id, Model model) {
    StudyPlan studyPlan = studyPlanService.findOne(id);

    List<SubjectForStudyPlan> subjectsForStudyPlan = studyPlanService.getSubjectsForStudyPlan(id);
    List<SubjectForStudyPlan> mandatory = subjectsForStudyPlan
            .stream()
            .filter(SubjectForStudyPlan::getMandatory)
            .collect(Collectors.toList());
    List<SubjectForStudyPlan> optional = subjectsForStudyPlan
            .stream()
            .filter(s -> !s.getMandatory())
            .collect(Collectors.toList());

    model.addAttribute("studyPlan", studyPlan);
    model.addAttribute("mandatory", mandatory);
    model.addAttribute("optional", optional);

    return "student/all-studyplan-details";
}
 
Example 2
Project: csap-core   File: HostStatusManager.java   View source code 6 votes vote down vote up
public Map<String, ObjectNode> hostsRuntime ( List<String> hosts ) {

		return hosts.stream()
			.map( host -> {
				ObjectNode hostRuntime = hostResponseMap.get( host );
				if ( hostRuntime == null ) {
					hostRuntime = jsonMapper.createObjectNode();
					hostRuntime.put( "error", "No response found" );
				}
				hostRuntime.put( "collectedHost", host );
				return hostRuntime;
			} )
			.collect( Collectors.toMap(
				hostStatus -> hostStatus.get( "collectedHost" ).asText(),
				hostStatus -> hostStatus ) );
	}
 
Example 3
Project: openjdk-jdk10   File: TestCase.java   View source code 6 votes vote down vote up
/**
 * Generates source which represents the class.
 *
 * @return source which represents the class
 */
@Override
public String generateSource() {
    String sourceForAnnotations = generateSourceForAnnotations();
    String classModifiers = mods.stream().collect(Collectors.joining(" "));
    return sourceForAnnotations
            + String.format("%s%s %s %s %s {%n",
            indention(),
            classModifiers,
            classType.getDescription(),
            name,
            parent == null ? "" : "extends " + parent)
            + classType.collectFields(fields.values())
            + classType.collectMethods(methods.values())
            + classType.collectInnerClasses(innerClasses.values())
            + indention() + "}";
}
 
Example 4
Project: FreeCol   File: Specification.java   View source code 6 votes vote down vote up
private void fixUnitChanges() {
    // Unlike roles, we can not trust what is already there, as the changes
    // are deeper.

    if (compareVersion("0.116") > 0) return;

    unitChangeTypeList.clear();
    File uctf = FreeColDirectories.getCompatibilityFile(UNIT_CHANGE_TYPES_COMPAT_FILE_NAME);
    try (
         FileInputStream fis = new FileInputStream(uctf);
         ) {
        load(fis);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to load unit changes.", e);
        return;
    }

    logger.info("Loading unit-changes backward compatibility fragment: "
        + UNIT_CHANGE_TYPES_COMPAT_FILE_NAME + " with changes: "
        + transform(getUnitChangeTypeList(), alwaysTrue(),
            UnitChangeType::getId, Collectors.joining(" ")));
}
 
Example 5
Project: elements-of-programming-interviews   File: GenerateNonuniformRandomNumbersTest.java   View source code 6 votes vote down vote up
private void test(List<Integer> values, List<Double> probabilities) {
    final Map<Integer, AtomicInteger> results = new ConcurrentHashMap<>(
            values.stream()
                    .map(integer -> new AbstractMap.SimpleImmutableEntry<>(integer, new AtomicInteger(0)))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
    );

    IntStream.range(0, N)
            .parallel()
            .forEach(i -> {
                results.get(GenerateNonuniformRandomNumbers.getRandom(values,probabilities)).incrementAndGet();
            });

    IntStream.range(0, values.size())
            .parallel()
            .forEach(i -> {
                double expectedValue = N * probabilities.get(i);
                assertThat(results.get(values.get(i)), allOf(greaterThan(expectedValue - 50), lessThan(expectedValue + 50)));
            });
}
 
Example 6
Project: ascii-table   File: AsciiTable.java   View source code 6 votes vote down vote up
public static String getTable(Character[] borderChars, Column[] rawColumns, String[][] data) {
    if (borderChars.length != NO_BORDERS.length) {
        throw new IllegalArgumentException("Border characters array must be exactly " + NO_BORDERS.length + " elements long");
    }

    final int numColumns = getNumColumns(rawColumns, data);
    final Column[] columns = IntStream.range(0, numColumns)
            .mapToObj(index -> index < rawColumns.length ? rawColumns[index] : new Column())
            .toArray(Column[]::new);
    final int[] colWidths = getColWidths(columns, data);

    final HorizontalAlign[] headerAligns = Arrays.stream(columns).map(Column::getHeaderAlign).toArray(HorizontalAlign[]::new);
    final HorizontalAlign[] dataAligns = Arrays.stream(columns).map(Column::getDataAlign).toArray(HorizontalAlign[]::new);
    final HorizontalAlign[] footerAligns = Arrays.stream(columns).map(Column::getFooterAlign).toArray(HorizontalAlign[]::new);

    final String[] header = Arrays.stream(columns).map(Column::getHeader).toArray(String[]::new);
    final String[] footer = Arrays.stream(columns).map(Column::getFooter).toArray(String[]::new);

    List<String> tableRows = getTableRows(colWidths, headerAligns, dataAligns, footerAligns, borderChars, header, data, footer);

    return tableRows.stream()
            .filter(line -> !line.isEmpty())
            .collect(Collectors.joining(System.lineSeparator()));
}
 
Example 7
Project: openjdk-jdk10   File: MergeName.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        test("p1", "read", "write", "delete", "execute");
        test("p2", "read,write", "delete,execute");
        test("p3", "read,write,delete", "execute");
        test("p4", "read,write,delete,execute");
    } else {
        SecurityManager sm = System.getSecurityManager();
        for (String arg : args) {
            // Use bits to create powerset of ALL_ACTIONS
            IntStream.range(1, 16)
                    .mapToObj(n -> IntStream.range(0, 4)
                            .filter(x -> (n & (1 << x)) != 0)
                            .mapToObj(x -> ALL_ACTIONS[x])
                            .collect(Collectors.joining(",")))
                    .forEach(a -> sm.checkPermission(
                            new FilePermission(arg, a)));
        }
    }
}
 
Example 8
Project: uroborosql   File: SqlContextFactoryTest.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testConst_enum() {
	sqlContextFactory.setEnumConstantPackageNames(Arrays.asList(TestEnum1.class.getPackage().getName()));

	sqlContextFactory.initialize();

	Map<String, Parameter> constParameterMap = sqlContextFactory.getConstParameterMap();
	Set<String> set = constParameterMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().getValue())
			.collect(Collectors.toSet());

	assertThat(
			set,
			is(new HashSet<>(Arrays.asList("CLS_TEST_ENUM1_A=A", "CLS_TEST_ENUM1_B=B", "CLS_TEST_ENUM1_C=C",
					"CLS_PACKTEST_TEST_ENUM2_D=D", "CLS_PACKTEST_TEST_ENUM2_E=E", "CLS_PACKTEST_TEST_ENUM2_F=F",
					"CLS_PACKTEST_TEST_ENUM2_INNER_G=G", "CLS_PACKTEST_TEST_ENUM2_INNER_H=H",
					"CLS_PACKTEST_TEST_ENUM2_INNER_I=I"))));

	for (Parameter parameter : constParameterMap.values()) {
		assertThat(parameter.getValue(), isA((Class) Enum.class));
	}
}
 
Example 9
Project: keycloak-protocol-cas   File: AbstractUserRoleMappingMapper.java   View source code 6 votes vote down vote up
/**
 * Retrieves all roles of the current user based on direct roles set to the user, its groups and their parent groups.
 * Then it recursively expands all composite roles, and restricts according to the given predicate {@code restriction}.
 * If the current client sessions is restricted (i.e. no client found in active user session has full scope allowed),
 * the final list of roles is also restricted by the client scope. Finally, the list is mapped to the token into
 * a claim.
 */
protected void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                                   Predicate<RoleModel> restriction, String prefix) {
    String rolePrefix = prefix == null ? "" : prefix;
    UserModel user = userSession.getUser();

    // get a set of all realm roles assigned to the user or its group
    Stream<RoleModel> clientUserRoles = getAllUserRolesStream(user).filter(restriction);

    boolean dontLimitScope = userSession.getAuthenticatedClientSessions().values().stream().anyMatch(cs -> cs.getClient().isFullScopeAllowed());
    if (! dontLimitScope) {
        Set<RoleModel> clientRoles = userSession.getAuthenticatedClientSessions().values().stream()
          .flatMap(cs -> cs.getClient().getScopeMappings().stream())
          .collect(Collectors.toSet());

        clientUserRoles = clientUserRoles.filter(clientRoles::contains);
    }

    Set<String> realmRoleNames = clientUserRoles
      .map(m -> rolePrefix + m.getName())
      .collect(Collectors.toSet());

    setPlainAttribute(attributes, mappingModel, realmRoleNames);
}
 
Example 10
Project: aws-s3-file-system   File: IndexController.java   View source code 6 votes vote down vote up
@GetMapping("/")
  public String listUploadedFiles(Model model) {

      try {
      	logger.info("Fetching all Files from S3");
	model.addAttribute("files", s3OperationService.getAllFiles()
	        .stream()
	        .collect(Collectors.toMap(f-> f, f -> {
	        	List<String> filesNFolders = new ArrayList<>();
	        	String[] folders = f.split("/");
	        	Arrays.asList(folders).forEach(filesNFolders::add);
	        	return filesNFolders;
	        })));
} catch(IOException e) {
	logger.error("Failed to Connect to AWS S3 - Please check your AWS Keys");
	e.printStackTrace();
}

      return "index";
  }
 
Example 11
Project: powsybl-core   File: BranchTrippingTest.java   View source code 6 votes vote down vote up
@Test
public void fictitiousSwitchTest() {
    Set<String> switchIds = Sets.newHashSet("BD", "BL");

    Network network = FictitiousSwitchFactory.create();
    List<Boolean> expectedSwitchStates = getSwitchStates(network, switchIds);

    BranchTripping tripping = new BranchTripping("CJ", "C");

    Set<Switch> switchesToOpen = new HashSet<>();
    Set<Terminal> terminalsToDisconnect = new HashSet<>();
    tripping.traverse(network, null, switchesToOpen, terminalsToDisconnect);
    assertEquals(switchIds, switchesToOpen.stream().map(Switch::getId).collect(Collectors.toSet()));
    assertEquals(Collections.emptySet(), terminalsToDisconnect);

    tripping.modify(network, null);
    assertTrue(network.getSwitch("BD").isOpen());
    assertTrue(network.getSwitch("BL").isOpen());

    List<Boolean> switchStates = getSwitchStates(network, switchIds);
    assertEquals(expectedSwitchStates, switchStates);
}
 
Example 12
Project: mapr-music   File: AlbumParser.java   View source code 6 votes vote down vote up
private List<Album> parseReleaseStatusFile(List<Album> albums) {
    Map<String, List<Album>> albumMap = albums.stream()
            .filter(album -> !StringUtils.isEmpty(album.getStatus()))
            .collect(Collectors.groupingBy(Album::getStatus));

    //read file into stream, try-with-resources
    try (Stream<String> stream = Files.lines(Paths.get(albumStatusFilePath))) {
        Stream<String[]> rows = stream.map(strRow -> strRow.split(TAB_SYMBOL));
        rows.forEach(row -> {
            List<Album> albumList = albumMap.get(row[0]);
            if (albumList != null) {
                albumList.forEach(album -> album.setStatus(row[1]));
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    return albums;
}
 
Example 13
Project: EgTest   File: TestWriter.java   View source code 6 votes vote down vote up
static void write(ClassWriter classWriter, TypeSpec.Builder builder) {
    Map<Element, List<EgItem<?>>> examplesByElement = classWriter.getItems().stream()
            .collect(Collectors.groupingBy(EgItem::getElement));

    for (Map.Entry<Element, List<EgItem<?>>> entry: examplesByElement.entrySet()) {
        Element el = entry.getKey();
        List<EgItem<?>> examples = entry.getValue();

        new PatternMatchWriter(el, filterAndConvert(PatternMatchExample.class, examples), classWriter, builder)
                .addTests();
        new FunctionMatchWriter(el, filterAndConvert(FunctionMatchExample.class, examples), classWriter, builder)
                .addTests();

        if (el instanceof ExecutableElement) {
            ExecutableElement exEl = (ExecutableElement) el;

            List<ReturnsExample> returnsExamples = filterAndConvert(ReturnsExample.class, examples);
            new EgWriter(exEl, returnsExamples, classWriter, builder)
                    .addTests();

            List<ExceptionExample> exceptionExamples = filterAndConvert(ExceptionExample.class, examples);
            new ExceptionWriter(exEl, exceptionExamples, classWriter, builder)
                    .addTests();
        }
    }
}
 
Example 14
Project: infxnity   File: MaskTextFilter.java   View source code 6 votes vote down vote up
/**
 * @param input
 *            {@link TextInputControl} where set the default value
 */
public void applyDefault(final TextInputControl input)
{
    try
    {
        settingDefaultOn = input;
        final String defaultText = Stream.of(mask) //
                                         .map(m -> Character.toString(m.getDefault()))
                                         .collect(Collectors.joining());
        input.setText(defaultText);

        final int firstAllowedPosition = IntStream.range(0, mask.length)
                                                  .filter(i -> mask[i].isNavigable())
                                                  .findFirst()
                                                  .orElse(0);
        input.selectRange(firstAllowedPosition, firstAllowedPosition);
    }
    finally
    {
        settingDefaultOn = null;
    }
}
 
Example 15
Project: web3j-maven-plugin   File: JavaClassGeneratorITest.java   View source code 6 votes vote down vote up
@Test
public void pomStandard() throws Exception {
    File pom = new File(resources.getBasedir("valid"), "pom.xml");
    assertNotNull(pom);
    assertTrue(pom.exists());

    JavaClassGeneratorMojo mojo = (JavaClassGeneratorMojo) mojoRule.lookupMojo("generate-sources", pom);
    assertNotNull(mojo);

    mojo.sourceDestination = testFolder.getRoot().getPath();
    mojo.execute();

    Path path = Paths.get(mojo.sourceDestination);

    List<Path> files = Files.find(path, 99, (p, bfa) -> bfa.isRegularFile()).collect(Collectors.toList());
    assertEquals("Greeter and Mortal Class", 2l, files.size());
}
 
Example 16
Project: SoftUni   File: p12_LittleJohn.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    LinkedHashMap<String, Integer> arrows = new LinkedHashMap<String, Integer>(){{
        put(">>>----->>", 0); put(">>----->", 0); put(">----->", 0);}};

    for (int i = 0; i < 4; i++) {
        String line = reader.readLine();
        // if(line.length() < 7) continue;
        for (Map.Entry<String, Integer> arr :
                arrows.entrySet()) {
            int index = line.indexOf(arr.getKey());
            while(index > -1){
                arrows.put(arr.getKey(), arr.getValue() + 1);
                index = line.indexOf(arr.getKey(), index + arr.getKey().length());
            }
            // replace with neutral symbol, to ensure that after replacement we will not produce new arrow
            // -> nested arrows
            line = line.replaceAll(arr.getKey(), "*");
        }
    }
    long num = Long.parseLong(arrows.entrySet().stream()
        .sorted(Comparator.comparingInt(arr -> (arr.getKey().length())))
        .map(e -> e.getValue().toString()).collect(Collectors.joining("")));
    StringBuilder strNum = new StringBuilder(Long.toString(num, 2));
    strNum.append(new StringBuilder(strNum).reverse());
    System.out.println(Long.parseLong(strNum.toString(), 2));
}
 
Example 17
Project: vulture   File: VultureProcessor.java   View source code 5 votes vote down vote up
@TargetApi(24)
private List<FieldSpec> getIdFieldSpecs(Map<ExecutableElement, String> methodToIdMap) {
    AtomicInteger index = new AtomicInteger(0);
    return methodToIdMap.values()
            .stream()
            .map(value -> FieldSpec
                    .builder(int.class, value)
                    .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
                    .initializer("$L", index.getAndIncrement())
                    .build())
            .collect(Collectors.toList());
}
 
Example 18
Project: yapi   File: YeelightFlow.java   View source code 5 votes vote down vote up
/**
 * Create params array for a command
 * @return Params array
 */
public Object[] createCommandParams() {
    String flowExpression = this.transitions.stream()
            .map(t -> YeelightUtils.joinIntArray(",", t.getTuple()))
            .collect(Collectors.joining(","));
    return new Object[] {
            this.count * this.transitions.size(),
            this.action.getValue(),
            flowExpression
    };
}
 
Example 19
Project: cas-5.1.0   File: OidcConfiguration.java   View source code 5 votes vote down vote up
@Bean
public HandlerInterceptorAdapter requiresAuthenticationDynamicRegistrationInterceptor() {
    final String clients = Stream.of(
            Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN,
            Authenticators.CAS_OAUTH_CLIENT_DIRECT_FORM,
            Authenticators.CAS_OAUTH_CLIENT_USER_FORM).collect(Collectors.joining(","));
    return new SecurityInterceptor(oauthSecConfig, clients);
}
 
Example 20
Project: promagent   File: Delegator.java   View source code 5 votes vote down vote up
private static List<Method> findHookMethods(Class<? extends Annotation> annotation, Class<?> hookClass, Method interceptedMethod) throws HookException {
    return Stream.of(hookClass.getDeclaredMethods())
            .filter(method -> method.isAnnotationPresent(annotation))
            .filter(method -> getMethodNames(method.getAnnotation(annotation)).contains(interceptedMethod.getName()))
            .filter(method -> parameterTypesMatch(method, interceptedMethod))
            .collect(Collectors.toList());
}
 
Example 21
Project: smarti   File: Configuration.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <C extends ComponentConfiguration> Iterable<C> getConfigurations(Configurable<C> component, boolean onlyEnabled){
    if(component == null){
        return null;
    }
    List<ComponentConfiguration> catConfigs = config.get(component.getComponentCategory());
    if(catConfigs == null){
        return Collections.emptyList();
    }
    return (Iterable<C>)catConfigs.stream()
            .filter(cc -> Objects.equals(component.getComponentName(), cc.getType()))
            .filter(cc -> component.getConfigurationType().isAssignableFrom(cc.getClass()))
            .filter(cc -> !onlyEnabled || cc.isEnabled())
        .collect(Collectors.toList());
}
 
Example 22
Project: dawn   File: SecurityInfo.java   View source code 5 votes vote down vote up
static AuthoritiesEnum getTopAuth() {
    Iterator iterator = SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator();
    List<AuthoritiesEnum> authorities = new ArrayList<>();
    while (iterator.hasNext()) {
        authorities.add(AuthoritiesEnum.valueOf(iterator.next().toString()));
    }
    authorities = authorities.stream().sorted().collect(Collectors.toList());
    return authorities.get(0);
}
 
Example 23
Project: rs-aggregator   File: ResultIndexPivot.java   View source code 5 votes vote down vote up
public List<Result<RsRoot>> listRsRootResults(Capability capability) {
  return streamRsRootResults()
    .filter(result -> result.getContent()
      .map(RsRoot::getMetadata)
      .flatMap(RsMd::getCapability).orElse("Invalid capability").equals(capability.xmlValue))
    .collect(Collectors.toList());
}
 
Example 24
Project: Shuriken   File: ClassWrapper.java   View source code 5 votes vote down vote up
/**
 * Get all available fields in class
 *
 * @return List of fields
 */
public List<FieldWrapper<?>> getFields() {
    return FIELD_INDEX.values().stream()
            .map(index -> FIELDWRAPPER_CACHE.computeIfAbsent(index, k ->
                    MethodHandleFieldWrapper.of(this, FIELD_CACHE.get(index))))
            .collect(Collectors.toList());
}
 
Example 25
Project: openjdk-jdk10   File: ComboTask.java   View source code 5 votes vote down vote up
/**
 * Dump useful info associated with this task.
 */
public String compilationInfo() {
    return "instance#" + env.info().comboCount + ":[ options = " + options
            + ", diagnostics = " + diagsCollector.diagsByKeys.keySet()
            + ", dimensions = " + env.bindings
            + ", sources = \n" + sources.stream().map(s -> {
        try {
            return s.getCharContent(true);
        } catch (IOException ex) {
            return "";
        }
    }).collect(Collectors.joining(",")) + "]";
}
 
Example 26
Project: devops-cstack   File: LogResourceFactory.java   View source code 5 votes vote down vote up
public static List<LogResource> fromOutput(String outputShell) {
    if (outputShell == null) return new ArrayList<>();
    if(outputShell.trim().length()<=3) return new ArrayList<>();
    outputShell = outputShell.trim();
    List<LogResource> logResources = Arrays.stream(outputShell.split("\\n"))
            .map(LogResourceFactory::fromStdout)
            .collect(Collectors.toList());
    Collections.reverse(logResources);
    return logResources;
}
 
Example 27
Project: trex-java-sdk   File: TRexClient.java   View source code 5 votes vote down vote up
private List<TRexCommand> buildRemoveCaptureCommand(List<Integer> capture_ids) {
    return capture_ids.stream()
                      .map(captureId -> {
                          Map<String, Object> parameters = new HashMap<>();
                          parameters.put("command", "remove");
                          parameters.put("capture_id", captureId);
                          return buildCommand("capture", parameters);
                      })
                      .collect(Collectors.toList());
}
 
Example 28
Project: Indra   File: IndraDriverTest.java   View source code 5 votes vote down vote up
public void oneToManyRelatedness(RelatednessPairRequest pairRequest, RelatednessOneToManyRequest otmRequest) {
    RelatednessPairResponse pairRes = driver.getRelatedness(pairRequest);
    Map<String, Double> pairResults = pairRes.getPairs().stream().collect(Collectors.toMap(p -> p.t2, p -> p.score));

    RelatednessOneToManyResponse otmRes = driver.getRelatedness(otmRequest);

    for (String m : otmRes.getMany().keySet()) {
        Assert.assertEquals(otmRes.getMany().get(m), pairResults.get(m));
    }
}
 
Example 29
Project: rest-modeling-framework   File: RamlObjectValidator.java   View source code 5 votes vote down vote up
private List<Diagnostic> validatePositiveIntegerAttributes(final EClass eClass, final EObject eObject, final DiagnosticChain diagnostics) {
    final List<Diagnostic> missingRequiredAttributes = eClass.getEAllAttributes().stream()
            .filter(eAttribute -> !eAttribute.isMany()
                    && eAttribute.getEAttributeType() == FacetsPackage.Literals.POSITIVE_INTEGER
                    && eObject.eIsSet(eAttribute) && ((Integer) eObject.eGet(eAttribute)) <= 0)
            .map(eAttribute -> error("Facet '" + eAttribute.getName() + "' must > 0.", eObject)).collect(Collectors.toList());

    return missingRequiredAttributes;
}
 
Example 30
Project: tapir   File: SipSearchService.java   View source code 5 votes vote down vote up
private List<SipSession> extract(Map<String, SipSessionContainer> accumulator, SipSearchRequest request) {
    return accumulator.values().stream()
            .map(container -> container.session)
            .filter(session -> checkMillis(session.getMillis(), request.getMillis()))
            .sorted(Comparator.comparing(SipSession::getMillis))
            .collect(Collectors.toList());
}
 
Example 31
Project: athena   File: ResourceManager.java   View source code 5 votes vote down vote up
@Override
public <T> Set<T> getAvailableResourceValues(DiscreteResourceId parent, Class<T> cls) {
    checkPermission(RESOURCE_READ);
    checkNotNull(parent);
    checkNotNull(cls);

    // naive implementation
    return getAvailableResources(parent).stream()
            .flatMap(resource -> Tools.stream(resource.valueAs(cls)))
            .collect(Collectors.toSet());
}
 
Example 32
Project: Supreme-Bot   File: CommandHandler.java   View source code 5 votes vote down vote up
public static final EmbedBuilder generateHelpMessage(Invoker invoker, MessageEvent event, Command command) {
    final EmbedBuilder builder = command.getHelp(invoker, new EmbedBuilder().setTitle(String.format("Help for \"%s\"", invoker)));
    final ArrayList<Invoker> invokers = command.getInvokers();
    if (invokers.size() > 1) {
        builder.setDescription(String.format("Associated Command Invokers: %s", getInvokersAsString(invokers.stream().filter((invoker_) -> !invoker.equals(invoker_)).collect(Collectors.toList()))));
    }
    return builder;
}
 
Example 33
Project: wowza-letsencrypt-converter   File: ConverterTest.java   View source code 5 votes vote down vote up
private void checkResults() throws Exception {
    // test map
    Path map = outDir.resolve("jksmap.txt");
    assertThat(map).isRegularFile();
    List<String> mapLines = Files.lines(map).collect(Collectors.toList());

    assertThat(mapLines.size()).isEqualTo(6);

    checkLine(mapLines, "multi-1.not-secure.r2.io");
    checkLine(mapLines, "multi-2.not-secure.r2.io");
    checkLine(mapLines, "multi-3.not-secure.r2.io");
    checkLine(mapLines, "not-secure.r2.io");
    checkLine(mapLines, "www.not-secure.r2.io");
    checkLine(mapLines, "single.not-secure.r2.io");
}
 
Example 34
Project: bamboo-soy   File: ParamUtils.java   View source code 5 votes vote down vote up
public static Collection<String> getGivenParameters(CallStatementElement statement) {
  return statement
      .getParamListElementList()
      .stream()
      .map(param -> param.getBeginParamTag().getParamSpecificationIdentifier())
      .filter(param -> param != null)
      .map(PsiElement::getText)
      .collect(Collectors.toList());
}
 
Example 35
Project: chvote-protocol-poc   File: MixingAuthorityAlgorithms.java   View source code 5 votes vote down vote up
private List<Integer> reversePermutation(List<Integer> psy) {
    Preconditions.checkArgument(psy.containsAll(
            IntStream.range(0, psy.size()).boxed().collect(Collectors.toList())),
            "The permutation should contain all number from 0 (inclusive) to length (exclusive)");

    return IntStream.range(0, psy.size()).mapToObj(psy::indexOf).collect(Collectors.toList());
}
 
Example 36
Project: incubator-servicecomb-saga   File: GraphCycleDetectorImpl.java   View source code 5 votes vote down vote up
private Set<Node<T>> unvisitedNodes(Map<Node<T>, Set<Node<T>>> nodeParents) {
  return nodeParents.entrySet()
      .parallelStream()
      .filter(parents -> !parents.getValue().isEmpty())
      .map(Entry::getKey)
      .collect(Collectors.toSet());
}
 
Example 37
Project: act-platform   File: ObjectSearchDelegate.java   View source code 5 votes vote down vote up
public ResultSet<Object> handle(SearchObjectRequest request)
        throws AccessDeniedException, AuthenticationFailedException, InvalidArgumentException {
  TiSecurityContext.get().checkPermission(TiFunctionConstants.viewFactObjects);

  List<ObjectEntity> filteredObjects = filterObjects(request);

  return ResultSet.builder()
          .setCount(filteredObjects.size())
          .setLimit(ObjectUtils.ifNull(request.getLimit(), DEFAULT_LIMIT))
          .setValues(filteredObjects.stream().map(TiRequestContext.get().getObjectConverter()).collect(Collectors.toList()))
          .build();
}
 
Example 38
Project: uis   File: TagFrequencyCalculatorImpl.java   View source code 5 votes vote down vote up
private Map<Tag, Double> mergeTagFrequency(Map<Tag, Double> map1, Map<Tag, Double> map2) {
    return Stream
            .concat(map1.entrySet().stream(), map2.entrySet().stream())
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    Double::sum
                    )
            );
}
 
Example 39
Project: secrets-proxy   File: SecretService.java   View source code 5 votes vote down vote up
/**
 * Normalize a list of unique secret names.
 *
 * @param uniqSecretNames collection of unique secret names.
 * @return list of normalized secret names.
 */
public List<String> normalize(Collection<String> uniqSecretNames) {
    return uniqSecretNames.stream().map(uniqName -> {
        AppSecret appSecret = new AppSecret(uniqName);
        return appSecret.getSecretName();
    }).collect(Collectors.toList());
}
 
Example 40
Project: NGB-master   File: FeatureIndexManagerTest.java   View source code 5 votes vote down vote up
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void groupingTest() throws IOException {
    VcfFilterForm vcfFilterForm = new VcfFilterForm();

    IndexSearchResult<VcfIndexEntry> entryList = featureIndexManager.filterVariations(vcfFilterForm,
                                                                                      testProject.getId());
    Assert.assertFalse(entryList.getEntries().isEmpty());

    List<Group> counts = featureIndexManager.groupVariations(new VcfFilterForm(), testProject.getId(),
                                                             IndexSortField.CHROMOSOME_NAME.name());
    Assert.assertFalse(counts.isEmpty());

    // test load additional info and group by it
    VcfFilterInfo info = vcfManager.getFiltersInfo(Collections.singletonList(testVcf.getId()));

    vcfFilterForm = new VcfFilterForm();
    vcfFilterForm.setInfoFields(info.getInfoItems().stream().map(i -> i.getName()).collect(Collectors.toList()));

    entryList = featureIndexManager.filterVariations(vcfFilterForm, testProject.getId());
    Assert.assertFalse(entryList.getEntries().isEmpty());

    for (InfoItem infoItem : info.getInfoItems()) {
        String groupByField = infoItem.getName();
        List<Group> c = featureIndexManager.groupVariations(new VcfFilterForm(), testProject.getId(),
                                                                            groupByField);
        List<VcfIndexEntry> entriesWithField = entryList.getEntries().stream()
            .filter(e -> e.getInfo().get(groupByField) != null).collect(Collectors.toList());
        if (!entriesWithField.isEmpty()) {
            Assert.assertFalse("Empty grouping for field: " + groupByField, c.isEmpty());
        }
    }
}