Search in sources :

Example 1 with PerunSession

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

the class Utils method generateAllGroupsToWriter.

/**
	 * Method generate all Groups to the text for using in LDIF.
	 * Write all these information to writer in perunInitializer object.
	 *
	 * @param perunInitializer need to be loaded to get all needed dependencies
	 *
	 * @throws InternalErrorException if some problem with initializer or objects in perun-core
	 * @throws IOException if some problem with writer
	 */
public static void generateAllGroupsToWriter(PerunInitializer perunInitializer) throws InternalErrorException, IOException {
    //Load basic variables
    if (perunInitializer == null)
        throw new InternalErrorException("PerunInitializer must be loaded before using in generating methods!");
    PerunSession perunSession = perunInitializer.getPerunSession();
    PerunBl perun = perunInitializer.getPerunBl();
    BufferedWriter writer = perunInitializer.getOutputWriter();
    //First get all vos
    List<Vo> vos = perun.getVosManagerBl().getVos(perunSession);
    //Then from all vos get all assigned groups and generate data about them to the writer
    for (Vo vo : vos) {
        List<Group> groups;
        groups = perun.getGroupsManagerBl().getGroups(perunSession, vo);
        for (Group group : groups) {
            String dn = "dn: ";
            String oc1 = "objectclass: top";
            String oc3 = "objectclass: perunGroup";
            String cn = "cn: ";
            String perunVoId = "perunVoId: ";
            String parentGroup = "perunParentGroup: ";
            String parentGroupId = "perunParentGroupId: ";
            String perunGroupId = "perunGroupId: ";
            String owner = "owner: ";
            String description = "description: ";
            String perunUniqueGroupName = "perunUniqueGroupName: ";
            List<Member> members;
            members = perun.getGroupsManagerBl().getGroupMembers(perunSession, group, Status.VALID);
            perunGroupId += String.valueOf(group.getId());
            perunVoId += String.valueOf(group.getVoId());
            dn += "perunGroupId=" + group.getId() + ",perunVoId=" + group.getVoId() + ",dc=perun,dc=cesnet,dc=cz";
            cn += group.getName();
            perunUniqueGroupName += vo.getShortName() + ":" + group.getName();
            if (group.getDescription() != null)
                description += group.getDescription();
            if (group.getParentGroupId() != null) {
                parentGroupId += group.getParentGroupId();
                parentGroup += "perunGroupId=" + group.getParentGroupId() + ",perunVoId=" + group.getVoId() + ",dc=perun,dc=cesnet,dc=cz";
            }
            List<Member> admins = new ArrayList<>();
            writer.write(dn + '\n');
            writer.write(oc1 + '\n');
            writer.write(oc3 + '\n');
            writer.write(cn + '\n');
            writer.write(perunUniqueGroupName + '\n');
            writer.write(perunGroupId + '\n');
            writer.write(perunVoId + '\n');
            if (group.getDescription() != null)
                writer.write(description + '\n');
            if (group.getParentGroupId() != null) {
                writer.write(parentGroupId + '\n');
                writer.write(parentGroup + '\n');
            }
            //ADD Group Members
            for (Member m : members) {
                writer.write("uniqueMember: " + "perunUserId=" + m.getUserId() + ",ou=People,dc=perun,dc=cesnet,dc=cz");
                writer.write('\n');
            }
            //ADD resources which group is assigned to
            List<Resource> associatedResources;
            associatedResources = perun.getResourcesManagerBl().getAssignedResources(perunSession, group);
            for (Resource r : associatedResources) {
                writer.write("assignedToResourceId: " + r.getId());
                writer.write('\n');
            }
            //FOR NOW No groups has owner
            writer.write(owner + '\n');
            writer.write('\n');
        }
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) PerunSession(cz.metacentrum.perun.core.api.PerunSession) ArrayList(java.util.ArrayList) Resource(cz.metacentrum.perun.core.api.Resource) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) BufferedWriter(java.io.BufferedWriter) Vo(cz.metacentrum.perun.core.api.Vo) Member(cz.metacentrum.perun.core.api.Member)

Example 2 with PerunSession

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

the class Utils method generateAllResourcesToWriter.

/**
	 * Method generate all Resources to the text for using in LDIF.
	 * Write all these information to writer in perunInitializer object.
	 *
	 * @param perunInitializer need to be loaded to get all needed dependencies
	 *
	 * @throws InternalErrorException if some problem with initializer or objects in perun-core
	 * @throws IOException if some problem with writer
	 */
public static void generateAllResourcesToWriter(PerunInitializer perunInitializer) throws InternalErrorException, IOException {
    //Load basic variables
    if (perunInitializer == null)
        throw new InternalErrorException("PerunInitializer must be loaded before using in generating methods!");
    PerunSession perunSession = perunInitializer.getPerunSession();
    PerunBl perun = perunInitializer.getPerunBl();
    BufferedWriter writer = perunInitializer.getOutputWriter();
    //first get all Vos
    List<Vo> vos = perun.getVosManagerBl().getVos(perunSession);
    //Then from every Vo get all assigned resources and write their data to the writer
    for (Vo vo : vos) {
        List<Resource> resources;
        resources = perun.getResourcesManagerBl().getResources(perunSession, vo);
        for (Resource resource : resources) {
            //Read facility attribute entityID and write it for the resource if exists
            Facility facility = null;
            try {
                facility = perun.getFacilitiesManagerBl().getFacilityById(perunSession, resource.getFacilityId());
            } catch (FacilityNotExistsException ex) {
                throw new InternalErrorException("Can't found facility of this resource " + resource, ex);
            }
            Attribute entityIDAttr = null;
            try {
                entityIDAttr = perun.getAttributesManagerBl().getAttribute(perunSession, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID");
            } catch (AttributeNotExistsException | WrongAttributeAssignmentException ex) {
                throw new InternalErrorException("Problem with loading entityID attribute of facility " + facility, ex);
            }
            String dn = "dn: ";
            String oc1 = "objectclass: top";
            String oc3 = "objectclass: perunResource";
            String cn = "cn: ";
            String perunVoId = "perunVoId: ";
            String perunFacilityId = "perunFacilityId: ";
            String perunResourceId = "perunResourceId: ";
            String description = "description: ";
            String entityID = "entityID: ";
            perunVoId += String.valueOf(resource.getVoId());
            perunFacilityId += String.valueOf(resource.getFacilityId());
            perunResourceId += String.valueOf(resource.getId());
            dn += "perunResourceId=" + resource.getId() + ",perunVoId=" + resource.getVoId() + ",dc=perun,dc=cesnet,dc=cz";
            cn += resource.getName();
            String descriptionValue = resource.getDescription();
            if (descriptionValue != null) {
                if (descriptionValue.matches("^[ ]*$"))
                    descriptionValue = null;
            }
            writer.write(dn + '\n');
            writer.write(oc1 + '\n');
            writer.write(oc3 + '\n');
            writer.write(cn + '\n');
            writer.write(perunResourceId + '\n');
            if (descriptionValue != null)
                writer.write(description + descriptionValue + '\n');
            writer.write(perunVoId + '\n');
            writer.write(perunFacilityId + '\n');
            if (entityIDAttr.getValue() != null)
                writer.write(entityID + (String) entityIDAttr.getValue() + '\n');
            //ADD resources which group is assigned to
            List<Group> associatedGroups = perun.getResourcesManagerBl().getAssignedGroups(perunSession, resource);
            for (Group g : associatedGroups) {
                writer.write("assignedGroupId: " + g.getId());
                writer.write('\n');
            }
            writer.write('\n');
        }
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) PerunSession(cz.metacentrum.perun.core.api.PerunSession) Attribute(cz.metacentrum.perun.core.api.Attribute) WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) Resource(cz.metacentrum.perun.core.api.Resource) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) BufferedWriter(java.io.BufferedWriter) Vo(cz.metacentrum.perun.core.api.Vo) Facility(cz.metacentrum.perun.core.api.Facility)

Example 3 with PerunSession

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

the class RegistrarBaseIntegrationTest method createVOformIntegrationTest.

@Test
@Transactional
public void createVOformIntegrationTest() throws PerunException, PrivilegeException, InternalErrorException {
    System.out.println("createVOformIntegrationTest()");
    // get form for VO (if not exists, it's created)
    ApplicationForm applicationForm = registrarManager.getFormForVo(vo);
    // put in standard options
    ApplicationFormItem i0 = new ApplicationFormItem();
    i0.setShortname("pokecI");
    i0.setType(ApplicationFormItem.Type.HTML_COMMENT);
    i0.getTexts(CS).setLabel("Vyplňte, prosím, přihlášku.");
    i0.getTexts(EN).setLabel("Fill in the initial application, please.");
    i0.setApplicationTypes(Arrays.asList(Application.AppType.INITIAL));
    registrarManager.addFormItem(session, applicationForm, i0);
    ApplicationFormItem i0b = new ApplicationFormItem();
    i0b.setShortname("pokecE");
    i0b.setType(ApplicationFormItem.Type.HTML_COMMENT);
    i0b.getTexts(CS).setLabel("Zkontrolujte, prosím, před podáním žádosti o prodloužení účtu, svoje údaje.");
    i0b.getTexts(EN).setLabel("Please check you personal data before applying for account extension.");
    i0b.setApplicationTypes(Arrays.asList(Application.AppType.EXTENSION));
    registrarManager.addFormItem(session, applicationForm, i0b);
    ApplicationFormItem i1 = new ApplicationFormItem();
    i1.setShortname("titleBefore");
    i1.setPerunDestinationAttribute("urn:perun:user:attribute-def:core:titleBefore");
    i1.setRequired(false);
    i1.setType(ApplicationFormItem.Type.TEXTFIELD);
    i1.getTexts(CS).setLabel("Titul před jménem");
    i1.getTexts(CS).setHelp("Ing.,RNDr.,pplk., atd.");
    i1.getTexts(EN).setLabel("Title before name");
    registrarManager.addFormItem(session, applicationForm, i1);
    ApplicationFormItem i2 = new ApplicationFormItem();
    i2.setShortname("displayName");
    i2.setPerunDestinationAttribute("urn:perun:user:attribute-def:core:displayName");
    i2.setType(ApplicationFormItem.Type.FROM_FEDERATION_HIDDEN);
    i2.setRequired(true);
    i2.setFederationAttribute("Shib-Person-displayName");
    registrarManager.addFormItem(session, applicationForm, i2);
    ApplicationFormItem i2a = new ApplicationFormItem();
    i2a.setShortname("firstName");
    i2a.setPerunDestinationAttribute("urn:perun:user:attribute-def:core:firstName");
    i2a.setType(ApplicationFormItem.Type.TEXTFIELD);
    i2a.setRequired(true);
    i2a.setFederationAttribute("Shib-Person-givenName");
    i2a.getTexts(CS).setLabel("Jméno");
    i2a.getTexts(EN).setLabel("First name");
    registrarManager.addFormItem(session, applicationForm, i2a);
    ApplicationFormItem i2b = new ApplicationFormItem();
    i2b.setShortname("lastName");
    i2b.setPerunDestinationAttribute("urn:perun:user:attribute-def:core:lastName");
    i2b.setType(ApplicationFormItem.Type.TEXTFIELD);
    i2b.setRequired(true);
    i2b.setFederationAttribute("Shib-Person-sureName");
    i2b.getTexts(CS).setLabel("Příjmení");
    i2b.getTexts(EN).setLabel("Last name");
    registrarManager.addFormItem(session, applicationForm, i2b);
    ApplicationFormItem i3 = new ApplicationFormItem();
    i3.setShortname("titleAfter");
    i3.setPerunDestinationAttribute("urn:perun:user:attribute-def:core:titleAfter");
    i3.setRequired(false);
    i3.setType(ApplicationFormItem.Type.TEXTFIELD);
    i3.getTexts(CS).setLabel("Titul za jménem");
    i3.getTexts(CS).setHelp("Ph.D., CSc., DrSc., atd.");
    i3.getTexts(EN).setLabel("Title after name");
    registrarManager.addFormItem(session, applicationForm, i3);
    ApplicationFormItem i4 = new ApplicationFormItem();
    i4.setShortname("preferredMail");
    i4.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:preferredMail");
    i4.setRequired(true);
    i4.setType(ApplicationFormItem.Type.VALIDATED_EMAIL);
    i4.getTexts(CS).setLabel("Email");
    i4.getTexts(CS).setHelp("Bude ověřen zasláním zprávy.");
    i4.getTexts(EN).setLabel("Email");
    i4.getTexts(EN).setHelp("Will be validated by sending an email message.");
    registrarManager.addFormItem(session, applicationForm, i4);
    ApplicationFormItem i5 = new ApplicationFormItem();
    i5.setShortname("organization");
    i5.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:organization");
    i5.setType(ApplicationFormItem.Type.FROM_FEDERATION_SHOW);
    i5.setRequired(true);
    i5.setFederationAttribute("Shib-Person-o");
    i5.getTexts(CS).setLabel("Organizace");
    i5.getTexts(EN).setLabel("Organisation");
    registrarManager.addFormItem(session, applicationForm, i5);
    ApplicationFormItem i5b = new ApplicationFormItem();
    i5b.setShortname("affiliation");
    i5b.setPerunDestinationAttribute("urn:perun:member:attribute-def:opt:eduPersonAffiliation");
    i5b.setType(ApplicationFormItem.Type.FROM_FEDERATION_HIDDEN);
    i5b.setRequired(true);
    i5b.setFederationAttribute("Shib-EP-Affiliation");
    registrarManager.addFormItem(session, applicationForm, i5b);
    ApplicationFormItem i5c = new ApplicationFormItem();
    i5c.setShortname("mail");
    i5c.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:mail");
    i5c.setType(ApplicationFormItem.Type.FROM_FEDERATION_HIDDEN);
    i5c.setRequired(true);
    i5c.setFederationAttribute("Shib-InetOrgPerson-mail");
    registrarManager.addFormItem(session, applicationForm, i5c);
    ApplicationFormItem i6 = new ApplicationFormItem();
    i6.setShortname("vyuziti");
    i6.setPerunDestinationAttribute("urn:perun:member:attribute-def:opt:registrationNote");
    i6.setRequired(true);
    i6.setType(ApplicationFormItem.Type.TEXTAREA);
    i6.getTexts(CS).setLabel("Popis plánovaného využití MetaCentra");
    i6.getTexts(CS).setHelp("Uveďte stručně, jakou činností se hodláte v MetaCentru zabývat. Uveďte také Vaše nadstandardní požadavky, požadavky, které nejsou pokryty položkami formuláře, případně jiné skutečnosti, které považujete za podstatné pro vyřízení přihlášky.");
    i6.getTexts(EN).setLabel("Description of planned activity");
    i6.getTexts(EN).setHelp("Describe shortly activity which you plane to perform at MetaCentrum. Mention your nonstandard demands, requests which are not covered in this form, eventually anything you consider important for this registration too.");
    registrarManager.addFormItem(session, applicationForm, i6);
    ApplicationFormItem i7 = new ApplicationFormItem();
    i7.setShortname("phone");
    i7.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:phone");
    i7.setRequired(true);
    i7.setRegex("\\+*[0-9 ]*");
    i7.setType(ApplicationFormItem.Type.TEXTFIELD);
    i7.getTexts(CS).setLabel("Telefon");
    i7.getTexts(EN).setLabel("Phone");
    registrarManager.addFormItem(session, applicationForm, i7);
    ApplicationFormItem i8 = new ApplicationFormItem();
    i8.setShortname("workplace");
    i8.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:workplace");
    i8.setRequired(true);
    i8.setType(ApplicationFormItem.Type.TEXTAREA);
    i8.getTexts(CS).setLabel("Katedra/ústav/výzkumná skupina");
    i8.getTexts(EN).setLabel("Department/research group");
    registrarManager.addFormItem(session, applicationForm, i8);
    ApplicationFormItem i9 = new ApplicationFormItem();
    i9.setShortname("jazyk");
    i9.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:preferredLanguage");
    i9.setRequired(true);
    i9.setType(ApplicationFormItem.Type.SELECTIONBOX);
    i9.getTexts(CS).setLabel("Preferovaný jazyk");
    i9.getTexts(CS).setHelp("Zvolte jazyk, ve kterém chcete dostávát novinky a upozornění.");
    i9.getTexts(CS).setOptions("cs#česky|en#anglicky");
    i9.getTexts(EN).setLabel("Preffered language");
    i9.getTexts(EN).setHelp("Choose the language in which you want to receive news and notifications.");
    i9.getTexts(EN).setOptions("en#English|cs#Czech");
    registrarManager.addFormItem(session, applicationForm, i9);
    ApplicationFormItem i10 = new ApplicationFormItem();
    i10.setShortname("username");
    i10.setRequired(true);
    i10.setRegex("[a-z][a-z0-9_]+");
    i10.setType(ApplicationFormItem.Type.TEXTFIELD);
    i10.setPerunDestinationAttribute("urn:perun:user:attribute-def:def:login-namespace:meta");
    i10.getTexts(CS).setLabel("Zvolte si uživatelské jméno");
    i10.getTexts(CS).setHelp("Uživatelské jméno musí začínat malým písmenem, a obsahovat pouze malá písmena, číslice a podtržení. Doporučujeme délku nanejvýš 8 znaků.");
    i10.getTexts(EN).setLabel("Choose you user name");
    i10.getTexts(EN).setHelp("User name must begin with a small letter, and can contain only small letters, digits and underscores. We recommend length max 8 characters.");
    i10.setApplicationTypes(Arrays.asList(Application.AppType.INITIAL));
    registrarManager.addFormItem(session, applicationForm, i10);
    ApplicationFormItem i11 = new ApplicationFormItem();
    i11.setShortname("heslo");
    i11.setRequired(true);
    i11.setRegex("\\p{Print}{8,20}");
    i11.setType(ApplicationFormItem.Type.PASSWORD);
    i11.getTexts(CS).setLabel("Heslo");
    i11.getTexts(CS).setHelp("Heslo musí být 8 až 20 znaků dlouhé, a obsahovat aspoň 3 písmena a 1 znak jiný než písmeno.");
    i11.getTexts(EN).setLabel("Password");
    i11.getTexts(EN).setHelp("Password must be from 8 up to 20 characters long and contain printable characters only.");
    i11.setApplicationTypes(Arrays.asList(Application.AppType.INITIAL));
    registrarManager.addFormItem(session, applicationForm, i11);
    ApplicationFormItem i12 = new ApplicationFormItem();
    i12.setShortname("pokec");
    i12.setType(ApplicationFormItem.Type.HTML_COMMENT);
    i12.getTexts(CS).setLabel("Stiskem tlačítka 'Podat žádost o členství ve VO MetaCentrum' souhlaste s pravidly využití VO MetaCentrum.");
    i12.getTexts(EN).setLabel("By pressing the button you agree with MetaCentrum rules.");
    i12.setApplicationTypes(Arrays.asList(Application.AppType.INITIAL));
    registrarManager.addFormItem(session, applicationForm, i12);
    ApplicationFormItem i13 = new ApplicationFormItem();
    i13.setShortname("souhlasI");
    i13.setType(ApplicationFormItem.Type.SUBMIT_BUTTON);
    i13.getTexts(CS).setLabel("Podat žádost o členství ve VO MetaCentrum");
    i13.getTexts(EN).setLabel("Apply for membership in the MetaCentrum VO");
    i13.setApplicationTypes(Arrays.asList(Application.AppType.INITIAL));
    registrarManager.addFormItem(session, applicationForm, i13);
    ApplicationFormItem i13b = new ApplicationFormItem();
    i13b.setShortname("souhlasE");
    i13b.setType(ApplicationFormItem.Type.SUBMIT_BUTTON);
    i13b.getTexts(CS).setLabel("Podat žádost o prodloužení účtu");
    i13b.getTexts(EN).setLabel("Apply for account extension");
    i13b.setApplicationTypes(Arrays.asList(Application.AppType.EXTENSION));
    registrarManager.addFormItem(session, applicationForm, i13b);
    // update form not to auto aprove
    applicationForm.setAutomaticApproval(false);
    registrarManager.updateForm(session, applicationForm);
    // test returned app form
    assertEquals("Application form not same as expected", applicationForm, registrarManager.getFormForVo(vo));
    // test form items
    List<ApplicationFormItem> items = registrarManager.getFormItems(session, applicationForm);
    assertTrue("Item i0 was not returned from form", items.contains(i0));
    assertTrue("Item i0b was not returned from form", items.contains(i0b));
    assertTrue("Item i1 was not returned from form", items.contains(i1));
    assertTrue("Item i2 was not returned from form", items.contains(i2));
    assertTrue("Item i2a was not returned from form", items.contains(i2a));
    assertTrue("Item i2b was not returned from form", items.contains(i2b));
    assertTrue("Item i3 was not returned from form", items.contains(i3));
    assertTrue("Item i4 was not returned from form", items.contains(i4));
    assertTrue("Item i5 was not returned from form", items.contains(i5));
    assertTrue("Item i5b was not returned from form", items.contains(i5b));
    assertTrue("Item i5c was not returned from form", items.contains(i5c));
    assertTrue("Item i6 was not returned from form", items.contains(i6));
    assertTrue("Item i7 was not returned from form", items.contains(i7));
    assertTrue("Item i8 was not returned from form", items.contains(i8));
    assertTrue("Item i9 was not returned from form", items.contains(i9));
    assertTrue("Item i10 was not returned from form", items.contains(i10));
    assertTrue("Item i11 was not returned from form", items.contains(i11));
    assertTrue("Item i12 was not returned from form", items.contains(i12));
    assertTrue("Item i13 was not returned from form", items.contains(i13));
    assertTrue("Item i13b was not returned from form", items.contains(i13b));
    Random random = new Random();
    PerunSession applicant = perun.getPerunSession(new PerunPrincipal("rumcajs" + random.nextInt(100000) + "@raholec.cz", "http://www.raholec.cz/idp/", ExtSourcesManager.EXTSOURCE_IDP), new PerunClient());
}
Also used : ApplicationForm(cz.metacentrum.perun.registrar.model.ApplicationForm) ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) PerunSession(cz.metacentrum.perun.core.api.PerunSession) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Test(org.junit.Test) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with PerunSession

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

the class AttributesManagerBlImpl method initialize.

protected void initialize() throws InternalErrorException {
    log.debug("AttributesManagerBlImpl initialize started.");
    //Get PerunSession
    String attributesManagerInitializator = "attributesManagerBlImplInitializator";
    PerunPrincipal pp = new PerunPrincipal(attributesManagerInitializator, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL);
    PerunSession sess = perunBl.getPerunSession(pp, new PerunClient());
    //Prepare all attribute definition from system perun
    Set<AttributeDefinition> allAttributesDef = new HashSet<AttributeDefinition>();
    allAttributesDef.addAll(this.getAttributesDefinition(sess));
    //Basic state of all maps (record for every existing attributeDefinitions)
    for (AttributeDefinition ad : allAttributesDef) {
        dependencies.put(ad, new HashSet<AttributeDefinition>());
        strongDependencies.put(ad, new HashSet<AttributeDefinition>());
        inverseDependencies.put(ad, new HashSet<AttributeDefinition>());
        inverseStrongDependencies.put(ad, new HashSet<AttributeDefinition>());
        allDependencies.put(ad, new HashSet<AttributeDefinition>());
    }
    log.debug("Dependencies and StrongDependencies filling started.");
    //Fill dep and strongDep maps
    for (AttributeDefinition ad : allAttributesDef) {
        AttributesModuleImplApi module = null;
        List<String> depList = new ArrayList<String>();
        List<String> strongDepList = new ArrayList<String>();
        Set<AttributeDefinition> depSet = new HashSet<AttributeDefinition>();
        Set<AttributeDefinition> strongDepSet = new HashSet<AttributeDefinition>();
        //Return null to object if module not exist
        Object attributeModule = getAttributesManagerImpl().getAttributesModule(sess, ad);
        //If there is any existing module
        if (attributeModule != null) {
            module = (AttributesModuleImplApi) attributeModule;
            depList = module.getDependencies();
            strongDepList = module.getStrongDependencies();
            //Fill Set of dependencies
            for (String s : depList) {
                if (!s.endsWith("*")) {
                    try {
                        AttributeDefinition attrDef = getAttributeDefinition(sess, s);
                        depSet.add(attrDef);
                    } catch (AttributeNotExistsException ex) {
                        log.error("For attribute name " + s + "can't be found attributeDefinition at Inicialization in AttributesManagerBlImpl.");
                    }
                //If there is something like AttributesManager.NS_RESOURCE_ATTR_DEF + ":unixGID-namespace" + ":*" we need to replace * by all possibilities
                } else {
                    List<String> allVariantOfDependence = getAllSimilarAttributeNames(sess, s.substring(0, s.length() - 2));
                    for (String variant : allVariantOfDependence) {
                        try {
                            AttributeDefinition attrDef = getAttributeDefinition(sess, variant);
                            depSet.add(attrDef);
                        } catch (AttributeNotExistsException ex) {
                            log.error("For attribute name " + variant + "can't be found attributeDefinition at Inicialization in AttributesManagerBlImpl.");
                        }
                    }
                }
            }
            //Fil Set of strongDependencies
            for (String s : strongDepList) {
                if (!s.endsWith("*")) {
                    try {
                        AttributeDefinition attrDef = getAttributeDefinition(sess, s);
                        strongDepSet.add(attrDef);
                    } catch (AttributeNotExistsException ex) {
                        log.error("For attribute name " + s + "can't be found attributeDefinition at Inicialization in AttributesManagerBlImpl.");
                    }
                //If there is something like AttributesManager.NS_RESOURCE_ATTR_DEF + ":unixGID-namespace" + ":*" we need to replace * by all possibilities
                } else {
                    List<String> allVariantOfDependence = getAllSimilarAttributeNames(sess, s.substring(0, s.length() - 2));
                    for (String variant : allVariantOfDependence) {
                        try {
                            AttributeDefinition attrDef = getAttributeDefinition(sess, variant);
                            strongDepSet.add(attrDef);
                        } catch (AttributeNotExistsException ex) {
                            log.error("For attribute name " + variant + "can't be found attributeDefinition at Inicialization in AttributesManagerBlImpl.");
                        }
                    }
                }
            }
        }
        dependencies.put(ad, depSet);
        strongDependencies.put(ad, strongDepSet);
    }
    log.debug("Dependencies and StrongDependencies was filled successfully.");
    log.debug("InverseDependencies and InverseStrongDependencies filling started.");
    //First create inversion map for simple dependencies
    Set<AttributeDefinition> depSet = dependencies.keySet();
    for (AttributeDefinition key : depSet) {
        Set<AttributeDefinition> keySet = new HashSet<AttributeDefinition>();
        keySet = dependencies.get(key);
        for (AttributeDefinition keySetItem : keySet) {
            Set<AttributeDefinition> changeSet = new HashSet<AttributeDefinition>();
            changeSet = inverseDependencies.get(keySetItem);
            changeSet.add(key);
        //inverseDependencies.put(keySetItem, changeSet);
        }
    }
    //Second create inversion map for strong dependencies
    depSet = strongDependencies.keySet();
    for (AttributeDefinition key : depSet) {
        Set<AttributeDefinition> keySet = new HashSet<AttributeDefinition>();
        keySet = strongDependencies.get(key);
        for (AttributeDefinition keySetItem : keySet) {
            Set<AttributeDefinition> changeSet = new HashSet<AttributeDefinition>();
            changeSet = inverseStrongDependencies.get(keySetItem);
            changeSet.add(key);
        //inverseDependencies.put(keySetItem, changeSet);
        }
    }
    log.debug("InverseDependencies and InverseStrongDependencies was filled successfully.");
    log.debug("Cycle test of InverseStrongDependencies started.");
    if (isMapOfAttributesDefCyclic(inverseStrongDependencies)) {
        log.error("There is cycle in inverseStrongDependencies so map of All attribute will be not created!");
    } else {
        log.debug("Cycle test of InverseStrongDependencies was successfull.");
        log.debug("Filling map of allDependencies started.");
        for (AttributeDefinition key : allDependencies.keySet()) {
            List<AttributeDefinition> stackingAttributes = new ArrayList<AttributeDefinition>();
            Set<AttributeDefinition> dependenciesOfAttribute = new HashSet<AttributeDefinition>();
            dependenciesOfAttribute.addAll(inverseStrongDependencies.get(key));
            dependenciesOfAttribute.addAll(inverseDependencies.get(key));
            stackingAttributes.addAll(inverseStrongDependencies.get(key));
            while (!stackingAttributes.isEmpty()) {
                AttributeDefinition firstAttr = stackingAttributes.get(0);
                stackingAttributes.remove(firstAttr);
                dependenciesOfAttribute.addAll(inverseStrongDependencies.get(firstAttr));
                dependenciesOfAttribute.addAll(inverseDependencies.get(firstAttr));
                stackingAttributes.addAll(inverseStrongDependencies.get(firstAttr));
            }
            allDependencies.put(key, dependenciesOfAttribute);
        }
        log.debug("Map of allDependencies was filled successfully.");
    }
    //DEBUG creating file with all dependencies of all attributes (180+- on devel)
    /*String pathToFile = "./AllDependencies.log";
			File f = new File(pathToFile);
			try {
			f.createNewFile();
			PrintWriter writer;
			writer = new PrintWriter(new FileWriter(f, true));
			int i=1;
			for(AttributeDefinition ad: allDependencies.keySet()) {
			writer.println(i + ") " + ad.toString());
			for(AttributeDefinition a: allDependencies.get(ad)) {
			writer.println(" ---> " + a);
			}
			i++;
			}
			writer.close();
			} catch (IOException ex) {
			log.error("Error at saving AllDependencies file.");
			}*/
    //DEBUG end
    log.debug("AttributesManagerBlImpl initialize ended.");
}
Also used : PerunSession(cz.metacentrum.perun.core.api.PerunSession) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) ArrayList(java.util.ArrayList) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) HashSet(java.util.HashSet) UserVirtualAttributesModuleImplApi(cz.metacentrum.perun.core.implApi.modules.attributes.UserVirtualAttributesModuleImplApi) AttributesModuleImplApi(cz.metacentrum.perun.core.implApi.modules.attributes.AttributesModuleImplApi)

Example 5 with PerunSession

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

Aggregations

PerunSession (cz.metacentrum.perun.core.api.PerunSession)7 Group (cz.metacentrum.perun.core.api.Group)4 Member (cz.metacentrum.perun.core.api.Member)4 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)4 PerunBl (cz.metacentrum.perun.core.bl.PerunBl)4 BufferedWriter (java.io.BufferedWriter)4 ArrayList (java.util.ArrayList)4 Attribute (cz.metacentrum.perun.core.api.Attribute)3 PerunClient (cz.metacentrum.perun.core.api.PerunClient)3 PerunPrincipal (cz.metacentrum.perun.core.api.PerunPrincipal)3 Resource (cz.metacentrum.perun.core.api.Resource)3 Vo (cz.metacentrum.perun.core.api.Vo)3 HashSet (java.util.HashSet)3 AttributeDefinition (cz.metacentrum.perun.core.api.AttributeDefinition)2 Facility (cz.metacentrum.perun.core.api.Facility)2 User (cz.metacentrum.perun.core.api.User)2 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)2 FacilityNotExistsException (cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException)2 Host (cz.metacentrum.perun.core.api.Host)1 PerunBean (cz.metacentrum.perun.core.api.PerunBean)1