Search in sources :

Example 11 with MemberNotExistsException

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

the class EventExecServiceResolverImpl method parseEvent.

@Override
public Map<Facility, Set<ExecService>> parseEvent(String event) throws InvalidEventMessageException, ServiceNotExistsException, InternalErrorException, PrivilegeException {
    log.info("I am going to process event:" + event);
    /**
		 * Expected string format as on:
		 * https://projekty.ics.muni.cz/perunv3/trac
		 * /wiki/PerunEngineDispatcherController event|x|[timestamp][Event
		 * header][Event data]
		 */
    String eventParsingPattern = "^\\[([a-zA-Z0-9+: ]+)\\]\\[([^\\]]+)\\]\\[(.*)\\]$";
    Pattern pattern = Pattern.compile(eventParsingPattern);
    Matcher matcher = pattern.matcher(event);
    boolean matchFound = matcher.find();
    if (matchFound) {
        log.debug("Message format matched ok...");
        // NOT USED ANYMORE: not applicable in dispatcher
        // String thisEngineID = matcher.group(1);
        // // This should indeed match the current Engine instance ID, so
        // let's compare it...
        // if (Integer.parseInt(thisEngineID) != Integer.parseInt((String)
        // propertiesBean.get("engine.unique.id"))) {
        // throw new InvalidEventMessageException("Wrong Engine ID. Was:" +
        // thisEngineID + ", Expected:" +
        // propertiesBean.get("engine.unique.id"));
        // }
        // // Not being used at the moment.
        // String timeStamp = matcher.group(2);
        // Header should provide information regarding the target facility.
        String eventHeader = matcher.group(2);
        // We expect the string to contain something like this:
        // facility.id=2 ???
        // String headerParsingPattern = ".*facility.id\\=([0-9]+).*";
        // Pattern headerPattern = Pattern.compile(headerParsingPattern);
        // Matcher headerMatcher = headerPattern.matcher(eventHeader);
        /*
			 * boolean headerMatchFound = headerMatcher.find();
			 * if(!headerMatchFound) { throw new InvalidEventMessageException(
			 * "Invalid event header. It does not contain the expected facility.id=value..."
			 * ); } int facilityId = Integer.parseInt(matcher.group(1));
			 * PerunSession perunSession =
			 * engineManager.getPerunSession(propertiesBean
			 * .getProperty("perun.principal")); Facility facility = null; try {
			 * facility = facilitiesManager.getFacilityById(perunSession,
			 * facilityId); } catch (FacilityNotExistsException e) { throw new
			 * InvalidEventMessageException
			 * ("Facility with ID "+facilityId+"does not exist.", e); } catch
			 * (InternalErrorException e) { throw new
			 * InvalidEventMessageException("Unknown error...", e); } catch
			 * (PrivilegeException e) { throw new
			 * InvalidEventMessageException("Principal "
			 * +propertiesBean.getProperty
			 * ("perun.principal")+" is not allowed to access that facility. ",
			 * e); }
			 */
        // Data should provide information regarding the target ExecService
        // (Processing rule).
        String eventData = matcher.group(3);
        log.debug("Event data to be parsed:" + eventData);
        // GET All Beans (only PerunBeans) from message
        List<PerunBean> listOfBeans = new ArrayList<PerunBean>();
        listOfBeans = AuditParser.parseLog(eventData);
        // Prepare variables
        AttributeDefinition attributeDefinition = null;
        Attribute attribute = null;
        Facility facility = null;
        Resource resource = null;
        Group group = null;
        User user = null;
        Member member = null;
        Service service = null;
        Host host = null;
        // etc. ?
        for (PerunBean pb : listOfBeans) {
            if (pb instanceof AttributeDefinition && pb instanceof Attribute) {
                attribute = (Attribute) pb;
            } else if (pb instanceof Facility) {
                facility = (Facility) pb;
            } else if (pb instanceof Resource) {
                resource = (Resource) pb;
            } else if (pb instanceof Group) {
                group = (Group) pb;
            } else if (pb instanceof User) {
                user = (User) pb;
            } else if (pb instanceof Member) {
                member = (Member) pb;
            } else if (pb instanceof Service) {
                service = (Service) pb;
            } else if (pb instanceof Host) {
                host = (Host) pb;
            }
        }
        // If there is any attribute, so create AttributeDefinition
        if (attribute != null) {
            attributeDefinition = new AttributeDefinition(attribute);
            log.debug("Attribute found in event. {}.", attributeDefinition);
        }
        List<Facility> facilitiesResolvedFromEvent = new ArrayList<Facility>();
        List<Resource> resourcesResolvedFromEvent = new ArrayList<Resource>();
        List<Service> servicesResolvedFromEvent = new ArrayList<Service>();
        // =============== Resolve facilities from event======================
        PerunSession perunSession = perun.getPerunSession(new PerunPrincipal(dispatcherPropertiesBean.getProperty("perun.principal.name"), dispatcherPropertiesBean.getProperty("perun.principal.extSourceName"), dispatcherPropertiesBean.getProperty("perun.principal.extSourceType")), new PerunClient());
        // Try to find FACILITY in event
        if (facility != null) {
            try {
                log.debug("Facility found in event. {}.", facility);
                facilitiesResolvedFromEvent.add(facility);
                resourcesResolvedFromEvent.addAll(perun.getFacilitiesManager().getAssignedResources(perunSession, facility));
            } catch (FacilityNotExistsException ex) {
                log.debug("Non-existing facility found while resolving event. id={}", facility.getId());
            }
        } else {
            // Try to find RESOURCE in event
            if (resource != null) {
                resourcesResolvedFromEvent.add(resource);
            } else {
                // Try to find GROUP in event
                if (group != null) {
                    try {
                        resourcesResolvedFromEvent = perun.getResourcesManager().getAssignedResources(perunSession, group);
                    } catch (GroupNotExistsException ex) {
                        log.debug("Non-existing group found while resolving event. id={}", group.getId());
                    }
                } else {
                    // try to find USER in event
                    if (user != null) {
                        try {
                            resourcesResolvedFromEvent = perun.getUsersManager().getAllowedResources(perunSession, user);
                        } catch (UserNotExistsException ex) {
                            log.debug("Non-existing user found while resolving event. id={}", user.getId());
                        }
                    } else {
                        // try to find MEMBER in event
                        if (member != null) {
                            try {
                                resourcesResolvedFromEvent = perun.getResourcesManager().getAllowedResources(perunSession, member);
                            } catch (MemberNotExistsException ex) {
                                log.debug("Non-existing member found while resolving event. id={}", member.getId());
                            }
                        } else {
                            // try to find HOST in event
                            if (host != null) {
                                try {
                                    log.debug("Host found in event.id= {}.", host.getId());
                                    facility = perun.getFacilitiesManager().getFacilityForHost(perunSession, host);
                                    facilitiesResolvedFromEvent.add(facility);
                                    resourcesResolvedFromEvent.addAll(perun.getFacilitiesManager().getAssignedResources(perunSession, facility));
                                } catch (FacilityNotExistsException ex) {
                                    log.debug("Host on non-existing facility found while resolving event. Host id={}", host.getId());
                                } catch (HostNotExistsException ex) {
                                    log.debug("Non-existing host found while resolving event. id={}", host.getId());
                                }
                            } else {
                                log.warn("No match found for this event. Event={}", event);
                            }
                        }
                    }
                }
            }
        }
        // TODO resolve more than one service
        if (service != null) {
            servicesResolvedFromEvent.add(service);
        }
        //List<Pair<List<ExecService>, Facility>> pairs = new ArrayList<Pair<List<ExecService>, Facility>>();
        Map<Facility, Set<ExecService>> result = new HashMap<Facility, Set<ExecService>>();
        for (Resource r : resourcesResolvedFromEvent) {
            Facility facilityResolvedFromEvent;
            List<Service> servicesResolvedFromResource;
            try {
                facilityResolvedFromEvent = perun.getResourcesManager().getFacility(perunSession, r);
                servicesResolvedFromResource = perun.getResourcesManager().getAssignedServices(perunSession, r);
                // process only services resolved from event if any
                if (!servicesResolvedFromEvent.isEmpty())
                    servicesResolvedFromResource.retainAll(servicesResolvedFromEvent);
            } catch (ResourceNotExistsException ex) {
                log.debug("Non-existing resource found while resolving event. Resource={}", r);
                // skip to next resource
                continue;
            }
            for (Service s : servicesResolvedFromResource) {
                // TODO: Optimize with an SQL query...
                List<ExecService> execServicesGenAndSend = generalServiceManager.listExecServices(perunSession, s.getId());
                List<ExecService> execServices = new ArrayList<ExecService>();
                for (ExecService execService : execServicesGenAndSend) {
                    if (execService.getExecServiceType().equals(ExecServiceType.SEND)) {
                        execServices.add(execService);
                    }
                }
                if (attributeDefinition != null) {
                    // remove from future processing services
                    // which don't require the found attribute
                    // TODO (CHECKME) This method can raise
                    // ServiceNotExistsException. Is it ok? Or it must be
                    // catch?
                    List<AttributeDefinition> serviceRequiredAttributes = perun.getAttributesManager().getRequiredAttributesDefinition(perunSession, s);
                    if (!serviceRequiredAttributes.contains(attributeDefinition))
                        continue;
                }
                if (!result.containsKey(facilityResolvedFromEvent)) {
                    result.put(facilityResolvedFromEvent, new HashSet<ExecService>(execServices));
                } else {
                    result.get(facilityResolvedFromEvent).addAll(execServices);
                }
            }
        }
        log.info("I am going to return " + result.size() + " facilities.");
        return result;
    } else {
        throw new InvalidEventMessageException("Message[" + event + "]");
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) User(cz.metacentrum.perun.core.api.User) HashSet(java.util.HashSet) Set(java.util.Set) Matcher(java.util.regex.Matcher) Attribute(cz.metacentrum.perun.core.api.Attribute) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Member(cz.metacentrum.perun.core.api.Member) Pattern(java.util.regex.Pattern) PerunSession(cz.metacentrum.perun.core.api.PerunSession) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) HostNotExistsException(cz.metacentrum.perun.core.api.exceptions.HostNotExistsException) Resource(cz.metacentrum.perun.core.api.Resource) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) Service(cz.metacentrum.perun.core.api.Service) Host(cz.metacentrum.perun.core.api.Host) ResourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ResourceNotExistsException) PerunBean(cz.metacentrum.perun.core.api.PerunBean) PerunClient(cz.metacentrum.perun.core.api.PerunClient) Facility(cz.metacentrum.perun.core.api.Facility) InvalidEventMessageException(cz.metacentrum.perun.dispatcher.exceptions.InvalidEventMessageException)

Example 12 with MemberNotExistsException

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

the class AttributesManagerBlImpl method setCoreAttributeWithoutCheck.

public void setCoreAttributeWithoutCheck(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException {
    if (!attribute.getName().equals("urn:perun:member:attribute-def:core:status")) {
        throw new InternalErrorException("We can set only urn:perun:member:attribute-def:core:status from member's core attributes. Others are not permitted.");
    }
    //defensive construction
    Member storedMember;
    try {
        storedMember = getPerunBl().getMembersManagerBl().getMemberById(sess, member.getId());
    } catch (MemberNotExistsException ex) {
        throw new ConsistencyErrorException(ex);
    }
    if (!member.equals(storedMember))
        throw new InternalErrorException("You wan't to store core attribute for member which is not equals to member from DB (with same Id)");
    String methodName = "set" + Character.toUpperCase(attribute.getFriendlyName().charAt(0)) + attribute.getFriendlyName().substring(1);
    Method method;
    try {
        method = member.getClass().getMethod(methodName, Class.forName(attribute.getType()));
    } catch (NoSuchMethodException ex) {
        throw new InternalErrorException("Bad core attribute definition. " + attribute, ex);
    } catch (ClassNotFoundException ex) {
        throw new InternalErrorException("Bad core attribute type. " + attribute, ex);
    }
    try {
        method.invoke(member, attribute.getValue());
    } catch (IllegalAccessException ex) {
        throw new InternalErrorException(ex);
    } catch (InvocationTargetException ex) {
        throw new WrongAttributeValueException(ex);
    } catch (IllegalArgumentException ex) {
        throw new WrongAttributeValueException(attribute, "Probably bad type of value", ex);
    } catch (RuntimeException ex) {
        throw new InternalErrorException(ex);
    }
    member = getPerunBl().getMembersManagerBl().updateMember(sess, member);
}
Also used : ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) WrongAttributeValueException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException) Member(cz.metacentrum.perun.core.api.Member)

Example 13 with MemberNotExistsException

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

the class EventProcessorImpl method resolveMessage.

/**
	 * Get a message and id of this message.
	 * Parse the message and decide which way will be further processed.
	 * Using patterns and objects to choose the way.
	 *
	 * Additional Information:
	 * -> For user and serviceUser there is the same behavior.
	 * -> If there is only serviceUser (not serviceUser and user) the behavior for serviceUser is the same like for user (in LDAP)
	 * -> If there are 2 groups in one message, expecting the first is subGroup and second is parentGroup
	 *
	 * Possible ways (first and only 1 possible way with the lowest number is choose):
	 * -> 1) GROUP and MEMBER exist
	 *   -> 1.1) if member status is valid => add member to group in LDAP
	 *   -> 1.2) if member was totally removed from group (totally means there is no direct or indirect existence of member in this group yet)
	 *           => remove member from this group in LDAP
	 * -> 2) GROUP and PARENT_GROUP exist
	 *   -> 2.1) if there is message with adding subgroup => add group like subgroup of parentGroup in LDAP
	 * -> 3) GROUP AND RESOURCE exist
	 *   -> 3.1) if there is message with adding group to resource => add resource to group (like attribute) in LDAP
	 *   -> 3.2) if there is message with removing group from resource => remove resource from group (like attribute) in LDAP
	 * -> 4) only RESOURCE exists (resource must be before group because of
	 *   -> 4.1) if there is message with deleting resource => delete this resource from LDAP
	 *   -> 4.2) if there is message with createing resource => create this resource in LDAP
	 *   -> 4.3) if there is message with updating resource => update this resource in LDAP
	 * -> 5) only GROUP exists
	 *   -> 5.1) if there is message with deleting group => delete this group from LDAP
	 *   -> 5.2) if there is message with creating group => create this group in LDAP
	 *   -> 5.3) if there is message with updating group => update this group in LDAP
	 * -> 6) only MEMBER exists (RPC CALLING used)
	 *   -> 6.1) if there is message with changing of member state to valid => add member to all groups in LDAP where he needs to be
	 *   -> 6.2) if there is message with changing of member state to other than valid => remove member from all groups in LDAP where is needed
	 * -> 7) only VO exists
	 *   -> 7.1) if there is message with deleting vo => delete this vo from LDAP
	 *   -> 7.2) if there is message with creating vo => create this vo in LDAP
	 *   -> 7.3) if there is message with updating vo => update this vo in LDAP
	 * -> 8) USER and USER_EXT_SOURCE exist
	 *   -> 8.1) if there is message with adding userExtSource (IDP) to user => create or update attribute of user in LDAP
	 *   -> 8.2) if there is message with removing userExtSource (IDP) from user => remove or update attribute of user in LDAP
	 * -> 9) USER and ATTRIBUTE exist
	 *   -> 9.1) if there is message with setting attribute to user => set Attribute to user in LDAP
	 * -> 10) USER and ATTRIBUTE_DEFINITION exist
	 *   -> 10.1) if there is message with removing attribute from user => remove Attribute from user in LDAP
	 * -> 11) only USER exists
	 *   -> 11.1) if there is message with deleting user => delete user from LDAP
	 *   -> 11.2) if there is message with creating user => create user in LDAP
	 *   -> 11.3) if there is message with updating user => update user in LDAP
	 *   -> 11.4) if there is message with removing all attribute from user => remove all attributes from user in LDAP (only removeable attributes)
	 * -> 12) FACILITY and ATTRIBUTE exist
	 *   -> 12.1) if there is message with setting attribute to facility => set Attribute to resources (assigned to facility) in LDAP
	 * -> 13) FACILITY and ATTRIBUTE_DEF exist
	 *   -> 13.1) if there is message with removing attribute from facility => remove Attribute from resources (assigned to facility) in LDAP
	 * -> 14) in all other cases
	 *   -> 14.1) always => only log some information
	 *
	 * @param msg message which need to be parse and resolve
	 * @param idOfMessage id of paring/resolving message
	 *
	 * @throws InternalErrorException when some internal error in core occurs
	 */
protected void resolveMessage(String msg, Integer idOfMessage) throws InternalErrorException {
    List<PerunBean> listOfBeans = new ArrayList<PerunBean>();
    listOfBeans = AuditParser.parseLog(msg);
    //TemporaryDebug information for controling parsing of message.
    if (!listOfBeans.isEmpty()) {
        int i = 0;
        for (PerunBean p : listOfBeans) {
            i++;
            if (p != null)
                log.debug("There is object number " + i + ") " + p.serializeToString());
            else
                log.debug("There is unknow object which is null");
        }
    }
    //Fill perunBeans
    emptyAndFillPerunBeans(listOfBeans);
    //Log debug data for looking in messages
    log.debug("MessageNumber=" + idOfMessage + " -- OBJECTS: " + this.member + '/' + this.group + '/' + this.facility + "/" + this.parentGroup + '/' + this.vo + '/' + this.resource + '/' + this.user + '/' + this.attribute + '/' + this.attributeDef + '/' + this.userExtSource);
    //If specific user is the only one user in message, so behavior will be same for him like for any other user!
    if (this.specificUser != null && this.user == null)
        this.user = this.specificUser;
    // 1) IF GROUP AND MEMBER WERE FOUND, TRY TO WORK WITH GROUP-MEMBER SPECIFIC OPERATIONS
    if (this.group != null && this.member != null) {
        // 1.1) ONLY FOR VALID MEMBER WE ADD HIM TO THE GROUP IN LDAP
        if (this.member.getStatus().equals(Status.VALID)) {
            Matcher addedTo = addedToPattern.matcher(msg);
            if (addedTo.find()) {
                if (!ldapConnector.isAlreadyMember(this.member, this.group))
                    ldapConnector.addMemberToGroup(this.member, this.group);
            }
        }
        // 1.2) MEMBER WILL BE REMOVED FROM GROUP
        //Matcher removedFrom = removedFromPattern.matcher(msg);
        Matcher totallyRemovedFrom = totallyRemovedFromPatter.matcher(msg);
        if (totallyRemovedFrom.find()) {
            if (ldapConnector.isAlreadyMember(this.member, this.group))
                ldapConnector.removeMemberFromGroup(this.member, this.group);
        }
    // 2) IF 2 GROUPS WERE FOUND, TRY TO WORK WITH PARENTGROUP-SUBGROUP SPECIFIC OPERATIONS
    } else if (this.group != null && this.parentGroup != null) {
        Matcher newSubGroup = subGroupPattern.matcher(msg);
        // 2.1) ADD GROUP AS SUBGROUP TO PARENTGROUP
        if (newSubGroup.find()) {
            ldapConnector.addGroupAsSubGroup(this.group, this.parentGroup);
        }
    // 3) IF GROUP AND RESOURCE WERE FOUND, TRY TO WORK WITH GROUP-RESOURCE SPECIFIC OPERATIONS
    } else if (this.group != null && this.resource != null) {
        Matcher assigned = assignGroupToResource.matcher(msg);
        Matcher removed = removeGroupFromResource.matcher(msg);
        // 3.1) ADD NEW RESOURCE FOR GROUP IN LDAP
        if (assigned.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.ADD_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.ADD_ATTRIBUTE, this.resource);
        // 3.2) REMOVE RESOURCE FROM GROUP IN LDAP
        } else if (removed.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.resource);
        }
    // 4) IF ONLY RESOURCE WERE FOUND, TRY TO WORK WITH RESOURCE SPECIFIC OPERATIONS
    } else if (this.resource != null) {
        Matcher deleted = deletedResourcePattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 4.1) RESOURCE WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteResource(resource);
        // 4.2) RESOURCE WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createResource(resource, getFacilityEntityIdValue(resource.getFacilityId()));
        // 4.3) RESOURCE WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.resource.getName()));
            if (this.resource.getDescription() != null && !this.resource.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.resource.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateResourceAttributes(attributes, this.resource);
        }
    // 5) IF ONLY GROUP WERE FOUND, TRY TO WORK WITH GROUP SPECIFIC OPERATIONS
    } else if (this.group != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher newGroup = newGroupPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 5.1) GROUP WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.removeGroup(this.group);
        // 5.2) GROUP WILL BE CREATED
        } else if (newGroup.find()) {
            ldapConnector.addGroup(this.group);
        // 5.3) GROUP WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.group.getName()));
            replaceList.add(new Pair("perunUniqueGroupName", ldapConnector.getVoShortName(this.group.getVoId()) + ":" + this.group.getName()));
            if (this.group.getDescription() != null && !this.group.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.group.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateGroupAttributes(attributes, this.group);
        }
    // 6) IF MEMBER WAS FOUND, TRY TO WORK WITH MEMBER SPECIFIC OPERATIONS (! RPC CALLING used there !)
    } else if (this.member != null) {
        Matcher validated = validatedPattern.matcher(msg);
        Matcher otherStateOfMember = otherStateOfMemberPattern.matcher(msg);
        // 6.1) MEMBER WAS VALIDATED, NEED TO ADD HIM TO ALL GROUPS
        if (validated.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (!ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.addMemberToGroup(this.member, g);
            }
        // 6.2) MEMBER STATE WAS CHANGED TO OTHER STATE THAN VALIDATE
        } else if (otherStateOfMember.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.removeMemberFromGroup(this.member, g);
            }
        }
    // 7) IF VO WAS FOUND, TRY TO WORK WITH VO SPECIFIC OPERATIONS
    } else if (this.vo != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 7.1) VO WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteVo(this.vo);
        // 7.2) VO WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createVo(this.vo);
        // 7.3) VO WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("description", this.vo.getName()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateVoAttributes(attributes, this.vo);
        }
    // 8) IF USER AND USEREXTSOURCE WERE FOUND, TRY TO WORK WITH USER-USEREXTSOURCE SPECIFIC OPERATIONS (LIKE SET EXT LOGINS FOR IDP EXTSOURCES)
    } else if (this.user != null && this.userExtSource != null) {
        Matcher addExtSource = addUserExtSource.matcher(msg);
        Matcher removeExtSource = removeUserExtSource.matcher(msg);
        // 8.1) ADD ATTRIBUTE WITH IDP EXTSOURCE
        if (addExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.ADD_ATTRIBUTE, user);
                }
            }
        // 8.2) REMOVE ATTRIBUTE WITH IDP EXTSOURCE
        } else if (removeExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            }
        }
    // 9) IF USER AND ATTRIBUTE WERE FOUND, TRY TO WORK WITH USER-ATTR SPECIFIC OPERATIONS (LIKE SET USER ATTRIBUTES)
    } else if (this.user != null && this.attribute != null) {
        Matcher set = userSetPattern.matcher(msg);
        // 9.1) SOME USER ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attribute.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attribute.getName());
            //USER PREFERREDMAIL WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                //this mean change of attribute preferredMail in User
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("preferredMail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                    updateUserAttribute("mail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                        updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapConnector.userAttributeExist(this.user, "mail")) {
                        updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER ORGANIZATION WILL BE SET
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("o", (String) attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "o")) {
                        updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER CERT DNS WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                Map<String, String> certDNsMap = new HashMap<String, String>();
                if (this.attribute.getValue() != null)
                    certDNsMap = (Map) this.attribute.getValue();
                else
                    certDNsMap = null;
                if (certDNsMap == null || certDNsMap.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                        updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    Set<String> certSubjectsWithPrefixes = ((Map) this.attribute.getValue()).keySet();
                    Set<String> certSubjectsWithoutPrefixes = new HashSet<>();
                    //remove prefixes from certificates
                    for (String key : certSubjectsWithPrefixes) {
                        certSubjectsWithoutPrefixes.add(key.replaceFirst("^[0-9]+[:]", ""));
                    }
                    String[] subjectsArray = Arrays.copyOf(certSubjectsWithoutPrefixes.toArray(), certSubjectsWithoutPrefixes.toArray().length, String[].class);
                    ldapConnector.updateUsersCertSubjects(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER LIBRARY IDs WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                List<String> libraryIDsList = new ArrayList<>();
                if (this.attribute.getValue() != null)
                    libraryIDsList = (ArrayList) this.attribute.getValue();
                else
                    libraryIDsList = null;
                if (libraryIDsList == null || libraryIDsList.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                        updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    String[] subjectsArray = Arrays.copyOf(libraryIDsList.toArray(), libraryIDsList.toArray().length, String[].class);
                    ldapConnector.updateUsersLibraryIds(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER UID NUMBER WILL BE SET
            } else if (uidMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), String.valueOf((Integer) this.attribute.getValue()), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER LOGIN WILL BE SET
            } else if (loginMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    //if login is from loginNamespace (eg. EINFRA) (new value), then userPassword must be set or modified
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("userPassword", "{SASL}" + this.attribute.getValue() + "@" + ldapProperties.getLdapLoginNamespace(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    }
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        if (ldapConnector.userAttributeExist(this.user, "userPassword")) {
                            updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                        }
                    }
                }
            }
        }
    // 10) IF USER AND ATTRIBTUE DEFINITION WERE FOUND, TRY TO WORK WITH USER-ATTRDEF SPECIFIC OPERATIONS
    } else if (this.user != null && attributeDef != null) {
        Matcher remove = userRemovePattern.matcher(msg);
        // 10.1) REMOVE SPECIFIC USER ATTRIBUTE
        if (remove.find() && ldapConnector.userExist(this.user)) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attributeDef.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attributeDef.getName());
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                    updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapConnector.userAttributeExist(this.user, "mail")) {
                    updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            //TODO: organization (user) will not exists
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (ldapConnector.userAttributeExist(this.user, "o")) {
                    updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                    updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                    updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (uidMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (loginMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("login;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attributeDef.getFriendlyNameParameter())) {
                    if (ldapConnector.userPasswordExists(this.user)) {
                        updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            }
        }
    // 11) IF ONLY USER WAS FOUND, TRY TO WORK WITH USER SPECIFIC OPERATIONS
    } else if (this.user != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        Matcher removedAllAttrs = userAllAttrsRemovedPattern.matcher(msg);
        // 11.1) DELETE USER
        if (deleted.find()) {
            ldapConnector.deleteUser(this.user);
        // 11.2) CREATE USER
        } else if (created.find()) {
            ldapConnector.createUser(this.user);
        // 11.3) UPDATE USER
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            String firstName = this.user.getFirstName();
            String lastName = this.user.getLastName();
            if (firstName == null)
                firstName = "";
            if (lastName == null || lastName.isEmpty())
                lastName = "N/A";
            replaceList.add(new Pair("sn", lastName));
            replaceList.add(new Pair("cn", firstName + " " + lastName));
            // IF firstName is empty, maybe need to be removed first
            if (firstName.isEmpty()) {
                //if first name exists and new one is empty, then remove it, else do nothing
                if (ldapConnector.userAttributeExist(this.user, "givenName")) {
                    updateUserAttribute("givenName", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else {
                //if first name is not empty, replace it by new first name
                replaceList.add(new Pair("givenName", firstName));
            }
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateUserAttributes(attributes, this.user);
        // 11.4) REMOVE ALL USER ATTRIBUTES
        } else if (removedAllAttrs.find()) {
            if (ldapConnector.userExist(this.user)) {
                Attributes usersAttrs = ldapConnector.getAllUsersAttributes(this.user);
                List<ModificationItem> listOfItems = new ArrayList<ModificationItem>();
                if (usersAttrs != null) {
                    NamingEnumeration<? extends Attribute> attributesEnumeration;
                    attributesEnumeration = usersAttrs.getAll();
                    try {
                        while (attributesEnumeration.hasMore()) {
                            Attribute attr = attributesEnumeration.nextElement();
                            if (attr != null && attr.getID() != null) {
                                if (isRemovableUserAttribute(attr.getID())) {
                                    ModificationItem item = new ModificationItem(LdapOperation.REMOVE_ATTRIBUTE.getCode(), attr);
                                    listOfItems.add(item);
                                }
                            }
                        }
                    } catch (NamingException ex) {
                        throw new InternalErrorException("Error at Deleting All Users Attribute, throw namingException.", ex);
                    }
                }
                if (!listOfItems.isEmpty()) {
                    ModificationItem[] items = Arrays.copyOf(listOfItems.toArray(), listOfItems.toArray().length, ModificationItem[].class);
                    ldapConnector.updateUser(this.user, items);
                }
            }
        }
    //12) IF FACILITY AND ATTRIBUTE TO SET WAS FOUND
    } else if (this.facility != null && attribute != null) {
        Matcher set = facilitySetPattern.matcher(msg);
        // 12.1) SOME FACILITY ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            //EntityID WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    //this mean change of attribute entityID in all assigned resources
                    if (this.attribute.getValue() != null) {
                        for (Resource res : resources) {
                            updateResourceAttribute("entityID", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, res);
                        }
                    } else {
                        for (Resource res : resources) {
                            if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                                updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                            }
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    //13) IF FACILITY AND ATTRIBUTE DEF TO REMOVE WAS FOUND
    } else if (this.facility != null && attributeDef != null) {
        Matcher remove = facilityRemovePattern.matcher(msg);
        // 13.1) REMOVE SPECIFIC FACILITY ATTRIBUTE
        if (remove.find()) {
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    for (Resource res : resources) {
                        if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                            updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    // 14) IN OTHER CASES
    } else {
        log.debug("Nothing to resolve for message with number : " + idOfMessage);
    }
}
Also used : LdapOperation(cz.metacentrum.perun.ldapc.beans.LdapOperation) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 14 with MemberNotExistsException

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

the class MembersManagerBlImpl method findRichMembersInVo.

public List<RichMember> findRichMembersInVo(PerunSession sess, Vo vo, String searchString) throws InternalErrorException {
    List<User> users = getPerunBl().getUsersManagerBl().findUsers(sess, searchString);
    List<Member> members = new ArrayList<Member>();
    for (User user : users) {
        try {
            members.add(getMembersManagerImpl().getMemberByUserId(sess, vo, user.getId()));
        } catch (MemberNotExistsException e) {
        // User is not member of this VO
        }
    }
    return this.convertMembersToRichMembers(sess, this.setAllMembersSameType(members, MembershipType.DIRECT));
}
Also used : User(cz.metacentrum.perun.core.api.User) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) ArrayList(java.util.ArrayList) RichMember(cz.metacentrum.perun.core.api.RichMember) Member(cz.metacentrum.perun.core.api.Member)

Aggregations

MemberNotExistsException (cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException)14 ArrayList (java.util.ArrayList)11 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)10 Member (cz.metacentrum.perun.core.api.Member)9 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)7 User (cz.metacentrum.perun.core.api.User)6 RichMember (cz.metacentrum.perun.core.api.RichMember)5 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)5 Map (java.util.Map)5 Group (cz.metacentrum.perun.core.api.Group)4 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 Attribute (cz.metacentrum.perun.core.api.Attribute)3 AttributeDefinition (cz.metacentrum.perun.core.api.AttributeDefinition)3 ExtSource (cz.metacentrum.perun.core.api.ExtSource)3 ExtSourceNotExistsException (cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException)3 GroupNotExistsException (cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException)3 VoNotExistsException (cz.metacentrum.perun.core.api.exceptions.VoNotExistsException)3 Candidate (cz.metacentrum.perun.core.api.Candidate)2