use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.
the class MembersManagerBlImpl method manageMembershipExpiration.
/**
* More info on https://wiki.metacentrum.cz/wiki/VO_managers%27s_manual
*
* If setAttributeValue is true, then store the membership expiration date into the attribute, otherwise
* return object pair containing true/false if the member can be extended and date specifying exact date of the new expiration
*
* @param sess session
* @param member member to check / set membership expiration
* @param setAttributeValue TRUE = set new membership expiration date / FALSE = do NOT set new expiration date (just calculate it)
* @param throwExceptions TRUE = throw exception / FALSE = return false when member can't extend membership
* @return Pair with result in left side (can / can't extend membership) and Date in right side telling new membership expiration date
*
* @throws InternalErrorException
* @throws ExtendMembershipException When member can't extend membership and throwException is set to true.
*/
protected Pair<Boolean, Date> manageMembershipExpiration(PerunSession sess, Member member, boolean setAttributeValue, boolean throwExceptions) throws InternalErrorException, ExtendMembershipException {
// Check if the VO has set membershipExpirationRules attribute
LinkedHashMap<String, String> membershipExpirationRules;
Vo vo;
Attribute membershipExpirationRulesAttribute = null;
try {
vo = getPerunBl().getVosManagerBl().getVoById(sess, member.getVoId());
membershipExpirationRulesAttribute = getPerunBl().getAttributesManagerBl().getAttribute(sess, vo, MembersManager.membershipExpirationRulesAttributeName);
membershipExpirationRules = (LinkedHashMap<String, String>) membershipExpirationRulesAttribute.getValue();
// If attribute was not filled, then silently exit
if (membershipExpirationRules == null)
return new Pair<Boolean, Date>(true, null);
} catch (VoNotExistsException e) {
throw new ConsistencyErrorException("Member " + member + " of non-existing VO id=" + member.getVoId());
} catch (AttributeNotExistsException e) {
// There is no attribute definition for membership expiration rules.
return new Pair<Boolean, Date>(true, null);
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException("Shouldn't happen.");
}
// Get user LOA
String memberLoa = null;
try {
Attribute loa = getPerunBl().getAttributesManagerBl().getAttribute(sess, member, AttributesManager.NS_MEMBER_ATTR_VIRT + ":loa");
memberLoa = (String) loa.getValue();
} catch (AttributeNotExistsException e) {
// Ignore, will be probably set further
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException(e);
}
// Get current membershipExpiration date
Attribute membershipExpirationAttribute = null;
try {
membershipExpirationAttribute = getPerunBl().getAttributesManagerBl().getAttribute(sess, member, AttributesManager.NS_MEMBER_ATTR_DEF + ":membershipExpiration");
} catch (AttributeNotExistsException e) {
throw new ConsistencyErrorException("Attribute: " + AttributesManager.NS_MEMBER_ATTR_DEF + ":membershipExpiration" + " must be defined in order to use membershipExpirationRules");
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException(e);
}
boolean isServiceUser = false;
try {
User user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId());
isServiceUser = user.isServiceUser();
} catch (UserNotExistsException ex) {
throw new ConsistencyErrorException("User must exists for " + member + " when checking expiration rules.");
}
// and are not service users
if (membershipExpirationRules.get(MembersManager.membershipDoNotExtendLoaKeyName) != null && membershipExpirationAttribute.getValue() != null && !isServiceUser) {
if (memberLoa == null) {
// Member doesn't have LOA defined and LOA is required for extension, so do not extend membership.
log.warn("Member {} doesn't have LOA defined, but 'doNotExtendLoa' option is set for VO id {}.", member, member.getVoId());
if (throwExceptions) {
throw new ExtendMembershipException(ExtendMembershipException.Reason.NOUSERLOA, "Member " + member + " doesn't have LOA defined, but 'doNotExtendLoa' option is set for VO id " + member.getVoId() + ".");
} else {
return new Pair<Boolean, Date>(false, null);
}
}
String[] doNotExtendLoas = membershipExpirationRules.get(MembersManager.membershipDoNotExtendLoaKeyName).split(",");
for (String doNotExtendLoa : doNotExtendLoas) {
if (doNotExtendLoa.equals(memberLoa)) {
// Member has LOA which is not allowed for extension
if (throwExceptions) {
throw new ExtendMembershipException(ExtendMembershipException.Reason.INSUFFICIENTLOAFOREXTENSION, "Member " + member + " doesn't have required LOA for VO id " + member.getVoId() + ".");
} else {
return new Pair<Boolean, Date>(false, null);
}
}
}
}
Calendar calendar = Calendar.getInstance();
// Does the user have expired membership, if yes, then for canExtendMembership return true
if (!setAttributeValue && membershipExpirationAttribute.getValue() != null) {
try {
Date currentMemberExpiration = BeansUtils.getDateFormatterWithoutTime().parse((String) membershipExpirationAttribute.getValue());
Calendar currentMemberExpirationCalendar = Calendar.getInstance();
currentMemberExpirationCalendar.setTime(currentMemberExpiration);
if (calendar.after(currentMemberExpirationCalendar)) {
return new Pair<Boolean, Date>(true, null);
}
} catch (ParseException e) {
throw new InternalErrorException("Wrong format of the membersExpiration: " + membershipExpirationAttribute.getValue(), e);
}
}
String period = null;
// Default extension
if (membershipExpirationRules.get(MembersManager.membershipPeriodKeyName) != null) {
period = membershipExpirationRules.get(MembersManager.membershipPeriodKeyName);
}
// Do we extend particular LoA? Attribute syntax LoA|[period][.]
if (membershipExpirationRules.get(MembersManager.membershipPeriodLoaKeyName) != null) {
// Which period
String[] membershipPeriodLoa = membershipExpirationRules.get(MembersManager.membershipPeriodLoaKeyName).split("\\|");
String loa = membershipPeriodLoa[0];
String periodLoa = membershipPeriodLoa[1];
// Does the user have this LoA?
if (loa.equals(memberLoa)) {
if (periodLoa.endsWith(".")) {
// If period ends with ., then we do not allow extension for users with particular LoA if they are already members
if (membershipExpirationAttribute.getValue() != null) {
if (throwExceptions) {
throw new ExtendMembershipException(ExtendMembershipException.Reason.INSUFFICIENTLOAFOREXTENSION, "Member " + member + " doesn't have required LOA for VO id " + member.getVoId() + ".");
} else {
return new Pair<Boolean, Date>(false, null);
}
}
// remove dot from the end of the string
period = periodLoa.substring(0, periodLoa.length() - 1);
} else {
period = periodLoa;
}
}
}
// Do we extend for x months or for static date?
if (period != null) {
if (period.startsWith("+")) {
if (!isMemberInGracePeriod(membershipExpirationRules, (String) membershipExpirationAttribute.getValue())) {
if (throwExceptions) {
throw new ExtendMembershipException(ExtendMembershipException.Reason.OUTSIDEEXTENSIONPERIOD, (String) membershipExpirationAttribute.getValue(), "Member " + member + " cannot extend because we are outside grace period for VO id " + member.getVoId() + ".");
} else {
return new Pair<Boolean, Date>(false, null);
}
}
// By default do not add nothing
int amount = 0;
int field;
// We will add days/months/years
Pattern p = Pattern.compile("\\+([0-9]+)([dmy]?)");
Matcher m = p.matcher(period);
if (m.matches()) {
String countString = m.group(1);
amount = Integer.valueOf(countString);
String dmyString = m.group(2);
if (dmyString.equals("d")) {
field = Calendar.DAY_OF_YEAR;
} else if (dmyString.equals("m")) {
field = Calendar.MONTH;
} else if (dmyString.equals("y")) {
field = Calendar.YEAR;
} else {
throw new InternalErrorException("Wrong format of period in VO membershipExpirationRules attribute. Period: " + period);
}
} else {
throw new InternalErrorException("Wrong format of period in VO membershipExpirationRules attribute. Period: " + period);
}
// Add days/months/years
calendar.add(field, amount);
} else {
// We will extend to particular date
// Parse date
Pattern p = Pattern.compile("([0-9]+).([0-9]+).");
Matcher m = p.matcher(period);
if (m.matches()) {
int day = Integer.valueOf(m.group(1));
int month = Integer.valueOf(m.group(2));
// Get current year
int year = calendar.get(Calendar.YEAR);
// We must detect if the extension date is in current year or in a next year
boolean extensionInNextYear;
Calendar extensionCalendar = Calendar.getInstance();
extensionCalendar.set(year, month - 1, day);
Calendar today = Calendar.getInstance();
if (extensionCalendar.before(today)) {
// Extension date is in a next year
extensionInNextYear = true;
} else {
// Extension is in the current year
extensionInNextYear = false;
}
// Set the date to which the membershi should be extended, can be changed if there was grace period, see next part of the code
// month is 0-based
calendar.set(year, month - 1, day);
if (extensionInNextYear) {
calendar.add(Calendar.YEAR, 1);
}
// Is there a grace period?
if (membershipExpirationRules.get(MembersManager.membershipGracePeriodKeyName) != null) {
String gracePeriod = membershipExpirationRules.get(MembersManager.membershipGracePeriodKeyName);
// If the extension is requested in period-gracePeriod then extend to next period
// Get the value of the grace period
p = Pattern.compile("([0-9]+)([dmy]?)");
m = p.matcher(gracePeriod);
if (m.matches()) {
String countString = m.group(1);
int amount = Integer.valueOf(countString);
// Set the gracePeriodCalendar to the extension date
Calendar gracePeriodCalendar = Calendar.getInstance();
gracePeriodCalendar.set(year, month - 1, day);
if (extensionInNextYear) {
gracePeriodCalendar.add(Calendar.YEAR, 1);
}
int field;
String dmyString = m.group(2);
if (dmyString.equals("d")) {
field = Calendar.DAY_OF_YEAR;
} else if (dmyString.equals("m")) {
field = Calendar.MONTH;
} else if (dmyString.equals("y")) {
field = Calendar.YEAR;
} else {
throw new InternalErrorException("Wrong format of gracePeriod in VO membershipExpirationRules attribute. gracePeriod: " + gracePeriod);
}
// subtracts period definition, e.g. 3m
gracePeriodCalendar.add(field, -amount);
// Check if we are in grace period
if (gracePeriodCalendar.before(Calendar.getInstance())) {
// We are in grace period, so extend to the next period
calendar.add(Calendar.YEAR, 1);
}
// If we do not need to set the attribute value, only check if the current member's expiration time is not in grace period
if (!setAttributeValue && membershipExpirationAttribute.getValue() != null) {
try {
Date currentMemberExpiration = BeansUtils.getDateFormatterWithoutTime().parse((String) membershipExpirationAttribute.getValue());
// subtracts grace period from the currentMemberExpiration
Calendar currentMemberExpirationCalendar = Calendar.getInstance();
currentMemberExpirationCalendar.setTime(currentMemberExpiration);
currentMemberExpirationCalendar.add(field, -amount);
// if today is before that time, user can extend his period
if (currentMemberExpirationCalendar.after(Calendar.getInstance())) {
if (throwExceptions) {
throw new ExtendMembershipException(ExtendMembershipException.Reason.OUTSIDEEXTENSIONPERIOD, (String) membershipExpirationAttribute.getValue(), "Member " + member + " cannot extend because we are outside grace period for VO id " + member.getVoId() + ".");
} else {
return new Pair<Boolean, Date>(false, null);
}
}
} catch (ParseException e) {
throw new InternalErrorException("Wrong format of the membersExpiration: " + membershipExpirationAttribute.getValue(), e);
}
}
}
}
} else {
throw new InternalErrorException("Wrong format of period in VO membershipExpirationRules attribute. Period: " + period);
}
}
// Reset hours, minutes and seconds to 0
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// Set new value of the membershipExpiration for the member
if (setAttributeValue) {
membershipExpirationAttribute.setValue(BeansUtils.getDateFormatterWithoutTime().format(calendar.getTime()));
try {
getPerunBl().getAttributesManagerBl().setAttribute(sess, member, membershipExpirationAttribute);
} catch (WrongAttributeValueException e) {
throw new InternalErrorException("Wrong value: " + membershipExpirationAttribute.getValue(), e);
} catch (WrongReferenceAttributeValueException e) {
throw new InternalErrorException(e);
} catch (WrongAttributeAssignmentException e) {
throw new InternalErrorException(e);
}
}
}
return new Pair<Boolean, Date>(true, calendar.getTime());
}
use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.
the class MembersManagerBlImpl method deleteMember.
public void deleteMember(PerunSession sess, Member member) throws InternalErrorException, MemberAlreadyRemovedException, GroupOperationsException {
Vo vo = this.getMemberVo(sess, member);
User user;
try {
user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId());
} catch (UserNotExistsException e1) {
throw new ConsistencyErrorException("Removing member who doesn't have corresponding user.", e1);
}
List<Facility> allowedFacilities = getPerunBl().getFacilitiesManagerBl().getAllowedFacilities(sess, user);
Map<Facility, List<Attribute>> requiredAttributesBeforeMemberRemove = new HashMap<Facility, List<Attribute>>();
for (Facility facility : allowedFacilities) {
// Get actually required attributes, they will be later compared with list of required attributes when the member will be removed from all resources in this VO
requiredAttributesBeforeMemberRemove.put(facility, getPerunBl().getAttributesManagerBl().getRequiredAttributes(sess, facility, user));
}
// Remove member from all groups
List<Group> memberGroups = getPerunBl().getGroupsManagerBl().getMemberDirectGroups(sess, member);
for (Group group : memberGroups) {
// Member must be removed from the members group using separate method
if (group.getName().equals(VosManager.MEMBERS_GROUP))
continue;
try {
getPerunBl().getGroupsManagerBl().removeMember(sess, group, member);
} catch (NotGroupMemberException e) {
throw new ConsistencyErrorException("getMemberGroups return group where the member is not member", e);
} catch (GroupNotExistsException e) {
throw new ConsistencyErrorException(e);
}
}
// Remove member from the VO members group
try {
Group g = getPerunBl().getGroupsManagerBl().getGroupByName(sess, vo, VosManager.MEMBERS_GROUP);
try {
getPerunBl().getGroupsManagerBl().removeMemberFromMembersOrAdministratorsGroup(sess, g, member);
} catch (NotGroupMemberException e) {
throw new ConsistencyErrorException("Member is not in the \"members\" group." + member + " " + g, e);
}
} catch (GroupNotExistsException e) {
throw new InternalErrorException(e);
}
// Remove member's attributes (namespaces: member and resource-member)
try {
getPerunBl().getAttributesManagerBl().removeAllAttributes(sess, member);
List<Resource> resources = getPerunBl().getResourcesManagerBl().getResources(sess, vo);
for (Resource resource : resources) {
getPerunBl().getAttributesManagerBl().removeAllAttributes(sess, resource, member);
}
} catch (AttributeValueException ex) {
throw new ConsistencyErrorException("Member is removed from all groups. There are no required attribute for this member. Member's attributes can be removed without problem.", ex);
} catch (WrongAttributeAssignmentException ex) {
throw new InternalErrorException(ex);
}
// Remove user-facility attributes which are no longer required
for (Facility facility : allowedFacilities) {
List<Attribute> requiredAttributes = requiredAttributesBeforeMemberRemove.get(facility);
//remove currently required attributes from requiredAttributesBeforeMemberRemove
requiredAttributes.removeAll(getPerunBl().getAttributesManagerBl().getRequiredAttributes(sess, facility, user));
//remove attributes which are no longer required
try {
getPerunBl().getAttributesManagerBl().removeAttributes(sess, facility, user, requiredAttributes);
} catch (AttributeValueException | WrongAttributeAssignmentException ex) {
throw new ConsistencyErrorException(ex);
}
}
//Remove all members bans
List<BanOnResource> bansOnResource = getPerunBl().getResourcesManagerBl().getBansForMember(sess, member.getId());
for (BanOnResource banOnResource : bansOnResource) {
try {
getPerunBl().getResourcesManagerBl().removeBan(sess, banOnResource.getId());
} catch (BanNotExistsException ex) {
//it is ok, we just want to remove it anyway
}
}
/* TODO this can be used for future optimization. If the user is not asigned to the facility anymore all user-facility attributes (for this facility) can be safely removed.
for (Facility facility: facilitiesBeforeMemberRemove) {
// Remove user-facility attributes
try {
getPerunBl().getAttributesManagerBl().removeAllAttributes(sess, facility, user);
log.debug("Removing user-facility attributes for facility {}", facility);
} catch (AttributeValueException e) {
throw new ConsistencyErrorException("Member is removed from all resources. There are no required attribute for this member. User-facility attributes can be removed without problem.", e);
}
}
*/
// Remove member from the DB
getMembersManagerImpl().deleteMember(sess, member);
getPerunBl().getAuditer().log(sess, "{} deleted.", member);
}
use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.
the class ServicesManagerBlImpl method getData.
private ServiceAttributes getData(PerunSession sess, Service service, Facility facility, Resource resource, Member member) throws InternalErrorException {
ServiceAttributes memberServiceAttributes = new ServiceAttributes();
User user;
try {
user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId());
memberServiceAttributes.addAttributes(getPerunBl().getAttributesManagerBl().getRequiredAttributes(sess, service, facility, resource, user, member));
} catch (UserNotExistsException e) {
throw new ConsistencyErrorException("Member has assigned non-existing user.", e);
} catch (WrongAttributeAssignmentException ex) {
throw new InternalErrorException(ex);
}
return memberServiceAttributes;
}
use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.
the class Api method doGet.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (req.getPathInfo() == null || req.getPathInfo().equals("/")) {
resp.setContentType("text/plain; charset=utf-8");
Writer wrt = resp.getWriter();
PerunPrincipal perunPrincipal;
try {
perunPrincipal = setupPerunPrincipal(req);
wrt.write("OK! Version: " + PerunBl.PERUNVERSION + ", User: " + perunPrincipal.getActor() + ", extSource: " + perunPrincipal.getExtSourceName());
} catch (InternalErrorException e) {
wrt.write("ERROR! Exception " + e.getMessage());
} catch (UserNotExistsException e) {
wrt.write("ERROR! Exception " + e.getMessage());
}
wrt.write("\n");
wrt.close();
} else {
serve(req, resp, true, false);
}
}
use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.
the class CabinetManagerBlImpl method findExternalPublicationsOfUser.
public List<Publication> findExternalPublicationsOfUser(PerunSession sess, int userId, int yearSince, int yearTill, String pubSysNamespace) throws CabinetException, InternalErrorException {
// get PubSys
PublicationSystem ps = getPublicationSystemManagerBl().getPublicationSystemByNamespace(pubSysNamespace);
// get user
User user;
try {
user = perun.getUsersManagerBl().getUserById(sess, userId);
} catch (UserNotExistsException ex) {
throw new CabinetException("User with ID: " + userId + " doesn't exists.", ErrorCodes.PERUN_EXCEPTION, ex);
}
// result list
List<Publication> result = new ArrayList<Publication>();
// PROCESS MU PUB SYS
if (ps.getLoginNamespace().equalsIgnoreCase("mu")) {
// get UCO
List<UserExtSource> ues = perun.getUsersManagerBl().getUserExtSources(sess, user);
String authorId = "";
for (UserExtSource es : ues) {
// get login from LDAP
if (es.getExtSource().getName().equalsIgnoreCase("LDAPMU")) {
// get only UCO
authorId = es.getLogin();
break;
// get login from IDP
} else if (es.getExtSource().getName().equalsIgnoreCase("https://idp2.ics.muni.cz/idp/shibboleth")) {
// get only UCO from UCO@mail.muni.cz
authorId = es.getLogin().substring(0, es.getLogin().indexOf("@"));
break;
}
}
// check
if (authorId.isEmpty()) {
throw new CabinetException("You don't have assigned identity in Perun for MU (LDAPMU / Shibboleth IDP).", ErrorCodes.NO_IDENTITY_FOR_PUBLICATION_SYSTEM);
}
// get publications
result.addAll(findPublicationsInPubSys(authorId, yearSince, yearTill, ps));
return result;
// PROCESS ZCU 3.0 PUB SYS
} else if (ps.getLoginNamespace().equalsIgnoreCase("zcu")) {
// search is based on "lastName,firstName"
String authorId = user.getLastName() + "," + user.getFirstName();
result.addAll(findPublicationsInPubSys(authorId, yearSince, yearTill, ps));
return result;
} else {
log.error("Publication System with namespace: [{}] found but not supported for import.", pubSysNamespace);
throw new CabinetException("PubSys namespace found but not supported for import.");
}
}
Aggregations