List of usage examples for java.util Collection stream
default Stream<E> stream()
From source file:ijfx.core.imagedb.DefaultExplorerService.java
@Override public synchronized Collection<? extends ImageRecord> getRecordsFromDirectory(ProgressHandler handler, File directory) {// ww w . jav a2 s.c o m List<ImageRecord> records = new ArrayList<>(); statusService.showStatus(1, 10, "Analyzing folder : " + directory.getName()); Collection<File> files = getAllImagesFromDirectory(directory); int count = 0; int total = files.size(); handler.setTotal(total); List<ImageRecord> collect = files.stream().map(f -> { handler.increment(1.0); try { return getRecord(f); } catch (Exception e) { return null; } }).filter(record -> record != null).collect(Collectors.toList()); return collect; }
From source file:it.unibo.alchemist.boundary.monitors.SAPERENearestNodeSampler.java
@Override protected double[] getProperties(final Environment<List<? extends ILsaMolecule>> env, final Position pos, final Reaction<List<? extends ILsaMolecule>> r, final Time time, final long step) { if (mobility || !HashUtils.pointerEquals(env, envCache)) { pnCache.clear();/*www. jav a 2 s.com*/ envCache = env; } if (!HashUtils.pointerEquals(propertyCache, property)) { propertyCache = property; properties.clear(); final StringTokenizer tk = new StringTokenizer(propertyCache, propertySeparators); while (tk.hasMoreElements()) { properties.add(tk.nextToken()); } } if (!HashUtils.pointerEquals(lsaCache, lsa)) { lsaCache = lsa; mol = sapere.createMolecule(lsaCache); } if (env.getNodesNumber() > 0 && mol != null) { final double[] res = new double[properties.size()]; int i = 0; Node<List<? extends ILsaMolecule>> node = pnCache.get(pos); if (node == null) { double range = Arrays.stream(env.getSize()).reduce(1, (x, y) -> FastMath.max(x, y) / FastMath.sqrt(env.getNodesNumber())); Collection<Node<List<? extends ILsaMolecule>>> neighs = env.getNodesWithinRange(pos, range); while (neighs.isEmpty()) { range *= 2; neighs = env.getNodesWithinRange(pos, range); } node = neighs.stream().reduce( (n1, n2) -> env.getPosition(n1).getDistanceTo(pos) < env.getPosition(n2).getDistanceTo(pos) ? n1 : n2) .get(); pnCache.put(pos, node); } for (final String prop : properties) { /* * Take the nearest node */ res[i++] = sapere.getProperty(node, mol, prop); } return res; } return new double[0]; }
From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogService.java
private Collection<User> fillRoles(Collection<User> users) { return users.stream().map(this::fillRoles).collect(Collectors.toList()); }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateUserAuthenticationConverter.java
/** * {@inheritDoc}/*from ww w .ja va2s . co m*/ */ //TODO: might be too much unnecessary validation in here @Override public Authentication extractAuthentication(final Map<String, ?> map) { // Make sure we have a client id to use as the Principle if (!map.containsKey(CLIENT_ID_KEY)) { throw new InvalidTokenException("No client id key found in map"); } final Object clientIdObject = map.get(CLIENT_ID_KEY); if (!(clientIdObject instanceof String)) { throw new InvalidTokenException("Client id wasn't string"); } final String userName = (String) clientIdObject; if (StringUtils.isBlank(userName)) { throw new InvalidTokenException("Client id was blank. Unable to use as user name"); } // Scopes were already validated in PingFederateRemoteTokenServices final Object scopeObject = map.get(SCOPE_KEY); if (!(scopeObject instanceof Collection)) { throw new InvalidTokenException("Scopes were not a collection"); } @SuppressWarnings("unchecked") final Collection<String> scopes = (Collection<String>) scopeObject; if (scopes.isEmpty()) { throw new InvalidTokenException("No scopes available. Unable to authenticate"); } // Default to user role final Set<GrantedAuthority> authorities = Sets.newHashSet(USER_AUTHORITY); scopes.stream().filter(scope -> scope.contains(GENIE_PREFIX)).distinct() .forEach(scope -> authorities.add(new SimpleGrantedAuthority( ROLE_PREFIX + StringUtils.removeStartIgnoreCase(scope, GENIE_PREFIX).toUpperCase()))); return new UsernamePasswordAuthenticationToken(userName, "N/A", authorities); }
From source file:org.trustedanalytics.servicecatalog.unit.ServiceInstancesControllerTest.java
@Test public void getAllServiceInstances_withoutServiceFilter_returnAllServiceInstancesFromCloudfoundry() { UUID service = null;/*from w w w .java2 s . c o m*/ ServiceInstanceMetadata metadata = new ServiceInstanceMetadata(UUID.randomUUID(), "test-user"); when(serviceInstanceRegistry.getInstanceCreator(any(UUID.class))).thenReturn(metadata); Collection<ServiceInstance> allNotFilteredServiceInstances = ServiceInstancesTestsResources .allNotFilteredServiceInstances(); Collection<ServiceInstance> serviceInstances = sut.getAllServiceInstances(SPACE_GUID, null); List<UUID> expectedGuids = allNotFilteredServiceInstances.stream().map(i -> i.getGuid()) .collect(Collectors.toList()); List<UUID> resultGuids = serviceInstances.stream().map(i -> i.getGuid()).collect(Collectors.toList()); assertEquals(expectedGuids, resultGuids); verify(ccClient).getSpaceSummary(SPACE_GUID); }
From source file:com.openshift.internal.restclient.model.v1.ReplicationControllerTest.java
public void testGetEnvironmentVariablesWithValueFrom() { Collection<IEnvironmentVariable> envVars = rc.getEnvironmentVariables(); //fieldref// w w w. j a v a2 s. c o m Optional<IEnvironmentVariable> envVar = envVars.stream() .filter(e -> "OPENSHIFT_KUBE_PING_NAMESPACE".equals(e.getName())).findFirst(); assertTrue("Exp. to find env var", envVar.isPresent()); IEnvVarSource from = envVar.get().getValueFrom(); assertTrue(from instanceof IObjectFieldSelector); IObjectFieldSelector selector = (IObjectFieldSelector) from; assertEquals("v1", selector.getApiVersion()); assertEquals("metadata.namespace", selector.getFieldPath()); //configmapkeyref envVar = envVars.stream().filter(e -> "OPENSHIFT_CONFIGMAP_KEY_REF".equals(e.getName())).findFirst(); assertTrue("Exp. to find env var", envVar.isPresent()); from = envVar.get().getValueFrom(); assertTrue(from instanceof IConfigMapKeySelector); IConfigMapKeySelector configSelector = (IConfigMapKeySelector) from; assertEquals("xyz", configSelector.getName()); assertEquals("abc123", configSelector.getKey()); //secretkeyref envVar = envVars.stream().filter(e -> "OPENSHIFT_SECRET_KEY_REF".equals(e.getName())).findFirst(); assertTrue("Exp. to find env var", envVar.isPresent()); from = envVar.get().getValueFrom(); assertTrue(from instanceof ISecretKeySelector); ISecretKeySelector secretKeySelector = (ISecretKeySelector) from; assertEquals("bar", secretKeySelector.getName()); assertEquals("foo", secretKeySelector.getKey()); }
From source file:com.github.horrorho.liquiddonkey.cloud.client.FileGroupsClient.java
public List<ICloud.MBSFileAuthToken> getFiles(HttpClient client, String dsPrsID, String mmeAuthToken, String mobileBackupUrl, String udid, String snapshot, Collection<ICloud.MBSFile> files) throws BadDataException, IOException { logger.trace("<< getFiles() < dsPrsID: {} udid: {} snapshot: {} files: {}", dsPrsID, udid, snapshot, files.size());//from w w w. j a v a 2s . c o m logger.debug(marker, "-- getFiles() < files: {}", files); List<ICloud.MBSFile> postData = files.stream() .map(file -> ICloud.MBSFile.newBuilder().setFileID(file.getFileID()).build()) .collect(Collectors.toList()); byte[] encoded; try { encoded = ProtoBufArray.encode(postData); } catch (IOException ex) { throw new BadDataException(ex); } String uri = path(mobileBackupUrl, "mbs", dsPrsID, udid, snapshot, "getFiles"); HttpPost post = new HttpPost(uri); headers.mobileBackupHeaders(dsPrsID, mmeAuthToken).stream().forEach(post::addHeader); post.setEntity(new ByteArrayEntity(encoded)); List<ICloud.MBSFileAuthToken> tokens = client.execute(post, mbsFileAuthTokenListHandler); logger.debug(marker, "-- getFiles() > tokens: {}", tokens); logger.trace(">> getFiles() > {}", tokens.size()); return tokens; }
From source file:io.klerch.alexa.state.handler.AlexaSessionStateHandler.java
@Override public void removeModels(Collection<AlexaStateModel> models) throws AlexaStateException { Validate.notNull(models, "Collection of models to be removed must not be null."); final List<String> ids = models.stream().map(AlexaStateModel::getAttributeKey).collect(Collectors.toList()); removeValues(ids);/*from ww w. j a va 2 s . c o m*/ }
From source file:fi.vrk.xroad.catalog.collector.actors.ListClientsActorTest.java
@Test public void testOnReceive() throws Exception { List<ClientType> memberlist = new ArrayList<>(); memberlist.add(createClientType(XRoadObjectType.MEMBER, "member1", null)); memberlist.add(createClientType(XRoadObjectType.SUBSYSTEM, "member1", "sub1")); memberlist.add(createClientType(XRoadObjectType.SUBSYSTEM, "member1", "sub2")); memberlist.add(createClientType(XRoadObjectType.SUBSYSTEM, "member1", "sub3")); memberlist.add(createClientType(XRoadObjectType.MEMBER, "member2", null)); memberlist.add(createClientType(XRoadObjectType.SUBSYSTEM, "member2", "sssub1")); memberlist.add(createClientType(XRoadObjectType.SUBSYSTEM, "member2", "sssub2")); ClientList cMock = mock(ClientList.class); doReturn(cMock).when(restOperations).getForObject("http://localhost/listClients", ClientList.class); when(cMock.getMember()).thenReturn(memberlist); // doNothing().when(listMethodsPoolRef).tell(Matchers.anyObject(), Matchers.anyObject()); // doNothing().when(listMethodsPoolRef).tell(Matchers.any(ClientType.class), Matchers.any(ActorRef.class)); // Call onReceive listClientsActor.onReceive(ListClientsActor.START_COLLECTING); Set<Member> expectedMembers = new HashSet<>(); Member member1 = new Member("FI", "GOV", "member1", "member1"); Set<Subsystem> subsystems = new HashSet<>(); subsystems.add(new Subsystem(member1, "sub1")); subsystems.add(new Subsystem(member1, "sub2")); subsystems.add(new Subsystem(member1, "sub3")); member1.setSubsystems(subsystems);/* w w w .j av a 2 s . c o m*/ Member member2 = new Member("FI", "GOV", "member2", "member2"); subsystems = new HashSet<>(); subsystems.add(new Subsystem(member2, "sssub1")); subsystems.add(new Subsystem(member2, "sssub2")); member2.setSubsystems(subsystems); expectedMembers.add(member1); expectedMembers.add(member2); // Verify that the save method was called with correct member collection verify(catalogService).saveAllMembersAndSubsystems(argumentCaptor.capture()); Collection<Member> resultMembers = argumentCaptor.getValue(); Assert.assertEquals(HashMultiset.create(expectedMembers), HashMultiset.create(resultMembers)); Assert.assertEquals(HashMultiset.create(member1.getAllSubsystems()), HashMultiset .create(resultMembers.stream().filter(m -> member1.equals(m)).findAny().get().getAllSubsystems())); Assert.assertEquals(HashMultiset.create(member2.getAllSubsystems()), HashMultiset .create(resultMembers.stream().filter(m -> member2.equals(m)).findAny().get().getAllSubsystems())); }