use of java.util.Collections in project pravega by pravega.
the class CollectionHelpersTests method testJoinCollections.
/**
* Tests the joinCollections() method.
*/
@Test
public void testJoinCollections() {
AssertExtensions.assertContainsSameElements("Empty set.", Collections.<Integer>emptySet(), CollectionHelpers.joinCollections(Collections.<Integer>emptySet(), i -> i, Collections.<Integer>emptySet(), i -> i));
AssertExtensions.assertContainsSameElements("Empty+non-empty.", Arrays.asList(1, 2, 3), CollectionHelpers.joinCollections(Collections.<Integer>emptySet(), i -> i, Arrays.asList("1", "2", "3"), Integer::parseInt));
AssertExtensions.assertContainsSameElements("Non-empty+empty.", Arrays.asList(1, 2, 3), CollectionHelpers.joinCollections(Arrays.asList("1", "2", "3"), Integer::parseInt, Collections.<Integer>emptySet(), i -> i));
AssertExtensions.assertContainsSameElements("Non-empty+non-empty.", Arrays.asList(1, 2, 3), CollectionHelpers.joinCollections(Arrays.asList("1", "3"), Integer::parseInt, Arrays.asList("2"), Integer::parseInt));
val c = CollectionHelpers.joinCollections(Arrays.asList("1", "2"), Integer::parseInt, Arrays.asList("2", "3"), Integer::parseInt);
AssertExtensions.assertContainsSameElements("Non-empty+non-empty(duplicates).", Arrays.asList(1, 2, 2, 3), c);
// Now test the iterator.
val copy = new ArrayList<Integer>(c);
AssertExtensions.assertContainsSameElements("Non-empty+non-empty(duplicates, copy).", c, copy);
}
use of java.util.Collections in project pravega by pravega.
the class ControllerEventProcessors method handleOrphanedReaders.
private CompletableFuture<Void> handleOrphanedReaders(final EventProcessorGroup<? extends ControllerEvent> group, final Supplier<Set<String>> processes) {
return withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
try {
return group.getProcesses();
} catch (CheckpointStoreException e) {
if (e.getType().equals(CheckpointStoreException.Type.NoNode)) {
return Collections.<String>emptySet();
}
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor).thenComposeAsync(groupProcesses -> withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
try {
return new ImmutablePair<>(processes.get(), groupProcesses);
} catch (Exception e) {
log.error(String.format("Error fetching current processes%s", group.toString()), e);
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)).thenComposeAsync(pair -> {
Set<String> activeProcesses = pair.getLeft();
Set<String> registeredProcesses = pair.getRight();
if (registeredProcesses == null || registeredProcesses.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
if (activeProcesses != null) {
registeredProcesses.removeAll(activeProcesses);
}
List<CompletableFuture<Void>> futureList = new ArrayList<>();
for (String process : registeredProcesses) {
futureList.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
try {
group.notifyProcessFailure(process);
} catch (CheckpointStoreException e) {
log.error(String.format("Error notifying failure of process=%s in event processor group %s", process, group.toString()), e);
throw new CompletionException(e);
}
}, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
}
return Futures.allOf(futureList);
});
}
use of java.util.Collections in project photon-model by vmware.
the class AWSComputeStateCreationAdapterService method addUpdateOrRemoveNICStates.
/**
* From the previously calculated NICs delta (based on whether the local state correspond to
* existing AWS object, the AWS object was deleted, or a new AWS object was added): 1) Create,
* update or delete NICState objects 2) Update the CS's references to the added or removed
* NetworkInterfaceStates
*/
private Map<String, Map<String, Collection<Object>>> addUpdateOrRemoveNICStates(AWSComputeStateCreationContext context, Instance instance, Map<String, List<Integer>> nicsDeviceIndexDeltaMap, String existingEndpointLink, Set<String> endpointLinks) {
List<NetworkInterfaceState> existingNicStates = context.request.nicStatesToBeUpdated.get(instance.getInstanceId());
// Generate operation for adding NIC state and description, and retain its link to add to
// the CS
List<Integer> deviceIndexesToAdd = nicsDeviceIndexDeltaMap.get(ADD_NIC_STATES);
Collection<Object> networkInterfaceLinksToBeAdded = instance.getNetworkInterfaces().stream().filter(awsNic -> deviceIndexesToAdd.contains(awsNic.getAttachment().getDeviceIndex()) && context.request.enumeratedNetworks != null && context.request.enumeratedNetworks.subnets != null && context.request.enumeratedNetworks.subnets.containsKey(awsNic.getSubnetId())).map(awsNic -> createNICStateAndDescription(context, awsNic, existingEndpointLink, endpointLinks)).map(addedNicState -> UriUtils.buildUriPath(NetworkInterfaceService.FACTORY_LINK, addedNicState.documentSelfLink)).collect(Collectors.toList());
// Generate operation for removing NIC states, and retain its link to remove from the CS {{
List<Integer> deviceIndexesToRemove = nicsDeviceIndexDeltaMap.get(REMOVE_NIC_STATES);
Collection<Object> networkInterfaceLinksToBeRemoved = deviceIndexesToRemove.stream().map(deviceIndexToRemove -> {
NetworkInterfaceState stateToDelete = existingNicStates.stream().filter(existNicState -> existNicState.deviceIndex == deviceIndexToRemove).findFirst().orElse(null);
return stateToDelete;
}).filter(existingNicState -> existingNicState != null).map(existingNicState -> deleteNICState(context, existingNicState)).map(existingNicState -> existingNicState.documentSelfLink).collect(Collectors.toList());
// Generate operation for updating NIC states, no links should be updated on CS in this case
List<Integer> deviceIndexesToUpdate = nicsDeviceIndexDeltaMap.get(UPDATE_NIC_STATES);
deviceIndexesToUpdate.stream().map(deviceIndexToUpdate -> existingNicStates.stream().filter(existNicState -> existNicState.deviceIndex == deviceIndexToUpdate).findFirst().orElse(null)).filter(existingNicState -> existingNicState != null).forEach(existingNicState -> updateNICState(context, instance, existingNicState));
if (context.request.nicStatesToBeDeleted.size() > 0 && context.request.nicStatesToBeDeleted.get(instance.getInstanceId()) != null) {
this.logInfo(() -> String.format("Compute %s failed to discover %d nics", instance.getInstanceId(), context.request.nicStatesToBeDeleted.get(instance.getInstanceId()).size()));
networkInterfaceLinksToBeRemoved.addAll(context.request.nicStatesToBeDeleted.get(instance.getInstanceId()));
}
Map<String, Map<String, Collection<Object>>> nicsDeltaMap = new HashMap<>();
// only add the collections to the delta map in case there is something to add/remove
if (!networkInterfaceLinksToBeRemoved.isEmpty()) {
Map<String, Collection<Object>> collectionsToRemoveMap = new HashMap<>();
collectionsToRemoveMap.put(ComputeState.FIELD_NAME_NETWORK_INTERFACE_LINKS, networkInterfaceLinksToBeRemoved);
nicsDeltaMap.put(REMOVE_NIC_STATES, collectionsToRemoveMap);
}
if (!networkInterfaceLinksToBeAdded.isEmpty()) {
Map<String, Collection<Object>> collectionsToAddMap = new HashMap<>();
collectionsToAddMap.put(ComputeState.FIELD_NAME_NETWORK_INTERFACE_LINKS, networkInterfaceLinksToBeAdded);
nicsDeltaMap.put(ADD_NIC_STATES, collectionsToAddMap);
}
return nicsDeltaMap;
}
use of java.util.Collections in project syncope by apache.
the class PropagationManagerImpl method createTasks.
/**
* Create propagation tasks.
*
* @param any to be provisioned
* @param password clear text password to be provisioned
* @param changePwd whether password should be included for propagation attributes or not
* @param enable whether user must be enabled or not
* @param deleteOnResource whether any must be deleted anyway from external resource or not
* @param propByRes operation to be performed per resource
* @param vAttrs virtual attributes to be set
* @return list of propagation tasks created
*/
protected List<PropagationTaskTO> createTasks(final Any<?> any, final String password, final boolean changePwd, final Boolean enable, final boolean deleteOnResource, final PropagationByResource propByRes, final Collection<AttrTO> vAttrs) {
LOG.debug("Provisioning {}:\n{}", any, propByRes);
// Avoid duplicates - see javadoc
propByRes.purge();
LOG.debug("After purge {}:\n{}", any, propByRes);
// Virtual attributes
Set<String> virtualResources = new HashSet<>();
virtualResources.addAll(propByRes.get(ResourceOperation.CREATE));
virtualResources.addAll(propByRes.get(ResourceOperation.UPDATE));
virtualResources.addAll(dao(any.getType().getKind()).findAllResourceKeys(any.getKey()));
Map<String, Set<Attribute>> vAttrMap = new HashMap<>();
if (vAttrs != null) {
vAttrs.forEach(vAttr -> {
VirSchema schema = virSchemaDAO.find(vAttr.getSchema());
if (schema == null) {
LOG.warn("Ignoring invalid {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
} else if (schema.isReadonly()) {
LOG.warn("Ignoring read-only {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
} else if (anyUtilsFactory.getInstance(any).getAllowedSchemas(any, VirSchema.class).contains(schema) && virtualResources.contains(schema.getProvision().getResource().getKey())) {
Set<Attribute> values = vAttrMap.get(schema.getProvision().getResource().getKey());
if (values == null) {
values = new HashSet<>();
vAttrMap.put(schema.getProvision().getResource().getKey(), values);
}
values.add(AttributeBuilder.build(schema.getExtAttrName(), vAttr.getValues()));
propByRes.add(ResourceOperation.UPDATE, schema.getProvision().getResource().getKey());
} else {
LOG.warn("{} not owned by or {} not allowed for {}", schema.getProvision().getResource(), schema, any);
}
});
}
LOG.debug("With virtual attributes {}:\n{}\n{}", any, propByRes, vAttrMap);
List<PropagationTaskTO> tasks = new ArrayList<>();
propByRes.asMap().forEach((resourceKey, operation) -> {
ExternalResource resource = resourceDAO.find(resourceKey);
Provision provision = resource == null ? null : resource.getProvision(any.getType()).orElse(null);
List<? extends Item> mappingItems = provision == null ? Collections.<Item>emptyList() : MappingUtils.getPropagationItems(provision.getMapping().getItems());
if (resource == null) {
LOG.error("Invalid resource name specified: {}, ignoring...", resourceKey);
} else if (provision == null) {
LOG.error("No provision specified on resource {} for type {}, ignoring...", resource, any.getType());
} else if (mappingItems.isEmpty()) {
LOG.warn("Requesting propagation for {} but no propagation mapping provided for {}", any.getType(), resource);
} else {
PropagationTaskTO task = new PropagationTaskTO();
task.setResource(resource.getKey());
task.setObjectClassName(provision.getObjectClass().getObjectClassValue());
task.setAnyTypeKind(any.getType().getKind());
task.setAnyType(any.getType().getKey());
if (!deleteOnResource) {
task.setEntityKey(any.getKey());
}
task.setOperation(operation);
task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey()));
Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrs(any, password, changePwd, enable, provision);
task.setConnObjectKey(preparedAttrs.getKey());
// Check if any of mandatory attributes (in the mapping) is missing or not received any value:
// if so, add special attributes that will be evaluated by PropagationTaskExecutor
List<String> mandatoryMissing = new ArrayList<>();
List<String> mandatoryNullOrEmpty = new ArrayList<>();
mappingItems.stream().filter(item -> (!item.isConnObjectKey() && JexlUtils.evaluateMandatoryCondition(item.getMandatoryCondition(), any))).forEachOrdered(item -> {
Attribute attr = AttributeUtil.find(item.getExtAttrName(), preparedAttrs.getValue());
if (attr == null) {
mandatoryMissing.add(item.getExtAttrName());
} else if (attr.getValue() == null || attr.getValue().isEmpty()) {
mandatoryNullOrEmpty.add(item.getExtAttrName());
}
});
if (!mandatoryMissing.isEmpty()) {
preparedAttrs.getValue().add(AttributeBuilder.build(PropagationTaskExecutor.MANDATORY_MISSING_ATTR_NAME, mandatoryMissing));
}
if (!mandatoryNullOrEmpty.isEmpty()) {
preparedAttrs.getValue().add(AttributeBuilder.build(PropagationTaskExecutor.MANDATORY_NULL_OR_EMPTY_ATTR_NAME, mandatoryNullOrEmpty));
}
if (vAttrMap.containsKey(resource.getKey())) {
preparedAttrs.getValue().addAll(vAttrMap.get(resource.getKey()));
}
task.setAttributes(POJOHelper.serialize(preparedAttrs.getValue()));
tasks.add(task);
LOG.debug("PropagationTask created: {}", task);
}
});
return tasks;
}
use of java.util.Collections in project syncope by apache.
the class VirSchemaDetails method getExtAttrNames.
private List<String> getExtAttrNames() {
ConnInstanceTO connInstanceTO = new ConnInstanceTO();
connInstanceTO.setKey(selectedResource.getConnector());
connInstanceTO.getConf().addAll(selectedResource.getConfOverride());
Optional<ConnIdObjectClassTO> connIdObjectClass = connRestClient.buildObjectClassInfo(connInstanceTO, false).stream().filter(object -> object.getType().equals(anyTypes.get(anyType.getModelObject()))).findAny();
return connIdObjectClass.isPresent() ? connIdObjectClass.get().getAttributes() : Collections.<String>emptyList();
}
Aggregations