@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"; }
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 ) ); }
/** * 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() + "}"; }
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(" "))); }
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))); }); }
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())); }
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))); } } }
@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)); } }
/** * 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); }
@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"; }
@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); }
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; }
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(); } } }
/** * @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; } }
@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()); }
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)); }
@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()); }
/** * 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 }; }
@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); }
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()); }
@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()); }
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); }
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()); }
/** * 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()); }
/** * 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(",")) + "]"; }
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; }
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()); }
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)); } }
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; }
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()); }
@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()); }
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; }
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"); }
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()); }
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()); }
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()); }
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(); }
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 ) ); }
/** * 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()); }
@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()); } } }