Search in sources :

Example 1 with Pair

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

the class urn_perun_group_resource_attribute_def_def_systemUnixGroupName method checkAttributeValue.

public void checkAttributeValue(PerunSessionImpl sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
    String groupName = (String) attribute.getValue();
    Attribute isSystemGroup = new Attribute();
    if (groupName == null) {
        try {
            isSystemGroup = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, resource, group, A_GR_systemIsUnixGroup);
        } catch (AttributeNotExistsException ex) {
            throw new ConsistencyErrorException("Not exist Attribute " + A_GR_systemIsUnixGroup + " for group " + group, ex);
        }
        if (isSystemGroup.getValue() != null && (Integer) isSystemGroup.getValue() == 1) {
            throw new WrongReferenceAttributeValueException(attribute, "Attribute cant be null if " + group + " on " + resource + " is system unix group.");
        }
    } else if (groupName.matches("^[-_a-zA-Z0-9]*$") != true) {
        throw new WrongAttributeValueException(attribute, "String with other chars than numbers, letters or symbols _ and - is not allowed value.");
    }
    //Get facility for the resource
    Facility facility = sess.getPerunBl().getResourcesManagerBl().getFacility(sess, resource);
    //List of pairs (group and resource) which has the attribute with the value
    List<Pair<Group, Resource>> listGroupPairsResource = sess.getPerunBl().getGroupsManagerBl().getGroupResourcePairsByAttribute(sess, attribute);
    //Searching through all pairs and if is not checking group/resource/attribute, then try for being on the same facility, if yes then throw exception but only if these groups have not the same GID too.
    for (Pair<Group, Resource> p : listGroupPairsResource) {
        if (!p.getLeft().equals(group) || !p.getRight().equals(resource)) {
            Facility facilityForTest = sess.getPerunBl().getResourcesManagerBl().getFacility(sess, p.getRight());
            Attribute group1GID = new Attribute();
            Attribute group2GID = new Attribute();
            try {
                group1GID = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, resource, group, A_GR_systemUnixGID);
            } catch (AttributeNotExistsException ex) {
                throw new ConsistencyErrorException("Attribute " + A_GR_systemUnixGID + " not exists for group " + group + " and resource " + resource, ex);
            }
            try {
                group2GID = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, p.getRight(), p.getLeft(), A_GR_systemUnixGID);
            } catch (AttributeNotExistsException ex) {
                throw new ConsistencyErrorException("Attribute " + A_GR_systemUnixGID + " not exists for group " + p.getLeft() + " and resource " + p.getRight(), ex);
            }
            if (facilityForTest.equals(facility) && (group1GID.getValue() != null ? (!group1GID.getValue().equals(group2GID.getValue())) : group2GID != null)) {
                throw new WrongAttributeValueException(attribute, "Group name " + groupName + "is allready used by another group-resource and these have not the same GID and GroupName.  " + p.getLeft() + " " + p.getRight());
            }
        }
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) Attribute(cz.metacentrum.perun.core.api.Attribute) Resource(cz.metacentrum.perun.core.api.Resource) Facility(cz.metacentrum.perun.core.api.Facility) Pair(cz.metacentrum.perun.core.api.Pair)

Example 2 with Pair

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

the class urn_perun_user_attribute_def_virt_organizationsWithLoa method initializeMapOfExtSourceName.

private void initializeMapOfExtSourceName() {
    mapOfExtSourcesNames.put("https://idp.upce.cz/idp/shibboleth", new Pair("Univerzita Pardubice", "University in Pardubice"));
    mapOfExtSourcesNames.put("https://idp.slu.cz/idp/shibboleth", new Pair("Univerzita v Opavě", "University in Opava"));
    mapOfExtSourcesNames.put("https://login.feld.cvut.cz/idp/shibboleth", new Pair("Fakulta elektrotechnická, České vysoké učení technické v Praze", "Faculty of Electrical Engineering, Czech Technical University In Prague"));
    mapOfExtSourcesNames.put("https://www.vutbr.cz/SSO/saml2/idp", new Pair("Vysoké učení technické v Brně", "Brno University of Technology"));
    mapOfExtSourcesNames.put("https://shibboleth.nkp.cz/idp/shibboleth", new Pair("Národní knihovna České republiky", "The National Library of the Czech Republic"));
    mapOfExtSourcesNames.put("https://idp2.civ.cvut.cz/idp/shibboleth", new Pair("České vysoké účení technické v Praze", "Czech Technical University In Prague"));
    mapOfExtSourcesNames.put("https://shibbo.tul.cz/idp/shibboleth", new Pair("Technická univerzita v Liberci", "Technical University of Liberec"));
    mapOfExtSourcesNames.put("https://idp.mendelu.cz/idp/shibboleth", new Pair("Mendlova univerzita v Brně", "Mendel University in Brno"));
    mapOfExtSourcesNames.put("https://cas.cuni.cz/idp/shibboleth", new Pair("Univerzita Karlova v Praze", "Charles University in Prague"));
    mapOfExtSourcesNames.put("https://wsso.vscht.cz/idp/shibboleth", new Pair("Vysoká škola chemicko-technická v Praze", "Institute of Chemical Technology Prague"));
    mapOfExtSourcesNames.put("https://idp.vsb.cz/idp/shibboleth", new Pair("VŠB - Technická univerzita Ostrava", "VSB – Technical University of Ostrava"));
    mapOfExtSourcesNames.put("https://whoami.cesnet.cz/idp/shibboleth", new Pair("CESNET, z. s. p. o.", "CESNET, a. l. e."));
    mapOfExtSourcesNames.put("https://helium.jcu.cz/idp/shibboleth", new Pair("Jihočeská univerzita v Českých Budějovicích", "University of South Bohemia"));
    mapOfExtSourcesNames.put("https://idp.ujep.cz/idp/shibboleth", new Pair("Univerzita Jana Evangelisty Purkyně v Ústí nad Labem", "Jan Evangelista Purkyne University in Usti nad Labem"));
    mapOfExtSourcesNames.put("https://idp.amu.cz/idp/shibboleth", new Pair("Akademie múzických umění v Praze", "Academy of Performing Arts in Prague"));
    mapOfExtSourcesNames.put("https://idp.lib.cas.cz/idp/shibboleth", new Pair("Knihovna AV ČR, v. v. i.", "Academy of Sciences Library"));
    mapOfExtSourcesNames.put("https://shibboleth.mzk.cz/simplesaml/metadata.xml", new Pair("Moravská zemská knihovna", "Moravian  Library"));
    mapOfExtSourcesNames.put("https://idp2.ics.muni.cz/idp/shibboleth", new Pair("Masarykova univerzita", "Masaryk University"));
    mapOfExtSourcesNames.put("https://idp.upol.cz/idp/shibboleth", new Pair("Univerzita Palackého v Olomouci", "Palacky University, Olomouc"));
    mapOfExtSourcesNames.put("https://idp.fnplzen.cz/idp/shibboleth", new Pair("FN Plzeň", "FN Plzen"));
    mapOfExtSourcesNames.put("https://id.vse.cz/idp/shibboleth", new Pair("Vysoká škola ekonomická v Praze", "University of Economics, Prague"));
    mapOfExtSourcesNames.put("https://shib.zcu.cz/idp/shibboleth", new Pair("Západočeská univerzita v Plzni", "University of West Bohemia"));
    mapOfExtSourcesNames.put("https://idptoo.osu.cz/simplesaml/saml2/idp/metadata.php", new Pair("Ostravská Univerzita v Ostravě", "University of Ostrava"));
    mapOfExtSourcesNames.put("https://login.ics.muni.cz/idp/shibboleth", new Pair("MetaCentrum", "MetaCentrum"));
}
Also used : Pair(cz.metacentrum.perun.core.api.Pair)

Example 3 with Pair

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

the class urn_perun_member_resource_attribute_def_virt_isBanned method resolveVirtualAttributeValueChange.

@Override
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException {
    List<String> resolvingMessages = new ArrayList<>();
    if (message == null)
        return resolvingMessages;
    Matcher banModificationMatcher = banModification.matcher(message);
    List<Pair<Resource, Member>> listOfAffectedObjects = new ArrayList<>();
    String operationType = "";
    if (banModificationMatcher.find()) {
        try {
            String banType = banModificationMatcher.group(1);
            operationType = banModificationMatcher.group(2);
            int firstHolderId = Integer.valueOf(banModificationMatcher.group(3));
            int secondHolderId = Integer.valueOf(banModificationMatcher.group(4));
            if (operationType.equals(OPERATION_UPDATED)) {
                operationType = OPERATION_SET;
            } else if (!operationType.equals(OPERATION_SET) && !operationType.equals(OPERATION_REMOVED)) {
                throw new InternalErrorException("Type of operation '" + operationType + "' is unknown by module.");
            }
            if (banType.equals(BanOnResource.class.getSimpleName())) {
                Member member = perunSession.getPerunBl().getMembersManagerBl().getMemberById(perunSession, firstHolderId);
                Resource resource = perunSession.getPerunBl().getResourcesManagerBl().getResourceById(perunSession, secondHolderId);
                listOfAffectedObjects.add(new Pair(resource, member));
            } else if (banType.equals(BanOnFacility.class.getSimpleName())) {
                User user = perunSession.getPerunBl().getUsersManagerBl().getUserById(perunSession, firstHolderId);
                Facility facility = perunSession.getPerunBl().getFacilitiesManagerBl().getFacilityById(perunSession, secondHolderId);
                listOfAffectedObjects = getAffectedMemberResourceObjects(perunSession, user, facility);
            } else {
                throw new InternalErrorException("Type of ban '" + banType + "' is unkown by module.");
            }
        } catch (Exception e) {
            log.error("Can't resolve virtual attribute value change for " + this.getClass().getSimpleName() + " module because of exception.", e);
            //return empty array, do not throw exception because it can create problems
            return new ArrayList<>();
        }
    }
    for (Pair<Resource, Member> affectedObjects : listOfAffectedObjects) {
        try {
            Attribute attrVirtMemberResourceIsBanned = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, affectedObjects.getLeft(), affectedObjects.getRight(), AttributesManager.NS_MEMBER_RESOURCE_ATTR_VIRT + ":isBanned");
            resolvingMessages.add(attrVirtMemberResourceIsBanned.serializeToString() + " " + operationType + " for " + affectedObjects.getLeft().serializeToString() + " and " + affectedObjects.getRight().serializeToString());
        } catch (AttributeNotExistsException ex) {
            //This means that attribute isBanned not exists at all so we can skip this process
            log.info("Virtual attribute {} not exists.", this.getClass().getSimpleName());
            break;
        }
    }
    return resolvingMessages;
}
Also used : User(cz.metacentrum.perun.core.api.User) Matcher(java.util.regex.Matcher) Attribute(cz.metacentrum.perun.core.api.Attribute) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) ArrayList(java.util.ArrayList) Resource(cz.metacentrum.perun.core.api.Resource) BanOnResource(cz.metacentrum.perun.core.api.BanOnResource) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) WrongReferenceAttributeValueException(cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) BanOnResource(cz.metacentrum.perun.core.api.BanOnResource) BanOnFacility(cz.metacentrum.perun.core.api.BanOnFacility) Facility(cz.metacentrum.perun.core.api.Facility) Member(cz.metacentrum.perun.core.api.Member) Pair(cz.metacentrum.perun.core.api.Pair)

Example 4 with Pair

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

the class SchedulingPoolImpl method checkTasksDb.

@Override
public void checkTasksDb() {
    log.debug("Going to cross-check tasks in database...");
    for (Pair<Task, Integer> pair : taskManager.listAllTasksAndClients()) {
        Task task = pair.getLeft();
        DispatcherQueue taskQueue = dispatcherQueuePool.getDispatcherQueueByClient(pair.getRight());
        TaskStatus status = task.getStatus();
        if (status == null) {
            task.setStatus(TaskStatus.NONE);
        }
        Task local_task = null;
        TaskStatus local_status = null;
        log.debug("  checking task " + task.toString());
        if (taskQueue == null) {
            log.warn("  there is no task queue for client " + pair.getRight());
        // continue;
        }
        synchronized (tasksById) {
            Pair<Task, DispatcherQueue> local_pair = tasksById.get(task.getId());
            if (local_pair != null) {
                local_task = local_pair.getLeft();
            }
            if (local_task == null) {
                local_task = tasksByServiceAndFacility.get(new Pair<Integer, Integer>(task.getExecServiceId(), task.getFacilityId()));
            }
            if (local_task == null) {
                for (TaskStatus sts : TaskStatus.class.getEnumConstants()) {
                    List<Task> tasklist = pool.get(sts);
                    if (tasklist != null) {
                        local_task = tasklist.get(task.getId());
                    }
                    if (local_task != null) {
                        local_status = sts;
                        break;
                    }
                }
            }
        }
        if (local_task == null) {
            try {
                log.debug("  task not found in any of local structures, adding fresh");
                addToPool(task, taskQueue);
            } catch (InternalErrorException e) {
                log.error("Error adding task to the local structures: " + e.getMessage());
            }
        } else {
            synchronized (tasksById) {
                if (!tasksById.containsKey(local_task.getId())) {
                    log.debug("  task not known by id, adding");
                    tasksById.put(local_task.getId(), new Pair<Task, DispatcherQueue>(local_task, taskQueue));
                }
                if (!tasksByServiceAndFacility.containsKey(new Pair<Integer, Integer>(local_task.getExecServiceId(), local_task.getFacilityId()))) {
                    log.debug("  task not known by ExecService and Facility, adding");
                    tasksByServiceAndFacility.put(new Pair<Integer, Integer>(local_task.getExecServiceId(), local_task.getFacilityId()), task);
                }
                if (local_status != null && local_status != local_task.getStatus()) {
                    log.debug("  task listed with wrong status, removing");
                    if (pool.get(local_status) != null) {
                        pool.get(local_status).remove(local_task.getId());
                    } else {
                        log.error("  no task list for status " + local_status);
                    }
                }
                if (pool.get(local_task.getStatus()) != null && !pool.get(local_task.getStatus()).contains(local_task)) {
                    log.debug("  task not listed with its status, adding");
                    pool.get(local_task.getStatus()).add(local_task);
                }
            }
        }
    }
}
Also used : Task(cz.metacentrum.perun.taskslib.model.Task) DispatcherQueue(cz.metacentrum.perun.dispatcher.jms.DispatcherQueue) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) TaskStatus(cz.metacentrum.perun.taskslib.model.Task.TaskStatus) Pair(cz.metacentrum.perun.core.api.Pair)

Example 5 with Pair

use of cz.metacentrum.perun.core.api.Pair 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

Pair (cz.metacentrum.perun.core.api.Pair)12 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)8 Attribute (cz.metacentrum.perun.core.api.Attribute)4 Facility (cz.metacentrum.perun.core.api.Facility)4 Resource (cz.metacentrum.perun.core.api.Resource)4 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)3 WrongReferenceAttributeValueException (cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException)3 DispatcherQueue (cz.metacentrum.perun.dispatcher.jms.DispatcherQueue)3 Task (cz.metacentrum.perun.taskslib.model.Task)3 ArrayList (java.util.ArrayList)3 BanOnResource (cz.metacentrum.perun.core.api.BanOnResource)2 Group (cz.metacentrum.perun.core.api.Group)2 Member (cz.metacentrum.perun.core.api.Member)2 User (cz.metacentrum.perun.core.api.User)2 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)2 FacilityNotExistsException (cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException)2 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)2 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)2 WrongAttributeValueException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException)2 Date (java.util.Date)2