public void checkAttributeValue(PerunSessionImpl perunSession, String key, Attribute attribute)
     throws InternalErrorException, WrongAttributeValueException,
         WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
   Integer maxGID = (Integer) attribute.getValue();
   if (maxGID != null) {
     if (maxGID < 1)
       throw new WrongAttributeValueException(attribute, "Attribute value must be min 1.");
     try {
       Attribute minGIDAttr =
           perunSession
               .getPerunBl()
               .getAttributesManagerBl()
               .getAttribute(
                   perunSession,
                   key,
                   AttributesManager.NS_ENTITYLESS_ATTR_DEF + ":namespace-minGID");
     } catch (AttributeNotExistsException ex) {
       throw new ConsistencyErrorException("Attribute namespace-minGID is supposed to exist.", ex);
     }
     Integer minGID = (Integer) attribute.getValue();
     if (minGID != null) {
       if (maxGID < minGID)
         throw new WrongAttributeValueException(
             attribute,
             "Attribute value must be more than minGID. MinGID = "
                 + minGID
                 + ", and maxGID try to set = "
                 + maxGID);
     }
   }
 }
  @Override
  public void checkAttributeValue(
      PerunSessionImpl perunSession, Resource resource, Attribute attribute)
      throws InternalErrorException, WrongAttributeValueException,
          WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
    Attribute attrDefaultFilesLimit = null;
    Integer defaultFilesQuota = null;
    Integer defaultFilesLimit = null;

    // Get DefaultFilesLimit attribute
    try {
      attrDefaultFilesLimit =
          perunSession
              .getPerunBl()
              .getAttributesManagerBl()
              .getAttribute(perunSession, resource, A_R_defaultFilesLimit);
    } catch (AttributeNotExistsException ex) {
      throw new ConsistencyErrorException(
          "Attribute with defaultFilesLimit from resource "
              + resource.getId()
              + " could not obtained.",
          ex);
    }

    // Get defaultFilesQuota value
    if (attribute.getValue() != null) {
      defaultFilesQuota = (Integer) attribute.getValue();
    }
    if (defaultFilesQuota != null && defaultFilesQuota < 0)
      throw new WrongAttributeValueException(attribute, attribute + " cannot be less than 0.");

    // Get defaultFilesLimit value
    if (attrDefaultFilesLimit != null && attrDefaultFilesLimit.getValue() != null) {
      defaultFilesLimit = (Integer) attrDefaultFilesLimit.getValue();
    }
    if (defaultFilesLimit != null && defaultFilesLimit < 0)
      throw new ConsistencyErrorException(attrDefaultFilesLimit + " cannot be less than 0.");

    // Compare DefaultFilesQuota with DefaultFilesLimit
    if (defaultFilesQuota == null || defaultFilesQuota == 0) {
      if (defaultFilesLimit != null && defaultFilesLimit != 0)
        throw new WrongReferenceAttributeValueException(
            attribute,
            attrDefaultFilesLimit,
            "Try to set unlimited quota, but limit is still " + defaultFilesLimit);
    } else if (defaultFilesLimit != null && defaultFilesLimit != 0) {
      if (defaultFilesLimit < defaultFilesQuota)
        throw new WrongReferenceAttributeValueException(
            attribute,
            attrDefaultFilesLimit,
            attribute + " must be less than or equals " + attrDefaultFilesLimit);
    }
  }
 @Test
 public void getUsersForCoreAttribute() throws Exception {
   System.out.println("Searcher.getUsersForCoreAttribute");
   Attribute attr =
       perun
           .getAttributesManagerBl()
           .getAttribute(sess, user1, "urn:perun:user:attribute-def:core:id");
   Map<String, String> attributesWithSearchingValues = new HashMap<String, String>();
   attributesWithSearchingValues.put(attr.getName(), attr.getValue().toString());
   List<User> users = new ArrayList<User>();
   users = searcherBl.getUsers(sess, attributesWithSearchingValues);
   System.out.println(attr.getValue().toString());
   System.out.println(attr.getType().toString());
   System.out.println(users.toString());
 }
  @Override
  public void checkAttributeValue(
      PerunSessionImpl perunSession, Facility facility, Attribute attribute)
      throws InternalErrorException, WrongAttributeValueException,
          WrongReferenceAttributeValueException, WrongAttributeAssignmentException {

    if (attribute.getValue() == null) {
      throw new WrongAttributeValueException(attribute, facility, "attribute is null");
    }

    String value = (String) attribute.getValue();
    if (value.length() < 3) {
      throw new WrongAttributeValueException(
          attribute, facility, "attribute has to start with \"ou=\" or \"dc=\"");
    }

    String sub = value.substring(0, 3);

    if (!(sub.equalsIgnoreCase("ou=") || sub.equalsIgnoreCase("dc="))) {
      throw new WrongAttributeValueException(
          attribute, facility, "attribute has to start with \"ou=\" or \"dc=\"");
    }
  }
  @Override
  public void checkAttributeValue(
      PerunSessionImpl perunSession, Resource resource, Attribute attribute)
      throws InternalErrorException, WrongAttributeValueException,
          WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
    // attribute can be null, it means there are no default settings on resource
    if (attribute.getValue() == null) {
      return;
    }

    // Check if every part of this map has the right pattern
    // And also check if every quota part has right settings (softQuota<=hardQuota)
    perunSession
        .getPerunBl()
        .getModulesUtilsBl()
        .checkAndTransferQuotas(attribute, resource, null, true);
  }
  public Attribute getAttributeValue(
      PerunSessionImpl sess, Facility facility, User user, AttributeDefinition attributeDefinition)
      throws InternalErrorException {
    Attribute attr = new Attribute(attributeDefinition);
    try {
      Attribute attribute =
          sess.getPerunBl()
              .getAttributesManagerBl()
              .getAttribute(
                  sess, facility, user, AttributesManager.NS_USER_FACILITY_ATTR_DEF + ":shell");
      if (attribute.getValue() != null) {
        Utils.copyAttributeToVirtualAttributeWithValue(attribute, attr);
        return attr;
      }
    } catch (WrongAttributeAssignmentException | AttributeNotExistsException ex) {
      throw new InternalErrorException(ex);
    }

    try {
      Attribute facilityShells =
          sess.getPerunBl()
              .getAttributesManagerBl()
              .getAttribute(sess, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":shells");
      Attribute userPrefferedShells =
          (sess.getPerunBl()
              .getAttributesManagerBl()
              .getAttribute(sess, user, AttributesManager.NS_USER_ATTR_DEF + ":preferredShells"));
      List<Resource> resources =
          sess.getPerunBl().getUsersManagerBl().getAllowedResources(sess, facility, user);
      Set<String> resourcesShells = new HashSet<String>();

      for (Resource resource : resources) {
        List<String> resourcesShellsForTest =
            (List<String>)
                sess.getPerunBl()
                    .getAttributesManagerBl()
                    .getAttribute(
                        sess, resource, AttributesManager.NS_RESOURCE_ATTR_DEF + ":shells")
                    .getValue();
        if (resourcesShellsForTest != null) resourcesShells.addAll(resourcesShellsForTest);
      }
      if (userPrefferedShells.getValue() != null) {
        for (String pShell : (List<String>) userPrefferedShells.getValue()) {
          if (resourcesShells.contains(pShell)) {
            Utils.copyAttributeToViAttributeWithoutValue(userPrefferedShells, attr);
            attr.setValue(pShell);
            return attr;
          }
        }
      }
      if (facilityShells.getValue() != null) {
        for (String fShell : (List<String>) facilityShells.getValue()) {
          if (resourcesShells.contains(fShell)) {
            Utils.copyAttributeToViAttributeWithoutValue(facilityShells, attr);
            attr.setValue(fShell);
            return attr;
          }
        }
      }

    } catch (AttributeNotExistsException | WrongAttributeAssignmentException ex) {
      throw new InternalErrorException(ex);
    }
    return attr;
  }
  /**
   * Convert RichUsers to Identity objects with obfuscated email address and limited set of ext
   * sources. Service users are removed from the list.
   *
   * @param list RichUsers to convert
   * @return list of Identities without service ones
   * @throws PerunException
   */
  private List<Identity> convertToIdentities(List<RichUser> list) throws PerunException {

    List<Identity> result = new ArrayList<Identity>();

    if (list != null && !list.isEmpty()) {

      for (RichUser u : list) {

        // skip service users
        if (u.isServiceUser()) continue;

        Identity identity = new Identity();
        identity.setName(u.getDisplayName());
        identity.setId(u.getId());

        for (Attribute a : u.getUserAttributes()) {

          if (MailManagerImpl.URN_USER_PREFERRED_MAIL.equals(a.getName())) {
            if (a.getValue() != null && !((String) a.getValue()).isEmpty()) {

              String safeMail = ((String) a.getValue()).split("@")[0];

              if (safeMail.length() > 2) {
                safeMail =
                    safeMail.substring(0, 1)
                        + "****"
                        + safeMail.substring(safeMail.length() - 1, safeMail.length());
              }

              safeMail += "@" + ((String) a.getValue()).split("@")[1];

              identity.setEmail(safeMail);
            }
          } else if ("urn:perun:user:attribute-def:def:organization".equals(a.getName())) {
            if (a.getValue() != null) {
              identity.setOrganization((String) a.getValue());
            }
          }
        }

        List<ExtSource> es = new ArrayList<ExtSource>();
        for (UserExtSource ues : u.getUserExtSources()) {
          if (ues.getExtSource().getType().equals(ExtSourcesManagerEntry.EXTSOURCE_X509)) {
            es.add(ues.getExtSource());
          } else if (ues.getExtSource().getType().equals(ExtSourcesManagerEntry.EXTSOURCE_IDP)) {
            if (ues.getExtSource().getName().equals("https://extidp.cesnet.cz/idp/shibboleth")) {
              // FIXME - hack Social IdP to let us know proper identity source
              String type = ues.getLogin().split("@")[1].split("\\.")[0];
              ues.getExtSource()
                  .setName(
                      "https://extidp.cesnet.cz/idp/shibboleth&authnContextClassRef=urn:cesnet:extidp:authn:"
                          + type);
            } else if (ues.getExtSource().getName().equals("https://login.elixir-czech.org/idp/")) {
              // FIXME - hack Elixir proxy IdP to let us know proper identity source
              String type = ues.getLogin().split("@")[1];
              ues.getExtSource().setName("https://login.elixir-czech.org/idp/@" + type);
            }
            es.add(ues.getExtSource());
          } else if (ues.getExtSource()
              .getType()
              .equals(ExtSourcesManagerEntry.EXTSOURCE_KERBEROS)) {
            es.add(ues.getExtSource());
          }
        }
        identity.setIdentities(es);

        result.add(identity);
      }
    }

    return result;
  }
  public void checkAttributeValue(PerunSessionImpl sess, Vo vo, Attribute attribute)
      throws InternalErrorException, WrongAttributeValueException,
          WrongAttributeAssignmentException, WrongReferenceAttributeValueException {
    Map<String, String> attrValue = new LinkedHashMap<String, String>();

    // For no value is correct (it means no rules)
    if (attribute.getValue() == null) return;

    // save value to map attrValue

    attrValue = (Map) attribute.getValue();
    // Same for empty HashList
    if (attrValue.isEmpty()) return;

    // If is not empty, so i will check if all keys are correct first
    Set<String> keys = new LinkedHashSet<String>();
    keys = attrValue.keySet();

    // Only possibilities: period, doNotExtendLoa, gracePeriod, periodLoa
    for (String k : keys) {
      if (!isAllowedParameter(k))
        throw new WrongAttributeValueException(
            attribute, "There is not allowed parameter value: " + k);
    }

    // If all possibilities are correct, so check their values

    // For period (only date like 1.1. or 29.4. without year) or (+xy where x is number and y is
    // d/m/y - +35m or +80d)
    String parameter = MembersManager.membershipPeriodKeyName;
    if (keys.contains(parameter)) {
      DateFormat dateFormatter = new SimpleDateFormat("dd.MM.");
      Date date = null;
      try {
        date = dateFormatter.parse(attrValue.get(parameter));
        // Test if it is valid date format (need to use standardization: 01.01. = 1.1, 29.03 = 29.3
        // for both in test)
        if (!standardFormatDate(dateFormatter.format(date))
            .equals(standardFormatDate(attrValue.get(parameter)))) {
          throw new WrongAttributeValueException(
              attribute,
              "There is not allowed value (bad date format) for parameter '"
                  + parameter
                  + "': "
                  + attrValue.get(parameter));
        }
      } catch (ParseException ex) {
        // Its not date in format dd.MM. so test for next option exmp: "+18m"
        Matcher extensionDateMatcher = extensionDatePattern.matcher(attrValue.get(parameter));
        if (!extensionDateMatcher.find())
          throw new WrongAttributeValueException(
              attribute,
              "There is not allowed value for parameter '"
                  + parameter
                  + "': "
                  + attrValue.get(parameter));
      }
    }

    // For gracePeriod (xy where x is number and y is d/m/y - 35m or 80d)
    parameter = MembersManager.membershipGracePeriodKeyName;
    if (keys.contains(parameter)) {
      Matcher dateMatcher = datePattern.matcher(attrValue.get(parameter));
      if (!dateMatcher.find())
        throw new WrongAttributeValueException(
            attribute,
            "There is not allowed value for parameter '"
                + parameter
                + "': "
                + attrValue.get(parameter));
    }

    // For doNotExtendLoa (exmp: '3,4,5' or '3, 4 ,5' or '325, 324,336')
    parameter = MembersManager.membershipDoNotExtendLoaKeyName;
    if (keys.contains(parameter)) {
      Matcher loaMatcher = loaPattern.matcher(attrValue.get(parameter));
      if (!loaMatcher.find())
        throw new WrongAttributeValueException(
            attribute,
            "There is not allowed value for parameter '"
                + parameter
                + "': "
                + attrValue.get(parameter));
    }

    // For doNotAllowLoa (exmp: '3,4,5' or '3, 4 ,5' or '325, 324,336')
    parameter = MembersManager.membershipDoNotAllowLoaKeyName;
    if (keys.contains(parameter)) {
      Matcher loaMatcher = loaPattern.matcher(attrValue.get(parameter));
      if (!loaMatcher.find())
        throw new WrongAttributeValueException(
            attribute,
            "There is not allowed value for parameter '"
                + parameter
                + "': "
                + attrValue.get(parameter));
    }

    // For periodLoa x|y. or x|y where x is loa format and y is period format and symbol '.' is not
    // mandatory
    parameter = MembersManager.membershipPeriodLoaKeyName;
    if (keys.contains(parameter)) {
      Matcher periodLoaMatcher = periodLoaPattern.matcher(attrValue.get(parameter));
      if (!periodLoaMatcher.find())
        throw new WrongAttributeValueException(
            attribute,
            "There is not allowed value for parameter '"
                + parameter
                + "': "
                + attrValue.get(parameter));
      String value = attrValue.get(parameter);
      for (int i = 0; i < value.length(); i++) {
        if (value.charAt(i) == '|') value = value.substring(i + 1);
      }
      if (value.charAt(0) != '+') {
        if (value.contains("..")) {
          value = value.substring(0, value.length() - 1);
        }
        DateFormat dateFormatter = new SimpleDateFormat("dd.MM.");
        Date date = null;
        try {
          date = dateFormatter.parse(value);
          // Test if it is valid date format (need to use standardization: 01.01. = 1.1, 29.03 =
          // 29.3 for both in test)
          if (!standardFormatDate(dateFormatter.format(date)).equals(standardFormatDate(value))) {
            throw new WrongAttributeValueException(
                attribute,
                "There is not allowed value (bad date format) for parameter '"
                    + parameter
                    + "': "
                    + attrValue.get(parameter));
          }
        } catch (ParseException ex) {
          throw new WrongAttributeValueException(
              attribute,
              "There is not allowed value (bad date format) for parameter '"
                  + parameter
                  + "': "
                  + attrValue.get(parameter));
        }
      }
    }
  }