List of usage examples for java.util.stream Collectors toMap
public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)
From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBeanTest.java
public void testDoModifyXslExport() throws AccessDeniedException { MockHttpServletRequest request = new MockHttpServletRequest(); AdminUser user = new AdminUser(); user.setRoles(/*from w ww . j a v a 2 s . co m*/ AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity()))); Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT); String randomName = getRandomName(); Map<String, String[]> parameters = new HashMap<>(); parameters.put("title", new String[] { randomName }); parameters.put("description", new String[] { randomName }); parameters.put("extension", new String[] { randomName }); parameters.put("id_xsl_export", new String[] { Integer.toString(_xslExport.getIdXslExport()) }); parameters.put(SecurityTokenService.PARAMETER_TOKEN, new String[] { SecurityTokenService.getInstance().getToken(request, "admin/xsl/modify_xsl_export.html") }); Map<String, List<FileItem>> multipartFiles = new HashMap<>(); _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT); _instance.doModifyXslExport(new MultipartHttpServletRequest(request, multipartFiles, parameters)); XslExport stored = XslExportHome.findByPrimaryKey(_xslExport.getIdXslExport()); assertNotNull(stored); assertEquals(randomName, stored.getTitle()); assertEquals(randomName, stored.getDescription()); assertEquals(randomName, stored.getExtension()); }
From source file:io.pravega.controller.store.stream.ZKStream.java
@Override public CompletableFuture<Map<String, Data<Integer>>> getCurrentTxns() { return getActiveEpoch(false).thenCompose(epoch -> store.getChildren(getEpochPath(epoch.getKey())) .thenCompose(txIds -> FutureHelpers .allOfWithResults(txIds.stream().collect(Collectors.toMap(txId -> txId, txId -> cache.getCachedData(getActiveTxPath(epoch.getKey(), txId))))))); }
From source file:eu.itesla_project.modules.validation.OfflineValidationTool.java
private static void writeCsv(Map<String, Map<RuleId, ValidationStatus>> statusPerRulePerCase, Map<String, Map<RuleId, Map<HistoDbAttributeId, Object>>> valuesPerRulePerCase, Path outputDir) throws IOException { Set<RuleId> rulesIds = new TreeSet<>(); statusPerRulePerCase.values().stream().forEach(e -> rulesIds.addAll(e.keySet())); writeComparisonFiles(rulesIds, statusPerRulePerCase, outputDir); writeAttributesFiles(rulesIds, valuesPerRulePerCase, outputDir); List<String> categories = Arrays.asList(toCategory(OK_S, OK_R), toCategory(OK_S, NOK_R), toCategory(NOK_S, OK_R), toCategory(NOK_S, NOK_R), toCategory(OK_S, UNDEF_R), toCategory(NOK_S, UNDEF_R), toCategory(UNDEF_S, OK_R), toCategory(UNDEF_S, NOK_R), toCategory(UNDEF_S, UNDEF_R)); Map<RuleId, Map<String, AtomicInteger>> synthesisPerRule = new HashMap<>(); for (RuleId ruleId : rulesIds) { synthesisPerRule.put(ruleId,/*from w w w . j a va2s.c om*/ categories.stream().collect(Collectors.toMap(Function.identity(), e -> new AtomicInteger()))); } for (Map.Entry<String, Map<RuleId, ValidationStatus>> e : statusPerRulePerCase.entrySet()) { Map<RuleId, ValidationStatus> statusPerRule = e.getValue(); for (RuleId ruleId : rulesIds) { ValidationStatus status = statusPerRule.get(ruleId); String category = toCategory(status.isSimulationOkToStr(), status.isRuleOkToStr()); synthesisPerRule.get(ruleId).get(category).incrementAndGet(); } } writeSynthesisFile(synthesisPerRule, categories, outputDir.resolve("synthesis.csv")); }
From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java
private Creatable<VirtualMachine> prepareVitualMachine(Instance instance, Azure azureService, ResourceGroup resourceGroup, Region region, String instanceTag, VirtualMachineCustomImage image, Creatable<NetworkInterface> creatableNetworkInterface) { // Configure the VM depending on the OS type VirtualMachine.DefinitionStages.WithFromImageCreateOptionsManaged creatableVirtualMachineWithImage; OperatingSystemTypes operatingSystemType = image.osDiskImage().osType(); if (operatingSystemType.equals(OperatingSystemTypes.LINUX)) { creatableVirtualMachineWithImage = configureLinuxVirtualMachine(azureService, instanceTag, region, resourceGroup, instance.getCredentials(), image, creatableNetworkInterface); } else if (operatingSystemType.equals(OperatingSystemTypes.WINDOWS)) { creatableVirtualMachineWithImage = configureWindowsVirtualMachine(azureService, instanceTag, region, resourceGroup, instance.getCredentials(), image, creatableNetworkInterface); } else {//from www . j a v a2s . c om throw new RuntimeException( "ERROR Operating System of type '" + operatingSystemType.toString() + "' is not yet supported"); } // Set VM size (or type) and name of OS' disk Optional<String> optionalHardwareType = Optional.ofNullable(instance.getHardware()).map(Hardware::getType); VirtualMachine.DefinitionStages.WithCreate creatableVMWithSize = creatableVirtualMachineWithImage .withSize(new VirtualMachineSizeTypes(optionalHardwareType.orElse(DEFAULT_VM_SIZE.toString()))) .withOsDiskName(createUniqOSDiskName(instanceTag)); // Add init script(s) using dedicated Microsoft extension Optional.ofNullable(instance.getInitScript()).map(InstanceScript::getScripts).ifPresent(scripts -> { if (scripts.length > 0) { StringBuilder concatenatedScripts = new StringBuilder(); Lists.newArrayList(scripts) .forEach(script -> concatenatedScripts.append(script).append(SCRIPT_SEPARATOR)); creatableVMWithSize.defineNewExtension(createUniqueScriptName(instanceTag)) .withPublisher(SCRIPT_EXTENSION_PUBLISHER).withType(SCRIPT_EXTENSION_TYPE) .withVersion(SCRIPT_EXTENSION_VERSION).withMinorVersionAutoUpgrade() .withPublicSetting(SCRIPT_EXTENSION_CMD_KEY, concatenatedScripts.toString()).attach(); } }); // Set tags return creatableVMWithSize.withTags(tagManager.retrieveAllTags(instance.getOptions()).stream() .collect(Collectors.toMap(Tag::getKey, Tag::getValue))); }
From source file:com.github.sevntu.checkstyle.ordering.MethodOrder.java
private static Map<ResolvedCall, MethodInvocation> getAllInvocations(Dependencies dependencies, Map<String, Method> methods) { return dependencies.getResolvedCalls().stream() .collect(Collectors.toMap(Function.identity(), resolvedCall -> { final String callerSignature = resolvedCall.getCaller().getSignature(); final String calleeSignature = resolvedCall.getCallee().getSignature(); return new MethodInvocation(resolvedCall, methods.get(callerSignature), methods.get(calleeSignature)); }));/*from w w w . j av a 2 s .c om*/ }
From source file:ch.algotrader.service.tt.TTFixReferenceDataServiceImpl.java
private void retrieveFutures(final FutureFamily securityFamily, final List<TTSecurityDefVO> securityDefs) { // get all current futures List<Future> allFutures = this.futureDao.findBySecurityFamily(securityFamily.getId()); Map<String, Future> mapByTtid = allFutures.stream().filter(e -> e.getTtid() != null) .collect(Collectors.toMap(e -> e.getTtid(), e -> e)); Map<String, Future> mapBySymbol = allFutures.stream().collect(Collectors.toMap(e -> e.getSymbol(), e -> e)); for (TTSecurityDefVO securityDef : securityDefs) { String type = securityDef.getType(); if (!type.equalsIgnoreCase("FUT")) { throw new ServiceException("Unexpected security definition type for future: " + type); }/*from w w w.j av a 2 s . com*/ String id = securityDef.getId(); if (!mapByTtid.containsKey(id)) { LocalDate maturityDate = securityDef.getMaturityDate(); LocalDate expiration = maturityDate.withDayOfMonth(1); // IPE e-Brent has to be handled as a special case as it happens to have multiple contracts // with the same expiration month String symbol; if ("ICE_IPE".equalsIgnoreCase(securityDef.getExchange()) && securityDef.getAltSymbol() != null) { String altSymbol = securityDef.getAltSymbol(); if (altSymbol.startsWith("Q") || altSymbol.startsWith("Cal")) { continue; } else { try { TemporalAccessor parsed = ICE_IPE_SYMBOL.parse(altSymbol); int year = parsed.get(ChronoField.YEAR); int month = parsed.get(ChronoField.MONTH_OF_YEAR); expiration = LocalDate.of(year, month, 1); symbol = FutureSymbol.getSymbol(securityFamily, expiration, this.commonConfig.getFutureSymbolPattern()); } catch (DateTimeParseException ex) { throw new ServiceException( "Unable to parse IPE e-Brent expiration month / year: " + altSymbol, ex); } } } else { symbol = FutureSymbol.getSymbol(securityFamily, maturityDate, this.commonConfig.getFutureSymbolPattern()); } if (!mapBySymbol.containsKey(symbol)) { Future future = Future.Factory.newInstance(); String isin = securityFamily.getIsinRoot() != null ? FutureSymbol.getIsin(securityFamily, maturityDate) : null; String ric = securityFamily.getRicRoot() != null ? FutureSymbol.getRic(securityFamily, maturityDate) : null; future.setSymbol(symbol); future.setIsin(isin); future.setRic(ric); future.setTtid(id); future.setExpiration(DateTimeLegacy.toLocalDate(expiration)); future.setMonthYear(DateTimePatterns.MONTH_YEAR.format(maturityDate)); future.setSecurityFamily(securityFamily); future.setUnderlying(securityFamily.getUnderlying()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating future based on TT definition: {} {}", securityDef.getSymbol(), securityDef.getMaturityDate()); } this.futureDao.save(future); } else { Future future = mapBySymbol.get(symbol); future.setTtid(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Updating future based on TT definition: {} {}", securityDef.getSymbol(), securityDef.getMaturityDate()); } } } } }
From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java
@Override @Transactional/* ww w .j a v a 2 s. com*/ public Map<String, StockProduct> gatherAsMap(String[] stockProductId) { List<StockProduct> stockProducts = gather(stockProductId); return stockProducts.stream().collect(Collectors.toMap(StockProduct::getId, i -> i)); }
From source file:com.uber.hoodie.common.util.TestCompactionUtils.java
private Map<String, Pair<String, HoodieCompactionOperation>> generateExpectedCompactionOperations( List<HoodieCompactionPlan> plans) { return plans.stream().flatMap(plan -> { if (plan.getOperations() != null) { return plan.getOperations().stream() .map(op -> Pair.of(op.getFileId(), Pair.of(op.getBaseInstantTime(), op))); }/* ww w.j a v a 2 s .co m*/ return Stream.empty(); }).collect(Collectors.toMap(Pair::getKey, Pair::getValue)); }
From source file:com.okta.swagger.codegen.OktaJavaClientImplCodegen.java
@Override protected void buildDiscriminationMap(Swagger swagger) { super.buildDiscriminationMap(swagger); Map<String, Object> rootConfigMap = new HashMap<>(); Map<String, Object> destMap = new HashMap<>(); rootConfigMap.put("config", destMap); discriminatorMap.values().forEach(disc -> { String fqn = toModelImport(disc.getParentDefName()); String fieldName = disc.getFieldName(); Map<String, String> valueMap = disc.getValueDefMap().entrySet().stream() .collect(Collectors.toMap(e -> e.getValue(), e -> toModelImport(e.getKey()))); Map<String, Object> entries = new HashMap<>(); entries.put("fieldName", fieldName); entries.put("values", valueMap); destMap.put(fqn, entries);/* w w w . java 2 s .c o m*/ }); // now dump this to yaml // cheat a little here because we are assuming we are using maven, replace the LAST index of /target/ (the // release process will have two 'target' directories in the path String mavenTargetDir = outputFolder().substring(0, outputFolder.lastIndexOf("/target/") + 8); File destFile = new File(new File(mavenTargetDir), "generated-resources/swagger/" + overrideModelPackage.replace('.', '/') + "/discrimination.yaml"); boolean folderCreated = destFile.getParentFile().mkdirs(); if (!folderCreated && !destFile.getParentFile().exists()) { throw new RuntimeException( "Directory does not exist and could not be created: " + destFile.getParentFile()); } try (OutputStream outputStream = new FileOutputStream(destFile)) { Yaml yaml = new Yaml(); Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); yaml.dump(rootConfigMap, writer); } catch (IOException e) { throw new RuntimeException("Failed to write discrimination map to yaml: " + destFile.getAbsolutePath(), e); } }
From source file:com.vaadin.framework8.samples.SpringCrudIT.java
private void checkCategories(WebElement form, Product product) { WebElement categories = form.findElement(By.className("v-select-optiongroup")); WebElement captionElement = categories.findElement(By.xpath("..")).findElement(By.className("v-caption")); Assert.assertEquals("Categories", captionElement.getText()); List<WebElement> checkboxes = categories.findElements(By.className("v-checkbox")); Set<String> cats = checkboxes.stream().map(WebElement::getText).collect(Collectors.toSet()); Set<String> allCats = dataService.getAllCategories().stream().map(Category::getName) .collect(Collectors.toSet()); Assert.assertEquals(allCats, cats);/*from ww w . j a v a 2 s.c o m*/ Map<String, Category> productCategories = product.getCategory().stream() .collect(Collectors.toMap(Category::getName, Function.identity())); checkboxes.stream().forEach(checkbox -> checkCategory(checkbox, productCategories)); }