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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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());
        }
    }
}
 
Example 41
Project: NGB-master   File: FeatureIndexManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testLoadAllFields() throws IOException {
    VcfFilterForm filterForm = new VcfFilterForm();
    VcfFilterInfo info = vcfManager.getFiltersInfo(Collections.singletonList(testVcf.getId()));
    filterForm.setInfoFields(info.getInfoItems().stream().map(InfoItem::getName).collect(Collectors.toList()));

    IndexSearchResult<VcfIndexEntry> entries = featureIndexManager.filterVariations(filterForm,
                                                                                    testProject.getId());
    Assert.assertFalse(entries.getEntries().isEmpty());
}
 
Example 42
Project: exam   File: ExamRecordAPIController.java   Source Code and License 5 votes vote down vote up
private static List<ExamScore> getScores(String startDate) {
    DateTime start = ISODateTimeFormat.dateTimeParser().parseDateTime(startDate);
    List<ExamRecord> examRecords = Ebean.find(ExamRecord.class)
            .fetch("examScore")
            .where()
            .gt("timeStamp", start.toDate())
            .findList();
    return examRecords.stream().map(ExamRecord::getExamScore).collect(Collectors.toList());
}
 
Example 43
Project: monarch   File: BundledJarsJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void loadExpectedJars() throws IOException {
  String expectedJarFile =
      TestUtil.getResourcePath(BundledJarsJUnitTest.class, "/expected_jars.txt");

  expectedJars = Files.lines(Paths.get(expectedJarFile)).collect(Collectors.toSet());
}
 
Example 44
Project: Dhalion   File: HealthPolicyImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Diagnosis> executeDiagnosers(List<Symptom> symptoms) {
  List<Diagnosis> diagnosis = new ArrayList<>();
  if (diagnosers == null) {
    return diagnosis;
  }

  diagnosis = diagnosers.stream().map(diagnoser -> diagnoser.diagnose(symptoms))
      .filter(diagnoses -> diagnoses != null).flatMap(x -> x.stream())
      .collect(Collectors.toList());

  return diagnosis;
}
 
Example 45
Project: crypto-shuffle   File: KeyShardSetTest.java   Source Code and License 5 votes vote down vote up
@Test
public void buildTest() {
    final Set<KeyPair> keyPairs5 = generateKeyPairs(5);
    final Set<KeyPair> keyPairs3 = generateKeyPairs(3);
    final KeyShardSet.KeyShardingSetBuilder builder = KeyShardSet.newBuilder(AsymmetricEncryptionAlgorithm.RSA);
    final Set<PublicKey> publicKeys5 = keyPairs5.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
    final Set<PublicKey> publicKeys3 = keyPairs3.stream().map(KeyPair::getPublic).collect(Collectors.toSet());
    final KeyShardSet keyShardSet = builder.addKeyGroup(2,  publicKeys5)
            .addKeyGroup(3,  publicKeys3)
            .build(key4800);
    assertNotNull(keyShardSet.getUuid());
    assertEquals(8, keyShardSet.getShardCount());
    final Collection<KeyShardSet.KeyShardGroup> groups = keyShardSet.getGroups();
    assertEquals(2, groups.size());
    final Iterator<KeyShardSet.KeyShardGroup> groupIterator = groups.iterator();
    final KeyShardSet.KeyShardGroup thisGroup = groupIterator.next();
    final KeyShardSet.KeyShardGroup group5, group3;
    switch (thisGroup.getKeys().size()) {
        case 5:
            group5 = thisGroup;
            group3 = groupIterator.next();
            break;
        case 3:
            group3 = thisGroup;
            group5 = groupIterator.next();
            break;
        default:
            fail("Group has a size other than 5 or 3!");
            throw new RuntimeException("Group has a size other than 5 or 3!");
    }
    assertEquals(publicKeys5, group5.getKeys());
    assertEquals(publicKeys3, group3.getKeys());
    assertEquals(2, group5.getQuorumSize());
    assertEquals(3, group3.getQuorumSize());
    checkGroupShardsPerKey(group5, 4);
    checkGroupShardsPerKey(group3, 1);
    checkGroupCoverage(keyShardSet);
}
 
Example 46
Project: OneClient   File: InstanceManager.java   Source Code and License 5 votes vote down vote up
public static List<String> getFeaturedProjects() {
	Featured[] array = null;
	try {
		array = JsonUtil.read(new URL(FEATURED_URL), Featured[].class);
	} catch (MalformedURLException e) {
		OneClientLogging.error(e);
	}
	if (array != null) {
		return Arrays.stream(array).map(f -> f.projectId).collect(Collectors.toList());
	}
	return null;
}
 
Example 47
Project: rdf2x   File: RelationSchemaCollector.java   Source Code and License 5 votes vote down vote up
/**
 * Get all unique triples of (predicate URI, source type index, target type index) of related entities.
 *
 * @param relations DataFrame of relations (predicateIndex, fromTypeIndex, instanceID, toTypeIndex, relatedID)
 * @return all unique triples of (predicate URI, source type index, target type index) of related entities
 */
private Set<Tuple3<String, Integer, Integer>> getUniquePredicateTypeTriples(DataFrame relations) {
    return relations
            .select("predicateIndex", "fromTypeIndex", "toTypeIndex")
            .distinct()
            .collectAsList().stream()
            .map(row -> new Tuple3<>(rdfSchema.getPredicateIndex().getValue(row.getInt(0)), row.getInt(1), row.getInt(2)))
            .collect(Collectors.toSet());
}
 
Example 48
Project: quickmon   File: JsonBackedNotifiersRepositoryImpl.java   Source Code and License 5 votes vote down vote up
protected void loadFromFile() throws IOException {
    Collection<? extends NotifierBuilder> collection = objectMapper.readValue(
            new FileReader(notifierFile),
            new TypeReference<Set<NotifierBuilder>>() {
            }
    );
    this.notifierSet.addAll(collection.stream().map(builder -> builder.build()).collect(Collectors.toSet()));
}
 
Example 49
Project: Randores2   File: RandoresFromOreDictConvert.java   Source Code and License 5 votes vote down vote up
public List<MaterialDefinition> findFromOreDict(World world, ItemStack stack) {
    List<String> names = new ArrayList<>();
    for(int index : OreDictionary.getOreIDs(stack)) {
        names.add(OreDictionary.getOreName(index));
    }

    return RandoresWorldData.getAll(RandoresWorldData.getId(world)).stream().filter(def -> !names.contains(def.getMaterial().getType().getDictName() + def.getName())).collect(Collectors.toList());
}
 
Example 50
Project: cf-mta-deploy-service   File: PollServiceOperationsExecution.java   Source Code and License 5 votes vote down vote up
private List<CloudServiceExtended> getRemainingServicesToPoll(Map<CloudServiceExtended, ServiceOperation> servicesWithLastOperation) {
    return servicesWithLastOperation.entrySet()
        .stream()
        .filter(serviceWithLastOperation -> serviceWithLastOperation.getValue().getState() == ServiceOperationState.IN_PROGRESS)
        .map(serviceWithLastOperation -> serviceWithLastOperation.getKey())
        .collect(Collectors.toList());
}
 
Example 51
Project: elasticsearch_my   File: BucketScriptPipelineAggregator.java   Source Code and License 4 votes vote down vote up
@Override
public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext reduceContext) {
    InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket> originalAgg = (InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
    List<? extends Bucket> buckets = originalAgg.getBuckets();

    CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS);
    List newBuckets = new ArrayList<>();
    for (Bucket bucket : buckets) {
        Map<String, Object> vars = new HashMap<>();
        if (script.getParams() != null) {
            vars.putAll(script.getParams());
        }
        boolean skipBucket = false;
        for (Map.Entry<String, String> entry : bucketsPathsMap.entrySet()) {
            String varName = entry.getKey();
            String bucketsPath = entry.getValue();
            Double value = resolveBucketValue(originalAgg, bucket, bucketsPath, gapPolicy);
            if (GapPolicy.SKIP == gapPolicy && (value == null || Double.isNaN(value))) {
                skipBucket = true;
                break;
            }
            vars.put(varName, value);
        }
        if (skipBucket) {
            newBuckets.add(bucket);
        } else {
            ExecutableScript executableScript = reduceContext.scriptService().executable(compiledScript, vars);
            Object returned = executableScript.run();
            if (returned == null) {
                newBuckets.add(bucket);
            } else {
                if (!(returned instanceof Number)) {
                    throw new AggregationExecutionException("series_arithmetic script for reducer [" + name()
                            + "] must return a Number");
                }
                final List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false).map((p) -> {
                    return (InternalAggregation) p;
                }).collect(Collectors.toList());
                aggs.add(new InternalSimpleValue(name(), ((Number) returned).doubleValue(), formatter,
                        new ArrayList<>(), metaData()));
                InternalMultiBucketAggregation.InternalBucket newBucket = originalAgg.createBucket(new InternalAggregations(aggs),
                        (InternalMultiBucketAggregation.InternalBucket) bucket);
                newBuckets.add(newBucket);
            }
        }
    }
    return originalAgg.create(newBuckets);
}
 
Example 52
Project: aws-sdk-java-v2   File: DefaultNamingStrategy.java   Source Code and License 4 votes vote down vote up
@Override
public String getJavaClassName(String shapeName) {
    return Arrays.stream(shapeName.split("[._-]|\\W")).map(Utils::capitialize).collect(Collectors.joining());
}
 
Example 53
Project: Nadia   File: DependencyMatrix.java   Source Code and License 4 votes vote down vote up
public List<Integer> getFromParentDependencyList(int nodeId)
{
	return IntStream.range(0, this.dependencyMatrixSize).filter(i -> i != nodeId && this.dependencyMatrix[i][nodeId] != 0)
														.boxed().collect(Collectors.toList());
}
 
Example 54
Project: atlas   File: ApkInjectInfoCreator.java   Source Code and License 4 votes vote down vote up
private static List<String> concatList(List<String> listOne, List<String> listTwo) {
    return Stream.concat(listOne.stream(), listTwo.stream())
        .distinct()
        .collect(Collectors.toList());
}
 
Example 55
Project: oreilly-reactive-architecture-old   File: Coffee.java   Source Code and License 4 votes vote down vote up
static Coffee orderOther(final Coffee coffee) {
    Random rnd = new Random();
    List<Coffee> filtered = COFFEES.stream().filter(c -> !c.equals(coffee)).collect(Collectors.toList());
    return filtered.get(rnd.nextInt(filtered.size()));
}
 
Example 56
Project: charts   File: Converter.java   Source Code and License 4 votes vote down vote up
public List<Unit> getAvailableUnits(final Category UNIT_DEFINITION) {
    return getAllUnitDefinitions().get(UNIT_DEFINITION).stream().map(unitDefinition -> unitDefinition.UNIT).collect(Collectors.toList());
}
 
Example 57
Project: arquillian-reporter   File: ReportGeneratorUtils.java   Source Code and License 4 votes vote down vote up
public static List<Entry> getSetOfEntries(int startIndex, int endIndex) {
    return IntStream.range(startIndex, endIndex).mapToObj(index -> getKeyValueEntryWitIndex(index))
        .collect(Collectors.toList());
}
 
Example 58
Project: J-Cord   File: Client.java   Source Code and License 4 votes vote down vote up
@Override
public List<IRelationship> getRelationships(IRelationship.Type type) {
    return relationships.stream().filter(r -> r.getType().equals(type)).collect(Collectors.toList());
}
 
Example 59
Project: autorest-streaming-example   File: Servlet.java   Source Code and License 4 votes vote down vote up
public static String read(HttpServletRequest input) throws IOException {
    try (BufferedReader reader = input.getReader()) {
        return reader.lines().collect(Collectors.joining("\n"));
    }
}
 
Example 60
Project: rejoiner   File: SchemaProviderModule.java   Source Code and License 4 votes vote down vote up
@Override
public GraphQLSchema get() {
  Map<String, ? extends Function<String, Object>> nodeDataFetchers =
      this.nodeDataFetchers
          .stream()
          .collect(Collectors.toMap(e -> e.getClassName(), Function.identity()));

  GraphQLObjectType.Builder queryType =
      newObject().name("QueryType").fields(Lists.newArrayList(queryFields));

  ProtoRegistry protoRegistry =
      ProtoRegistry.newBuilder().addAll(fileDescriptors).add(modifications).build();

  if (protoRegistry.hasRelayNode()) {
    queryType.field(
        new Relay()
            .nodeField(
                protoRegistry.getRelayNode(),
                environment -> {
                  String id = environment.getArgument("id");
                  Relay.ResolvedGlobalId resolvedGlobalId = new Relay().fromGlobalId(id);
                  Function<String, ?> stringFunction =
                      nodeDataFetchers.get(resolvedGlobalId.getType());
                  if (stringFunction == null) {
                    throw new RuntimeException(
                        String.format(
                            "Relay Node fetcher not implemented for type=%s",
                            resolvedGlobalId.getType()));
                  }
                  return stringFunction.apply(resolvedGlobalId.getId());
                }));
  }

  if (mutationFields.isEmpty()) {
    return GraphQLSchema.newSchema().query(queryType).build(protoRegistry.listTypes());
  }
  GraphQLObjectType mutationType =
      newObject().name("MutationType").fields(Lists.newArrayList(mutationFields)).build();
  return GraphQLSchema.newSchema()
      .query(queryType)
      .mutation(mutationType)
      .build(protoRegistry.listTypes());
}