use of java.util.Collections in project n4js by eclipse.
the class RunnerHelper method getProjectExtendedDepsAndApiImplMapping.
/**
* Returns a mapping from all API projects among <code>dependencies</code> to their corresponding implementation
* project for implementation ID <code>implementationId</code>.
* <p>
* Special cases: if there are no API projects among the dependencies, this method will return an empty map in
* {@link ApiUsage#concreteApiImplProjectMapping} and {@link ApiUsage#implementationIdRequired}<code>==false</code>;
* otherwise, if <code>implementationId</code> is <code>null</code>, then this method will assert that there exists
* exactly one implementation for the API projects among the dependencies and use that (stored in
* {@link ApiUsage#implementationId}).
* <p>
* Throws exception in case of error given <code>throwOnError==true</code>, never returns null.
*
* @param runtimeEnvironment
* active runtime environment.
* @param moduleToRun
* what to run.
* @param implementationId
* might be <code>null</code>
* @param throwOnError
* if true fast fail in erroneous situations. Otherwise tries to proceed in a meaningful way. State can
* then be queried on the ApiUsage instance.
*
* @return result wrapped in an {@link ApiUsage} instance.
*/
// TODO this methods could require some cleanup after the concepts of API-Implementation mappings stabilized...
public ApiUsage getProjectExtendedDepsAndApiImplMapping(RuntimeEnvironment runtimeEnvironment, URI moduleToRun, String implementationId, boolean throwOnError) {
final LinkedHashSet<IN4JSProject> deps = new LinkedHashSet<>();
// 1) add project containing the moduleToRun and its direct AND indirect dependencies
final Optional<? extends IN4JSProject> project = n4jsCore.findProject(moduleToRun);
if (project.isPresent() == false) {
throw new RuntimeException("can't obtain containing project for moduleToRun: " + moduleToRun);
}
recursiveDependencyCollector(project.get(), deps, new RecursionGuard<>());
// TODO need to add not only REs but also RLs they provide
// 2) add the runtime environment project, REs it extends and RLs provided
final Optional<IN4JSProject> reProject = getCustomRuntimeEnvironmentProject(runtimeEnvironment);
if (reProject.isPresent()) {
IN4JSProject re = reProject.get();
recursiveExtendedREsCollector(re, deps);
} else {
// IDE-1359: don't throw exception to make runners work without user-defined runtime environment
// (will be changed later when library manager is available!)
// throw new RuntimeException("can't obtain runtime environment project for " + moduleToRun2);
}
// TODO actually we would like to return the dependencies in load order:
// - RuntimeEnvironment boot
// - all RuntimeLibrary boots (take deps2 between RLs into account)
// - all other deps2 (order does not matter they just needs to be on path later)
// - project to be called
// maybe some in order DFS or something above?
// manually transform to list, or is this one ok?
final ApiImplMapping apiImplMapping = ApiImplMapping.of(deps, n4jsCore.findAllProjects());
if (apiImplMapping.hasErrors()) {
if (throwOnError)
throw new IllegalStateException("the workspace setup contains errors related to API / implementation projects (check manifests of related projects):\n " + Joiner.on("\n ").join(apiImplMapping.getErrorMessages()));
}
if (apiImplMapping.isEmpty()) {
return ApiUsage.of(new ArrayList<>(deps), Collections.<IN4JSProject, IN4JSProject>emptyMap(), apiImplMapping);
}
// there must be exactly one implementation for the API projects in the workspace
if (implementationId == null) {
final List<String> allImplIds = apiImplMapping.getAllImplIds();
if (allImplIds.size() != 1) {
if (throwOnError) {
throw new IllegalStateException("no implementationId specified while several are available in the workspace: " + allImplIds);
} else {
// back out, further processing not possible without implementations id.
return ApiUsage.of(new ArrayList<>(deps), Collections.emptyMap(), apiImplMapping, true);
}
} else {
implementationId = allImplIds.get(0);
}
}
final Map<IN4JSProject, IN4JSProject> apiImplProjectMapping = new LinkedHashMap<>();
// projectIds of projects without an implementation
final List<String> missing = new ArrayList<>();
for (IN4JSProject dep : deps) {
if (dep != null) {
final String depId = dep.getProjectId();
if (depId != null && apiImplMapping.isApi(depId)) {
// so: dep is an API project ...
final IN4JSProject impl = apiImplMapping.getImpl(depId, implementationId);
if (impl != null) {
// so: impl is the implementation project for dep for implementation ID 'implementationId'
apiImplProjectMapping.put(dep, impl);
} else {
// bad: no implementation for dep for implementation ID 'implementationId'
missing.add(depId);
}
}
}
}
if (!missing.isEmpty()) {
if (throwOnError) {
throw new IllegalStateException("no implementation for implementation ID \"" + implementationId + "\" found for the following projects: " + Joiner.on(", ").join(missing));
}
}
// / #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
// IDEBUG-506 look for additional dependencies, pulled in from api-impl project not yet processed:
HashSet<IN4JSProject> processedDepProjects = deps;
LinkedHashSet<IN4JSProject> tobeInspectedApiImplProjects = new LinkedHashSet<>();
apiImplProjectMapping.entrySet().forEach(p -> {
IN4JSProject v = p.getValue();
if (!processedDepProjects.contains(v))
tobeInspectedApiImplProjects.add(v);
});
// Collect transitive mappings. Populate with original ones.
final Map<IN4JSProject, IN4JSProject> joinedApiImplProjectMapping = new LinkedHashMap<>(apiImplProjectMapping);
while (!tobeInspectedApiImplProjects.isEmpty()) {
// compute dependencies if necessary
LinkedHashSet<IN4JSProject> batchedPivotDependencies = new LinkedHashSet<>();
RecursionGuard<URI> guard = new RecursionGuard<>();
for (IN4JSProject pivotProject : tobeInspectedApiImplProjects) {
recursiveDependencyCollector(pivotProject, batchedPivotDependencies, guard);
}
tobeInspectedApiImplProjects.clear();
List<IN4JSProject> batchedPivotNewDepList = batchedPivotDependencies.stream().filter(p -> null != p && !processedDepProjects.contains(p)).collect(Collectors.toList());
// new Api-mapping
apiImplMapping.enhance(batchedPivotNewDepList, n4jsCore.findAllProjects());
// go over new dependencies and decide:
for (IN4JSProject pivNewDep : batchedPivotNewDepList) {
final String depId = pivNewDep.getProjectId();
if (apiImplMapping.isApi(depId)) {
// API-mapping
if (joinedApiImplProjectMapping.containsKey(pivNewDep)) {
// already done.
} else {
// put new entry
IN4JSProject pivImpl = apiImplMapping.getImpl(depId, implementationId);
if (null != pivImpl) {
joinedApiImplProjectMapping.put(pivNewDep, pivImpl);
tobeInspectedApiImplProjects.add(pivImpl);
} else {
missing.add(depId);
}
}
} else {
// no API.
if (!processedDepProjects.contains(pivNewDep)) {
// add to deps
processedDepProjects.add(pivNewDep);
}
}
}
}
if (!missing.isEmpty()) {
if (throwOnError) {
throw new IllegalStateException("no implementation for implementation ID \"" + implementationId + "\" found for the following projects: " + Joiner.on(", ").join(missing));
}
}
return ApiUsage.of(implementationId, new ArrayList<>(deps), apiImplProjectMapping, apiImplMapping, missing);
}
use of java.util.Collections in project syncope by apache.
the class ResourceTest method delete.
@Test
public void delete() {
ExternalResource resource = resourceDAO.find("resource-testdb");
assertNotNull(resource);
// -------------------------------------
// Get originally associated connector
// -------------------------------------
ConnInstance connector = resource.getConnector();
assertNotNull(connector);
// -------------------------------------
// -------------------------------------
// Get originally associated users
// -------------------------------------
List<User> users = userDAO.findByResource(resource);
assertNotNull(users);
Set<String> userKeys = users.stream().map(Entity::getKey).collect(Collectors.toSet());
// -------------------------------------
// Get tasks
List<PropagationTask> propagationTasks = taskDAO.findAll(TaskType.PROPAGATION, resource, null, null, null, -1, -1, Collections.<OrderByClause>emptyList());
assertFalse(propagationTasks.isEmpty());
// delete resource
resourceDAO.delete(resource.getKey());
// close the transaction
resourceDAO.flush();
// resource must be removed
ExternalResource actual = resourceDAO.find("resource-testdb");
assertNull(actual);
// resource must be not referenced any more from users
userKeys.stream().map(key -> userDAO.find(key)).map(actualUser -> {
assertNotNull(actualUser);
return actualUser;
}).forEachOrdered((actualUser) -> {
userDAO.findAllResources(actualUser).forEach(res -> assertFalse(res.getKey().equalsIgnoreCase(resource.getKey())));
});
// resource must be not referenced any more from the connector
ConnInstance actualConnector = connInstanceDAO.find(connector.getKey());
assertNotNull(actualConnector);
actualConnector.getResources().forEach(res -> assertFalse(res.getKey().equalsIgnoreCase(resource.getKey())));
// there must be no tasks
propagationTasks.forEach(task -> assertNull(taskDAO.find(task.getKey())));
}
use of java.util.Collections in project syncope by apache.
the class SAML2SPLogic method validateLoginResponse.
@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2LoginResponseTO validateLoginResponse(final SAML2ReceivedResponseTO response) {
check();
// 1. first checks for the provided relay state
if (response.getRelayState() == null) {
throw new IllegalArgumentException("No Relay State was provided");
}
Boolean useDeflateEncoding = false;
String requestId = null;
if (!IDP_INITIATED_RELAY_STATE.equals(response.getRelayState())) {
JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
if (!relayState.verifySignatureWith(jwsSignatureVerifier)) {
throw new IllegalArgumentException("Invalid signature found in Relay State");
}
useDeflateEncoding = Boolean.valueOf(relayState.getJwtClaims().getClaim(JWT_CLAIM_IDP_DEFLATE).toString());
requestId = relayState.getJwtClaims().getSubject();
Long expiryTime = relayState.getJwtClaims().getExpiryTime();
if (expiryTime == null || (expiryTime * 1000L) < new Date().getTime()) {
throw new IllegalArgumentException("Relay State is expired");
}
}
// 2. parse the provided SAML response
if (response.getSamlResponse() == null) {
throw new IllegalArgumentException("No SAML Response was provided");
}
Response samlResponse;
try {
XMLObject responseObject = saml2rw.read(useDeflateEncoding, response.getSamlResponse());
if (!(responseObject instanceof Response)) {
throw new IllegalArgumentException("Expected " + Response.class.getName() + ", got " + responseObject.getClass().getName());
}
samlResponse = (Response) responseObject;
} catch (Exception e) {
LOG.error("While parsing AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 3. validate the SAML response and, if needed, decrypt the provided assertion(s)
if (samlResponse.getIssuer() == null || samlResponse.getIssuer().getValue() == null) {
throw new IllegalArgumentException("The SAML Response must contain an Issuer");
}
final SAML2IdPEntity idp = getIdP(samlResponse.getIssuer().getValue());
if (idp.getConnObjectKeyItem() == null) {
throw new IllegalArgumentException("No mapping provided for SAML 2.0 IdP '" + idp.getId() + "'");
}
if (IDP_INITIATED_RELAY_STATE.equals(response.getRelayState()) && !idp.isSupportUnsolicited()) {
throw new IllegalArgumentException("An unsolicited request is not allowed for idp: " + idp.getId());
}
SSOValidatorResponse validatorResponse = null;
try {
validatorResponse = saml2rw.validate(samlResponse, idp, getAssertionConsumerURL(response.getSpEntityID(), response.getUrlContext()), requestId, response.getSpEntityID());
} catch (Exception e) {
LOG.error("While validating AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 4. prepare the result: find matching user (if any) and return the received attributes
final SAML2LoginResponseTO responseTO = new SAML2LoginResponseTO();
responseTO.setIdp(idp.getId());
responseTO.setSloSupported(idp.getSLOLocation(idp.getBindingType()) != null);
Assertion assertion = validatorResponse.getOpensamlAssertion();
NameID nameID = assertion.getSubject().getNameID();
if (nameID == null) {
throw new IllegalArgumentException("NameID not found");
}
String keyValue = null;
if (StringUtils.isNotBlank(nameID.getValue()) && idp.getConnObjectKeyItem().getExtAttrName().equals("NameID")) {
keyValue = nameID.getValue();
}
if (assertion.getConditions().getNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(assertion.getConditions().getNotOnOrAfter().toDate());
}
assertion.getAuthnStatements().forEach(authnStmt -> {
responseTO.setSessionIndex(authnStmt.getSessionIndex());
responseTO.setAuthInstant(authnStmt.getAuthnInstant().toDate());
if (authnStmt.getSessionNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(authnStmt.getSessionNotOnOrAfter().toDate());
}
});
for (AttributeStatement attrStmt : assertion.getAttributeStatements()) {
for (Attribute attr : attrStmt.getAttributes()) {
if (!attr.getAttributeValues().isEmpty()) {
String attrName = attr.getFriendlyName() == null ? attr.getName() : attr.getFriendlyName();
if (attrName.equals(idp.getConnObjectKeyItem().getExtAttrName())) {
if (attr.getAttributeValues().get(0) instanceof XSString) {
keyValue = ((XSString) attr.getAttributeValues().get(0)).getValue();
} else if (attr.getAttributeValues().get(0) instanceof XSAny) {
keyValue = ((XSAny) attr.getAttributeValues().get(0)).getTextContent();
}
}
AttrTO attrTO = new AttrTO();
attrTO.setSchema(attrName);
attr.getAttributeValues().stream().filter(value -> value.getDOM() != null).forEachOrdered(value -> {
attrTO.getValues().add(value.getDOM().getTextContent());
});
responseTO.getAttrs().add(attrTO);
}
}
}
final List<String> matchingUsers = keyValue == null ? Collections.<String>emptyList() : userManager.findMatchingUser(keyValue, idp.getKey());
LOG.debug("Found {} matching users for {}", matchingUsers.size(), keyValue);
String username;
if (matchingUsers.isEmpty()) {
if (idp.isCreateUnmatching()) {
LOG.debug("No user matching {}, about to create", keyValue);
username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.create(idp, responseTO, nameID.getValue()));
} else if (idp.isSelfRegUnmatching()) {
responseTO.setNameID(nameID.getValue());
UserTO userTO = new UserTO();
userManager.fill(idp.getKey(), responseTO, userTO);
responseTO.getAttrs().clear();
responseTO.getAttrs().addAll(userTO.getPlainAttrs());
responseTO.getAttrs().addAll(userTO.getVirAttrs());
if (StringUtils.isNotBlank(userTO.getUsername())) {
responseTO.setUsername(userTO.getUsername());
}
responseTO.setSelfReg(true);
return responseTO;
} else {
throw new NotFoundException("User matching the provided value " + keyValue);
}
} else if (matchingUsers.size() > 1) {
throw new IllegalArgumentException("Several users match the provided value " + keyValue);
} else {
if (idp.isUpdateMatching()) {
LOG.debug("About to update {} for {}", matchingUsers.get(0), keyValue);
username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.update(matchingUsers.get(0), idp, responseTO));
} else {
username = matchingUsers.get(0);
}
}
responseTO.setUsername(username);
responseTO.setNameID(nameID.getValue());
// 5. generate JWT for further access
Map<String, Object> claims = new HashMap<>();
claims.put(JWT_CLAIM_IDP_ENTITYID, idp.getId());
claims.put(JWT_CLAIM_NAMEID_FORMAT, nameID.getFormat());
claims.put(JWT_CLAIM_NAMEID_VALUE, nameID.getValue());
claims.put(JWT_CLAIM_SESSIONINDEX, responseTO.getSessionIndex());
byte[] authorities = null;
try {
authorities = ENCRYPTOR.encode(POJOHelper.serialize(authDataAccessor.getAuthorities(responseTO.getUsername())), CipherAlgorithm.AES).getBytes();
} catch (Exception e) {
LOG.error("Could not fetch authorities", e);
}
Pair<String, Date> accessTokenInfo = accessTokenDataBinder.create(responseTO.getUsername(), claims, authorities, true);
responseTO.setAccessToken(accessTokenInfo.getLeft());
responseTO.setAccessTokenExpiryTime(accessTokenInfo.getRight());
return responseTO;
}
use of java.util.Collections in project syncope by apache.
the class SAML2UserManager method findMatchingUser.
@Transactional(readOnly = true)
public List<String> findMatchingUser(final String keyValue, final String idpKey) {
List<String> result = new ArrayList<>();
SAML2IdP idp = idpDAO.find(idpKey);
if (idp == null) {
LOG.warn("Invalid IdP: {}", idpKey);
return result;
}
String transformed = keyValue;
for (ItemTransformer transformer : MappingUtils.getItemTransformers(idp.getConnObjectKeyItem().get())) {
List<Object> output = transformer.beforePull(null, null, Collections.<Object>singletonList(transformed));
if (output != null && !output.isEmpty()) {
transformed = output.get(0).toString();
}
}
IntAttrName intAttrName;
try {
intAttrName = intAttrNameParser.parse(idp.getConnObjectKeyItem().get().getIntAttrName(), AnyTypeKind.USER);
} catch (ParseException e) {
LOG.error("Invalid intAttrName '{}' specified, ignoring", idp.getConnObjectKeyItem().get().getIntAttrName(), e);
return result;
}
if (intAttrName.getField() != null) {
switch(intAttrName.getField()) {
case "key":
User byKey = userDAO.find(transformed);
if (byKey != null) {
result.add(byKey.getUsername());
}
break;
case "username":
User byUsername = userDAO.findByUsername(transformed);
if (byUsername != null) {
result.add(byUsername.getUsername());
}
break;
default:
}
} else if (intAttrName.getSchemaType() != null) {
switch(intAttrName.getSchemaType()) {
case PLAIN:
PlainAttrValue value = entityFactory.newEntity(UPlainAttrValue.class);
PlainSchema schema = plainSchemaDAO.find(intAttrName.getSchemaName());
if (schema == null) {
value.setStringValue(transformed);
} else {
try {
value.parseValue(schema, transformed);
} catch (ParsingValidationException e) {
LOG.error("While parsing provided key value {}", transformed, e);
value.setStringValue(transformed);
}
}
result.addAll(userDAO.findByPlainAttrValue(intAttrName.getSchemaName(), value).stream().map(user -> user.getUsername()).collect(Collectors.toList()));
break;
case DERIVED:
result.addAll(userDAO.findByDerAttrValue(intAttrName.getSchemaName(), transformed).stream().map(user -> user.getUsername()).collect(Collectors.toList()));
break;
default:
}
}
return result;
}
use of java.util.Collections in project syncope by apache.
the class GroupServiceImpl method replace.
@Override
public Response replace(final String id, final SCIMGroup group) {
if (!id.equals(group.getId())) {
throw new BadRequestException(ErrorType.invalidPath, "Expected " + id + ", found " + group.getId());
}
ResponseBuilder builder = checkETag(Resource.Group, id);
if (builder != null) {
return builder.build();
}
// save current group members
Set<String> beforeMembers = new HashSet<>();
MembershipCond membCond = new MembershipCond();
membCond.setGroup(id);
SearchCond searchCond = SearchCond.getLeafCond(membCond);
int count = userLogic().search(searchCond, 1, 1, Collections.<OrderByClause>emptyList(), SyncopeConstants.ROOT_REALM, false).getLeft();
for (int page = 1; page <= (count / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
beforeMembers.addAll(userLogic().search(searchCond, page, AnyDAO.DEFAULT_PAGE_SIZE, Collections.<OrderByClause>emptyList(), SyncopeConstants.ROOT_REALM, false).getRight().stream().map(EntityTO::getKey).collect(Collectors.toSet()));
}
// update group, don't change members
ProvisioningResult<GroupTO> result = groupLogic().update(AnyOperations.diff(binder().toGroupTO(group), groupLogic().read(id), false), false);
// assign new members
Set<String> afterMembers = new HashSet<>();
group.getMembers().forEach(member -> {
afterMembers.add(member.getValue());
if (!beforeMembers.contains(member.getValue())) {
UserPatch patch = new UserPatch();
patch.setKey(member.getValue());
patch.getMemberships().add(new MembershipPatch.Builder().operation(PatchOperation.ADD_REPLACE).group(result.getEntity().getKey()).build());
try {
userLogic().update(patch, false);
} catch (Exception e) {
LOG.error("While setting membership of {} to {}", result.getEntity().getKey(), member.getValue(), e);
}
}
});
// remove unconfirmed members
beforeMembers.stream().filter(member -> !afterMembers.contains(member)).forEach(user -> {
UserPatch patch = new UserPatch();
patch.setKey(user);
patch.getMemberships().add(new MembershipPatch.Builder().operation(PatchOperation.DELETE).group(result.getEntity().getKey()).build());
try {
userLogic().update(patch, false);
} catch (Exception e) {
LOG.error("While removing membership of {} from {}", result.getEntity().getKey(), user, e);
}
});
return updateResponse(result.getEntity().getKey(), binder().toSCIMGroup(result.getEntity(), uriInfo.getAbsolutePathBuilder().path(result.getEntity().getKey()).build().toASCIIString(), Collections.<String>emptyList(), Collections.<String>emptyList()));
}
Aggregations