Search in sources :

Example 1 with UserNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.

the class PerunNotifJabberSender method send.

@Override
public Set<Integer> send(List<PerunNotifMessageDto> dtosToSend) {
    Set<Integer> usedPools = new HashSet<Integer>();
    try {
        ConnectionConfiguration config = new ConnectionConfiguration(jabberServer, port, serviceName);
        XMPPConnection connection = new XMPPConnection(config);
        connection.connect();
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        connection.login(username, password);
        for (PerunNotifMessageDto messageDto : dtosToSend) {
            PerunNotifReceiver receiver = messageDto.getReceiver();
            PoolMessage dto = messageDto.getPoolMessage();
            Message message = new Message();
            message.setSubject(messageDto.getSubject());
            message.setBody(messageDto.getMessageToSend());
            message.setType(Message.Type.headline);
            String myReceiverId = dto.getKeyAttributes().get(receiver.getTarget());
            if (myReceiverId == null || myReceiverId.isEmpty()) {
                //Can be set one static account
                message.setTo(receiver.getTarget());
            } else {
                //We try to resolve id
                Integer id = null;
                try {
                    id = Integer.valueOf(myReceiverId);
                } catch (NumberFormatException ex) {
                    logger.error("Cannot resolve id: {}, error: {}", Arrays.asList(id, ex.getMessage()));
                    logger.debug("ST:", ex);
                }
                if (id != null) {
                    try {
                        User user = perun.getUsersManagerBl().getUserById(session, id);
                        Attribute emailAttribute = perun.getAttributesManagerBl().getAttribute(session, user, "urn:perun:user:attribute-def:def:jabber");
                        if (emailAttribute != null && StringUtils.hasText(emailAttribute.toString())) {
                            message.setTo((String) emailAttribute.getValue());
                        }
                    } catch (UserNotExistsException ex) {
                        logger.error("Cannot found user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (AttributeNotExistsException ex) {
                        logger.warn("Cannot found email for user with id: {}, ex: {}", Arrays.asList(id, ex.getMessage()));
                        logger.debug("ST:", ex);
                    } catch (Exception ex) {
                        logger.error("Error during user email recognition, ex: {}", ex.getMessage());
                        logger.debug("ST:", ex);
                    }
                }
            }
            connection.sendPacket(message);
            usedPools.addAll(messageDto.getUsedPoolIds());
        }
        connection.disconnect();
    } catch (XMPPException ex) {
        logger.error("Error during jabber establish connection.", ex);
    }
    return null;
}
Also used : PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) Message(org.jivesoftware.smack.packet.Message) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) PerunNotifReceiver(cz.metacentrum.perun.notif.entities.PerunNotifReceiver) XMPPConnection(org.jivesoftware.smack.XMPPConnection) PerunNotifMessageDto(cz.metacentrum.perun.notif.dto.PerunNotifMessageDto) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionConfiguration(org.jivesoftware.smack.ConnectionConfiguration) PoolMessage(cz.metacentrum.perun.notif.dto.PoolMessage) XMPPException(org.jivesoftware.smack.XMPPException)

Example 2 with UserNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.

the class PerunBlImpl method getPerunSession.

public PerunSession getPerunSession(PerunPrincipal principal, PerunClient client) throws InternalErrorException {
    if (principal.getUser() == null && this.getUsersManagerBl() != null && !dontLookupUsersForLogins.contains(principal.getActor())) {
        // Get the user if we are completely initialized
        try {
            principal.setUser(this.getUsersManagerBl().getUserByExtSourceNameAndExtLogin(getPerunSession(), principal.getExtSourceName(), principal.getActor()));
            // Try to update LoA for userExtSource
            ExtSource es = this.getExtSourcesManagerBl().getExtSourceByName(getPerunSession(), principal.getExtSourceName());
            UserExtSource ues = this.getUsersManagerBl().getUserExtSourceByExtLogin(getPerunSession(), es, principal.getActor());
            if (ues.getLoa() != principal.getExtSourceLoa()) {
                ues.setLoa(principal.getExtSourceLoa());
                this.getUsersManagerBl().updateUserExtSource(getPerunSession(), ues);
            }
            // Update last access for userExtSource
            this.getUsersManagerBl().updateUserExtSourceLastAccess(getPerunSession(), ues);
        } catch (ExtSourceNotExistsException | UserExtSourceNotExistsException | UserNotExistsException e) {
        // OK - We don't know user yet
        }
    }
    return new PerunSessionImpl(this, principal, client);
}
Also used : UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) ExtSource(cz.metacentrum.perun.core.api.ExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) PerunSessionImpl(cz.metacentrum.perun.core.impl.PerunSessionImpl)

Example 3 with UserNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.

the class MembersManagerBlImpl method createMember.

//MAIN METHOD
public Member createMember(PerunSession sess, Vo vo, SpecificUserType specificUserType, Candidate candidate, List<Group> groups, List<String> overwriteUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, AlreadyMemberException, ExtendMembershipException, GroupOperationsException {
    log.debug("Creating member for VO {} from candidate {}", vo, candidate);
    // Get the user
    User user = null;
    if (candidate.getUserExtSources() != null) {
        for (UserExtSource ues : candidate.getUserExtSources()) {
            // Check if the extSource exists
            ExtSource tmpExtSource = getPerunBl().getExtSourcesManagerBl().checkOrCreateExtSource(sess, ues.getExtSource().getName(), ues.getExtSource().getType());
            // Set the extSource ID
            ues.getExtSource().setId(tmpExtSource.getId());
            try {
                // Try to find the user by userExtSource
                user = getPerunBl().getUsersManagerBl().getUserByExtSourceNameAndExtLogin(sess, ues.getExtSource().getName(), ues.getLogin());
            } catch (UserExtSourceNotExistsException e) {
            // This is OK, non-existent userExtSource will be assigned later
            } catch (UserNotExistsException e) {
            // Ignore, we are only checking if the user exists
            } catch (ExtSourceNotExistsException e) {
            // Ignore, we are only checking if the user exists
            }
        }
    }
    // If user hasn't been found, then create him
    if (user == null) {
        user = new User();
        user.setFirstName(candidate.getFirstName());
        user.setLastName(candidate.getLastName());
        user.setMiddleName(candidate.getMiddleName());
        user.setTitleAfter(candidate.getTitleAfter());
        user.setTitleBefore(candidate.getTitleBefore());
        if (specificUserType.equals(specificUserType.SERVICE))
            user.setServiceUser(true);
        if (specificUserType.equals(specificUserType.SPONSORED))
            user.setSponsoredUser(true);
        // Store the user, this must be done in separate transaction
        user = getPerunBl().getUsersManagerBl().createUser(sess, user);
        log.debug("createMember: new user: {}", user);
    }
    // Assign missing userExtSource and update LoA
    if (candidate.getUserExtSources() != null) {
        for (UserExtSource userExtSource : candidate.getUserExtSources()) {
            try {
                UserExtSource currentUserExtSource = getPerunBl().getUsersManagerBl().getUserExtSourceByExtLogin(sess, userExtSource.getExtSource(), userExtSource.getLogin());
                // Update LoA
                currentUserExtSource.setLoa(userExtSource.getLoa());
                getPerunBl().getUsersManagerBl().updateUserExtSource(sess, currentUserExtSource);
            } catch (UserExtSourceNotExistsException e) {
                // Create userExtSource
                try {
                    getPerunBl().getUsersManagerBl().addUserExtSource(sess, user, userExtSource);
                } catch (UserExtSourceExistsException e1) {
                    throw new ConsistencyErrorException("Adding userExtSource which already exists: " + userExtSource);
                }
            }
        }
    }
    try {
        Member member = getMemberByUser(sess, vo, user);
        throw new AlreadyMemberException(member);
    } catch (MemberNotExistsException IGNORE) {
    }
    // Create the member
    Member member = getMembersManagerImpl().createMember(sess, vo, user);
    getPerunBl().getAuditer().log(sess, "{} created.", member);
    // Create the member's attributes
    List<Attribute> membersAttributes = new ArrayList<Attribute>();
    List<Attribute> usersAttributesToMerge = new ArrayList<>();
    List<Attribute> usersAttributesToModify = new ArrayList<>();
    if (candidate.getAttributes() != null) {
        for (String attributeName : candidate.getAttributes().keySet()) {
            AttributeDefinition attributeDefinition;
            try {
                attributeDefinition = getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attributeName);
            } catch (AttributeNotExistsException ex) {
                throw new InternalErrorException(ex);
            }
            Attribute attribute = new Attribute(attributeDefinition);
            attribute.setValue(getPerunBl().getAttributesManagerBl().stringToAttributeValue(candidate.getAttributes().get(attributeName), attribute.getType()));
            if (getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_MEMBER_ATTR_DEF) || getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_MEMBER_ATTR_OPT)) {
                // This is member's attribute
                membersAttributes.add(attribute);
            } else if (getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_USER_ATTR_DEF) || getPerunBl().getAttributesManagerBl().isFromNamespace(sess, attribute, AttributesManager.NS_USER_ATTR_OPT)) {
                if (overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty() && overwriteUserAttributes.contains(attribute.getName())) {
                    usersAttributesToModify.add(attribute);
                } else {
                    usersAttributesToMerge.add(attribute);
                }
            }
        }
    }
    // Store the attributes
    try {
        //if empty, skip setting or merging empty arrays of attributes at all
        if (!membersAttributes.isEmpty())
            getPerunBl().getAttributesManagerBl().setAttributes(sess, member, membersAttributes);
        if (!usersAttributesToMerge.isEmpty())
            getPerunBl().getAttributesManagerBl().mergeAttributesValues(sess, user, usersAttributesToMerge);
        if (!usersAttributesToModify.isEmpty())
            getPerunBl().getAttributesManagerBl().setAttributes(sess, user, usersAttributesToModify);
    } catch (WrongAttributeAssignmentException e) {
        throw new InternalErrorException(e);
    }
    // Set the initial membershipExpiration
    // 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) {
    // user has no loa defined - if required by VO, it will be stopped in checking method later
    } catch (WrongAttributeAssignmentException e) {
        throw new InternalErrorException(e);
    }
    // check if user can be member
    this.canBeMemberInternal(sess, vo, user, memberLoa, true);
    // set initial membership expiration
    this.extendMembership(sess, member);
    insertToMemberGroup(sess, member, vo);
    // add member also to all groups in list
    if (groups != null && !groups.isEmpty()) {
        for (Group group : groups) {
            try {
                perunBl.getGroupsManagerBl().addMember(sess, group, member);
            } catch (NotMemberOfParentGroupException ex) {
                throw new InternalErrorException("Member " + member + " can't be add to the group " + group + " because he is not member of it's parent group.", ex);
            } catch (GroupNotExistsException e) {
                throw new ConsistencyErrorException(e);
            }
        }
    }
    return member;
}
Also used : Group(cz.metacentrum.perun.core.api.Group) ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) User(cz.metacentrum.perun.core.api.User) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) ParentGroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.ParentGroupNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) Attribute(cz.metacentrum.perun.core.api.Attribute) WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) ArrayList(java.util.ArrayList) AlreadyMemberException(cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) UserExtSourceExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException) NotMemberOfParentGroupException(cz.metacentrum.perun.core.api.exceptions.NotMemberOfParentGroupException) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSource(cz.metacentrum.perun.core.api.ExtSource) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException) UserExtSourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException) RichMember(cz.metacentrum.perun.core.api.RichMember) Member(cz.metacentrum.perun.core.api.Member)

Example 4 with UserNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.UserNotExistsException in project perun by CESNET.

the class AttributesManagerBlImpl method getResourceRequiredAttributes.

public List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Member member, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException {
    this.checkMemberIsFromTheSameVoLikeResource(sess, member, resource);
    List<Attribute> attributes = new ArrayList<Attribute>();
    attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, resourceToGetServicesFrom, resource, member));
    if (workWithUserAttributes) {
        User user;
        Facility facility;
        try {
            user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId());
            facility = getPerunBl().getFacilitiesManagerBl().getFacilityById(sess, resource.getFacilityId());
        } catch (UserNotExistsException e) {
            throw new ConsistencyErrorException("Member has non-existent user.", e);
        } catch (FacilityNotExistsException e) {
            throw new ConsistencyErrorException("Resource has non-existent facility.", e);
        }
        attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, resourceToGetServicesFrom, facility, user));
        attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, resourceToGetServicesFrom, user));
        attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, resourceToGetServicesFrom, member));
    }
    return attributes;
}
Also used : ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) User(cz.metacentrum.perun.core.api.User) Attribute(cz.metacentrum.perun.core.api.Attribute) RichAttribute(cz.metacentrum.perun.core.api.RichAttribute) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) ArrayList(java.util.ArrayList) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) Facility(cz.metacentrum.perun.core.api.Facility)

Example 5 with UserNotExistsException

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());
}
Also used : User(cz.metacentrum.perun.core.api.User) Attribute(cz.metacentrum.perun.core.api.Attribute) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) Matcher(java.util.regex.Matcher) WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) ExtendMembershipException(cz.metacentrum.perun.core.api.exceptions.ExtendMembershipException) VoNotExistsException(cz.metacentrum.perun.core.api.exceptions.VoNotExistsException) WrongReferenceAttributeValueException(cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException) Vo(cz.metacentrum.perun.core.api.Vo) Pair(cz.metacentrum.perun.core.api.Pair) Pattern(java.util.regex.Pattern) ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) Calendar(java.util.Calendar) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Date(java.util.Date) ParseException(java.text.ParseException) WrongAttributeValueException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException)

Aggregations

UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)13 User (cz.metacentrum.perun.core.api.User)8 Attribute (cz.metacentrum.perun.core.api.Attribute)7 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)6 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)6 ArrayList (java.util.ArrayList)6 Facility (cz.metacentrum.perun.core.api.Facility)4 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)4 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)4 Group (cz.metacentrum.perun.core.api.Group)3 FacilityNotExistsException (cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException)3 GroupNotExistsException (cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException)3 AttributeDefinition (cz.metacentrum.perun.core.api.AttributeDefinition)2 ExtSource (cz.metacentrum.perun.core.api.ExtSource)2 Member (cz.metacentrum.perun.core.api.Member)2 PerunPrincipal (cz.metacentrum.perun.core.api.PerunPrincipal)2 Resource (cz.metacentrum.perun.core.api.Resource)2 RichAttribute (cz.metacentrum.perun.core.api.RichAttribute)2 UserExtSource (cz.metacentrum.perun.core.api.UserExtSource)2 Vo (cz.metacentrum.perun.core.api.Vo)2