use of cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException in project perun by CESNET.
the class VosManagerBlImpl method findCandidates.
public List<Candidate> findCandidates(PerunSession sess, Vo vo, String searchString, int maxNumOfResults) throws InternalErrorException {
List<Candidate> candidates = new ArrayList<Candidate>();
int numOfResults = 0;
try {
// Iterate through all registered extSources
for (ExtSource source : getPerunBl().getExtSourcesManagerBl().getVoExtSources(sess, vo)) {
// Info if this is only simple ext source, change behavior if not
boolean simpleExtSource = true;
// Get potential subjects from the extSource
List<Map<String, String>> subjects;
try {
if (source instanceof ExtSourceApi) {
// find subjects with all their properties
subjects = ((ExtSourceApi) source).findSubjects(searchString, maxNumOfResults);
simpleExtSource = false;
} else {
// find subjects only with logins - they then must be retrieved by login
subjects = ((ExtSourceSimpleApi) source).findSubjectsLogins(searchString, maxNumOfResults);
}
} catch (ExtSourceUnsupportedOperationException e1) {
log.warn("ExtSource {} doesn't support findSubjects", source.getName());
continue;
} catch (InternalErrorException e) {
log.error("Error occurred on ExtSource {}, Exception {}.", source.getName(), e);
continue;
} finally {
try {
((ExtSourceSimpleApi) source).close();
} catch (ExtSourceUnsupportedOperationException e) {
// ExtSource doesn't support that functionality, so silently skip it.
} catch (InternalErrorException e) {
log.error("Can't close extSource connection. Cause: {}", e);
}
}
Set<String> uniqueLogins = new HashSet<>();
for (Map<String, String> s : subjects) {
// Check if the user has unique identifier within extSource
if ((s.get("login") == null) || (s.get("login") != null && ((String) s.get("login")).isEmpty())) {
log.error("User '{}' cannot be added, because he/she doesn't have a unique identifier (login)", s);
// Skip to another user
continue;
}
String extLogin = (String) s.get("login");
// check uniqueness of every login in extSource
if (uniqueLogins.contains(extLogin)) {
throw new InternalErrorException("There are more than 1 login '" + extLogin + "' getting from extSource '" + source + "'");
} else {
uniqueLogins.add(extLogin);
}
// Get Candidate
Candidate candidate;
try {
if (simpleExtSource) {
// retrieve data about subjects from ext source based on ext. login
candidate = getPerunBl().getExtSourcesManagerBl().getCandidate(sess, source, extLogin);
} else {
// retrieve data about subjects from subjects we already have locally
candidate = getPerunBl().getExtSourcesManagerBl().getCandidate(sess, s, source, extLogin);
}
} catch (ExtSourceNotExistsException e) {
throw new ConsistencyErrorException("Getting candidate from non-existing extSource " + source, e);
} catch (CandidateNotExistsException e) {
throw new ConsistencyErrorException("findSubjects returned that candidate, but getCandidate cannot find him using login " + extLogin, e);
} catch (ExtSourceUnsupportedOperationException e) {
throw new InternalErrorException("extSource supports findSubjects but not getCandidate???", e);
}
try {
getPerunBl().getMembersManagerBl().getMemberByUserExtSources(sess, vo, candidate.getUserExtSources());
// Candidate is already a member of the VO, so do not add him to the list of candidates
continue;
} catch (MemberNotExistsException e) {
// This is OK
}
// Add candidate to the list of candidates
log.debug("findCandidates: returning candidate: {}", candidate);
candidates.add(candidate);
numOfResults++;
// Stop getting new members if the number of already retrieved members exceeded the maxNumOfResults
if (maxNumOfResults > 0 && numOfResults >= maxNumOfResults) {
break;
}
}
// Stop walking through next sources if the number of already retrieved members exceeded the maxNumOfResults
if (maxNumOfResults > 0 && numOfResults >= maxNumOfResults) {
break;
}
}
log.debug("Returning {} potential members for vo {}", candidates.size(), vo);
return candidates;
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
use of cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException in project perun by CESNET.
the class AttributesManagerImpl method createAttributeExistsForInitialize.
public void createAttributeExistsForInitialize(AttributeDefinition attribute) throws InternalErrorException {
try {
int attributeId = Utils.getNewId(jdbc, "attr_names_id_seq");
jdbc.update("insert into attr_names (id, attr_name, type, dsc, namespace, friendly_name, display_name, default_attr_id) values (?,?,?,?,?,?,?,NULL)", attributeId, attribute.getName(), attribute.getType(), attribute.getDescription(), attribute.getNamespace(), attribute.getFriendlyName(), attribute.getDisplayName());
log.info("Attribute created during initialization of attributesManager: {}", attribute);
} catch (DataIntegrityViolationException e) {
throw new ConsistencyErrorException("Attribute already exists: " + attribute, e);
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
use of cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException in project perun by CESNET.
the class AttributesManagerImpl method setAttributeInDB.
private boolean setAttributeInDB(final PerunSession sess, final Attribute attribute, final String tableName, final Map<String, Object> params) throws InternalErrorException {
// get two sorted lists for parameter names and values
List<String> columnNames = new ArrayList<>();
List<Object> columnValues = new ArrayList<>();
for (Entry entry : params.entrySet()) {
columnNames.add((String) entry.getKey());
columnValues.add(entry.getValue());
}
try {
// deleting the attibute if the given attribute value is null
if (attribute.getValue() == null) {
int numAffected = jdbc.update("delete from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
if (numAffected > 1) {
throw new ConsistencyErrorException(String.format("Too much rows to delete (" + numAffected + " rows). SQL: delete from " + tableName + " where " + buildParameters(columnNames, "=%s", " and "), columnValues.toArray()));
}
return numAffected == 1;
}
// set the column name according to the size of the attribute
boolean largeAttribute = isLargeAttribute(sess, attribute);
String valueColName = (largeAttribute ? "attr_value_text" : "attr_value");
// if the DB value is the same as parameter, return
if (!largeAttribute) {
try {
Object value = BeansUtils.stringToAttributeValue(jdbc.queryForObject("select attr_value from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), String.class, columnValues.toArray()), attribute.getType());
if (attribute.getValue().equals(value)) {
return false;
}
} catch (EmptyResultDataAccessException ex) {
//This is ok. Attribute will be stored later.
}
}
int repetatCounter = 0;
while (true) {
// number of values of this attribute value in db
int numOfAttributesInDb = jdbc.queryForInt("select count(attr_id) from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
switch(numOfAttributesInDb) {
case 0:
{
// value doesn't exist -> insert
try {
return self.insertAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
} catch (DataAccessException ex) {
// unsuccessful insert, do it again in while loop
if (++repetatCounter > MERGE_TRY_CNT) {
throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
}
try {
//randomized sleep
Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
} catch (InterruptedException IGNORE) {
}
}
break;
}
case 1:
{
// value exists -> update
try {
return self.updateAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
} catch (DataAccessException ex) {
// unsuccessful insert, do it again in while loop
if (++repetatCounter > MERGE_TRY_CNT) {
throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
}
try {
//randomized sleep
Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
} catch (InterruptedException IGNORE) {
}
}
break;
}
default:
throw new ConsistencyErrorException(String.format("Attribute id " + attribute.getId() + " for " + tableName + " with parameters: " + buildParameters(columnNames, "=%s", " and ") + " is more than once in DB.", columnValues.toArray()));
}
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
use of cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException in project perun by CESNET.
the class urn_perun_group_attribute_def_def_unixGID_namespace method checkAttributeValue.
public void checkAttributeValue(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
try {
String gidNamespace = attribute.getFriendlyNameParameter();
//Special behaviour if gid is null
if (attribute.getValue() == null) {
List<Facility> groupFacilities = new ArrayList<Facility>();
for (Resource r : sess.getPerunBl().getResourcesManagerBl().getAssignedResources(sess, group)) {
groupFacilities.add(sess.getPerunBl().getResourcesManagerBl().getFacility(sess, r));
}
Set<String> namespacesWhereGroupMustHaveGIDifItHaveUnixNameThere = sess.getPerunBl().getModulesUtilsBl().getSetOfGroupNameNamespacesWhereFacilitiesHasTheSameGIDNamespace(sess, groupFacilities, attribute);
for (String namespace : namespacesWhereGroupMustHaveGIDifItHaveUnixNameThere) {
Attribute unixGroupName = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, A_G_unixGroupName_namespace + ":" + namespace);
if (unixGroupName.getValue() != null) {
throw new WrongAttributeValueException(attribute, group, "Group is propagated to the facility where it have set unix group name so it must have unix GID too.");
}
}
//Group is not propagated to any facility in this GID namespace or it doesn't have set unix name there so it doesn't need to have unix GID.
return;
}
//Special behaviour if gid is null
Integer attrValue = null;
if (attribute.getValue() == null) {
throw new WrongAttributeValueException(attribute, group, "Unix GID must be set");
} else {
attrValue = (Integer) attribute.getValue();
}
//check if gid is not already depleted
Attribute usedGids = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, gidNamespace, A_E_usedGids);
//null in value means there is no depleted or used gids
if (usedGids.getValue() != null) {
Map<String, String> usedGidsValue = (Map<String, String>) usedGids.getValue();
//Dx, where x is GID means depleted value for GID x
if (usedGidsValue.containsKey("D" + attrValue.toString())) {
throw new WrongReferenceAttributeValueException(attribute, usedGids, group, null, gidNamespace, null, "This GID is already depleted.");
}
}
//Check if gid GID is within allowed range
sess.getPerunBl().getModulesUtilsBl().checkIfGIDIsWithinRange(sess, attribute);
//Prepare lists for all groups and resources with same GID in the same namespace
List<Group> allGroupsWithSameGIDInSameNamespace = new ArrayList<Group>();
List<Resource> allResourcesWithSameGIDInSameNamespace = new ArrayList<Resource>();
//Prepare attributes for searching through groups and resources
Attribute groupGIDAttribute = attribute;
Attribute resourceGIDAttribute = new Attribute(sess.getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, A_R_unixGID_namespace + ":" + gidNamespace));
resourceGIDAttribute.setValue(groupGIDAttribute.getValue());
//Fill lists of Groups and Resources by data
allGroupsWithSameGIDInSameNamespace.addAll(sess.getPerunBl().getGroupsManagerBl().getGroupsByAttribute(sess, groupGIDAttribute));
allResourcesWithSameGIDInSameNamespace.addAll(sess.getPerunBl().getResourcesManagerBl().getResourcesByAttribute(sess, resourceGIDAttribute));
//remove this group
allGroupsWithSameGIDInSameNamespace.remove(group);
//Prepare list of GroupName attributes of this group
List<Attribute> groupNamesOfGroup = sess.getPerunBl().getAttributesManagerBl().getAllAttributesStartWithNameWithoutNullValue(sess, group, A_G_unixGroupName_namespace + ":");
//Searching through groups
if (!allGroupsWithSameGIDInSameNamespace.isEmpty()) {
for (Group g : allGroupsWithSameGIDInSameNamespace) {
for (Attribute a : groupNamesOfGroup) {
int compare = sess.getPerunBl().getModulesUtilsBl().haveTheSameAttributeWithTheSameNamespace(sess, g, a);
if (compare > 0) {
//This is problem, there is the same attribute but have other value
throw new WrongReferenceAttributeValueException(attribute, a, "There is a group with same GID (namespace: " + gidNamespace + ") and different unix group name (namespace: " + a.getFriendlyNameParameter() + "). " + g + " " + group);
}
//Other possibilities are not problem, less than 0 mean that same attribute not exists, and 0 mean that attribute exists but have same value
}
}
}
//Searching through resources
if (!allResourcesWithSameGIDInSameNamespace.isEmpty()) {
for (Resource r : allResourcesWithSameGIDInSameNamespace) {
for (Attribute a : groupNamesOfGroup) {
//Prepare resource version of this group attribute
Attribute resourceGroupName = new Attribute(sess.getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, A_R_unixGroupName_namespace + ":" + a.getFriendlyNameParameter()));
resourceGroupName.setValue(a.getValue());
int compare = sess.getPerunBl().getModulesUtilsBl().haveTheSameAttributeWithTheSameNamespace(sess, r, resourceGroupName);
if (compare > 0) {
//This is problem, there is the same attribute but have other value
throw new WrongReferenceAttributeValueException(attribute, a, "There is a resource with same GID (namespace: " + gidNamespace + ") and different unix group name (namespace: " + a.getFriendlyNameParameter() + "). " + r + " " + group);
}
//Other possibilities are not problem, less than 0 mean that same attribute not exists, and 0 mean that attribute exists but have same value
}
}
}
} catch (AttributeNotExistsException ex) {
throw new ConsistencyErrorException(ex);
}
}
use of cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException in project perun by CESNET.
the class urn_perun_group_attribute_def_def_unixGroupName_namespace method checkAttributeValue.
@Override
public void checkAttributeValue(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
//prepare namespace and groupName value variables
String groupName = null;
if (attribute.getValue() != null)
groupName = (String) attribute.getValue();
String groupNameNamespace = attribute.getFriendlyNameParameter();
if (groupName == null) {
// if this is group attribute, its ok
return;
}
//Check attribute regex
sess.getPerunBl().getModulesUtilsBl().checkAttributeRegex(attribute, "^[-._a-zA-Z0-9]+$");
//Check reserved unix group names
sess.getPerunBl().getModulesUtilsBl().checkReservedUnixGroupNames(attribute);
try {
//prepare attributes group and resource unixGroupName
Attribute groupUnixGroupName = attribute;
Attribute resourceUnixGroupName = new Attribute(sess.getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, A_R_unixGroupName_namespace + ":" + groupNameNamespace));
resourceUnixGroupName.setValue(attribute.getValue());
//prepare lists of groups and resources with the same groupName value in the same namespace
List<Group> groupsWithSameGroupNameInTheSameNamespace = new ArrayList<Group>();
List<Resource> resourcesWithSameGroupNameInTheSameNamespace = new ArrayList<Resource>();
//Fill lists of groups and resources
groupsWithSameGroupNameInTheSameNamespace.addAll(sess.getPerunBl().getGroupsManagerBl().getGroupsByAttribute(sess, groupUnixGroupName));
resourcesWithSameGroupNameInTheSameNamespace.addAll(sess.getPerunBl().getResourcesManagerBl().getResourcesByAttribute(sess, resourceUnixGroupName));
//If there is no group or resource with same GroupNameInTheSameNamespace, its ok
if (groupsWithSameGroupNameInTheSameNamespace.isEmpty() && resourcesWithSameGroupNameInTheSameNamespace.isEmpty())
return;
//First need to know that i have right to write any of duplicit groupName-namespace attribute
boolean haveRights = sess.getPerunBl().getModulesUtilsBl().haveRightToWriteAttributeInAnyGroupOrResource(sess, groupsWithSameGroupNameInTheSameNamespace, resourcesWithSameGroupNameInTheSameNamespace, groupUnixGroupName, resourceUnixGroupName);
if (!haveRights)
throw new WrongReferenceAttributeValueException(attribute, "This groupName is already used for other group or resource and user has no rights to use it.");
//Now if rights are ok, prepare lists of UnixGIDs attributes of this group (also equivalent resource GID)
List<Attribute> groupUnixGIDs = sess.getPerunBl().getAttributesManagerBl().getAllAttributesStartWithNameWithoutNullValue(sess, group, A_G_unixGID_namespace + ":");
List<Attribute> resourceVersionOfUnixGIDs = sess.getPerunBl().getModulesUtilsBl().getListOfResourceGIDsFromListOfGroupGIDs(sess, groupUnixGIDs);
//In list of duplicit groups looking for GID in same namespace but with different value, thats not correct
if (!groupsWithSameGroupNameInTheSameNamespace.isEmpty()) {
for (Group g : groupsWithSameGroupNameInTheSameNamespace) {
for (Attribute a : groupUnixGIDs) {
int compare;
compare = sess.getPerunBl().getModulesUtilsBl().haveTheSameAttributeWithTheSameNamespace(sess, g, a);
if (compare > 0) {
throw new WrongReferenceAttributeValueException(attribute, a, "One of the group GIDs is from the same namespace like other group GID but with different values.");
}
}
}
}
//In list of duplicit resources looking for GID in same namespace but with different value, thats not correct
if (!resourcesWithSameGroupNameInTheSameNamespace.isEmpty()) {
for (Resource r : resourcesWithSameGroupNameInTheSameNamespace) {
for (Attribute a : resourceVersionOfUnixGIDs) {
int compare;
compare = sess.getPerunBl().getModulesUtilsBl().haveTheSameAttributeWithTheSameNamespace(sess, r, a);
if (compare > 0) {
throw new WrongReferenceAttributeValueException(attribute, a, "One of the group GIDs is from the same namespace like other resource GIDs but with different values.");
}
}
}
}
} catch (AttributeNotExistsException ex) {
throw new ConsistencyErrorException(ex);
}
}
Aggregations