Class Utils

java.lang.Object
cz.metacentrum.perun.core.impl.Utils

public class Utils extends Object
Utilities.
  • Field Details

  • Constructor Details

    • Utils

      public Utils()
  • Method Details

    • normalizeString

      public static String normalizeString(String str)
      Replaces dangerous characters. Replaces : with - and spaces with _.
      Parameters:
      str - string to be normalized
      Returns:
      normalized string
    • hasDuplicate

      public static <T> boolean hasDuplicate(List<T> all)
    • join

      public static String join(Iterable<?> collection, String separator)
      Joins Strings or any objects into a String. Use as
        List list = Arrays.asList("a", 1, 2.0);
        String s = join(list,",");
       
      Parameters:
      collection - anything Iterable, like a List or Collection
      separator - any separator, like a comma
      Returns:
      string with string representations of objects joined by separators
    • extractAdditionalUserExtSources

      public static List<RichUserExtSource> extractAdditionalUserExtSources(PerunSession sess, Map<String,​String> subjectFromExtSource)
      Returns additionalUserExtSources from the subject. It's used for synchronization from different ExtSources. subjectFromExtSource was obtained from the ExtSource. This additional userExtSource has 3 required parts: name of extSource, type of extSource, login of extsource with optional ues attributes and their values. And 1 optional part: LoA. Expected format of additional userExtSource is: extSourceName|extSourceType|extLogin;uesAttribute1=value1,value2;uesAttribute2=value1|LoA
      Parameters:
      sess - perun session
      subjectFromExtSource - map with the subject
      Returns:
      List all additional ExtSources (and possibly their attributes) from the subject, returned list will never contain null value
    • join

      public static String join(Object[] objs, String separator)
      Joins Strings or any objects into a String. Use as
        String[] sa = { "a", "b", "c"};
        String s = join(list,",");
       
      Parameters:
      objs - array of objects
      separator - any separator, like a comma
      Returns:
      string with string representations of objects joined by separators
    • checkPerunSession

      public static void checkPerunSession(PerunSession sess)
    • createDeepCopyOfMapWithSets

      public static <T> Map<T,​Set<T>> createDeepCopyOfMapWithSets(Map<T,​Set<T>> original)
      Creates copy of given Map with Sets as values. The returned object contains a new Map and new Sets, the Utils objects remain the same.
      Type Parameters:
      T - parameter
      Parameters:
      original - original Map
      Returns:
      new Map with new Sets as values
    • notNull

      public static void notNull(Object e, String name)
      Checks whether the object is null or not.
      Parameters:
      e -
      name -
      Throws:
      InternalErrorException - which wraps NullPointerException
    • checkMinLength

      public static void checkMinLength(String propertyName, String actualValue, int minLength)
      Throws a MinSizeExceededException if the given value does not specified minLength. If the value is null then MinSizeExceededException is thrown as well.
      Parameters:
      propertyName - name of checked property
      minLength - minimal length
      Throws:
      MinSizeExceededException - when length of actualValue is lower than minLength or null
    • checkMaxLength

      public static void checkMaxLength(String propertyName, String actualValue, int maxLength)
      Throws a MaxSizeExceededException if the given value is longer than maxLength. If the value is null then nothing happens.
      Parameters:
      propertyName - name of checked property
      maxLength - max length
      Throws:
      MaxSizeExceededException - when length of actualValue is higher than maxLength
    • checkWithoutDiacritic

      public static void checkWithoutDiacritic(String name)
      Define, if some entity contain a diacritic symbol.
      Parameters:
      name - name of entity
      Throws:
      DiacriticNotAllowedException
    • checkWithoutSpecialChars

      public static void checkWithoutSpecialChars(String name)
      Define, if some entity contain a special symbol Special symbol is everything except - numbers, letters and space
      Parameters:
      name - name of entity
      Throws:
      SpecialCharsNotAllowedException
    • checkWithoutSpecialChars

      public static void checkWithoutSpecialChars(String name, String allowedSpecialChars)
      Define, if some entity contain a special symbol Special symbol is everything except - numbers, letters and space (and allowedSpecialChars) The allowedSpecialChars are on the end of regular expresion, so the same rule must be observed. (example, symbol - must be on the end of string) rules are the same like in regular expresion
      Parameters:
      name - name of entity
      allowedSpecialChars - this String must contain only special chars which are allowed
      Throws:
      SpecialCharsNotAllowedException
    • checkWithoutNumbers

      public static void checkWithoutNumbers(String name)
      Define, if some entity contain a number
      Parameters:
      name -
      Throws:
      NumbersNotAllowedException
    • checkWithoutSpaces

      public static void checkWithoutSpaces(String name)
      Define, if some entity contain a space
      Parameters:
      name -
      Throws:
      SpaceNotAllowedException
    • checkRangeOfNumbers

      public static void checkRangeOfNumbers(int number, int lowestValue, int highestValue)
      Define, if some number is in range. Example: number 4 is in range 4 - 12, number 3 is not
      Parameters:
      number -
      lowestValue -
      highestValue -
      Throws:
      NumberNotInRangeException
    • getNewId

      public static int getNewId(JdbcTemplate jdbc, String sequenceName)
      Gets the next number from the sequence.
      Parameters:
      jdbc -
      sequenceName -
      Returns:
      new ID
      Throws:
      InternalErrorException
    • startTimer

      public static long startTimer()
      Returns current time in millis. Result of this call can then be used by function getRunningTime().
      Returns:
      current time in millis.
    • getRunningTime

      public static long getRunningTime(long startTime)
      Returns difference between startTime and current time in millis.
      Parameters:
      startTime -
      Returns:
      difference between current time in millis and startTime.
    • getClasses

      public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException
      Scans all classes accessible from the context class loader which belong to the given package and subpackages.
      Parameters:
      packageName - The base package
      Returns:
      The classes
      Throws:
      ClassNotFoundException
      IOException
    • createUserFromNameMap

      public static User createUserFromNameMap(Map<String,​String> name, boolean allowEmptyFirstName)
    • createUserFromNameMap

      public static User createUserFromNameMap(Map<String,​String> name)
    • parseUserFromCommonName

      public static User parseUserFromCommonName(String rawName, boolean fullNameRequired)
      Creates a new instance of User with names initialized from parsed rawName. Imposes limit on leghts of fields.
      Parameters:
      rawName - raw name
      fullNameRequired - if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
      Returns:
      user
      See Also:
      parseCommonName(String)
    • parseCommonName

      public static Map<String,​String> parseCommonName(String rawName)
    • parseCommonName

      public static Map<String,​String> parseCommonName(String rawName, boolean fullNameRequired)
      Try to parse rawName to keys: "titleBefore" "firstName" "lastName" "titleAfter" If rawName is null or empty, return map with empty values of all keys. Parsing procedure: 1] prepare list of parts by replacing all characters "," and "_" by spaces 2] change all sequence of invisible characters (space, tabulator etc.) to one space 3] one by one try to parsing parts from the list - A] try to find all titleBefore parts - B] try to find one firstName part - C] try to find all lastName parts - D] if the rest is not lastName so save it to the title after Example of parsing rawName: 1] rawName = "Mgr. et Mgr. Petr_Jiri R. Sojka, Ph.D., CSc." 2] convert all ',' and '_' to spaces: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc." 3] convert more than 1 invisible char to 1 space: rawName = "Mgr. et Mgr. Petr Jiri R. Sojka Ph.D. CSc." 4] parse string to list of parts by space: ListOfParts= ["Mgr.","et","Mgr.","Petr","Jiri","R.","Sojka","Ph.D.","CSc."] 5] first fill everything what can be in title before: titleBefore="Mgr. et Mgr." 6] then fill everything what can be in first name (maximum 1 part): firstName="Petr" 7] then fill everything what can be in last name: lastName="Jiri R. Sojka" 8] everything else put to the title after: titleAfter="Ph.D. CSc." 9] put these variables to map like key=value, for ex.: Map[titleBefore="Mgr. et Mgr.",firstName="Petr", ... ] and return this map
      Parameters:
      rawName - name to parse
      fullNameRequired - if true, throw exception if firstName or lastName is missing, do not throw exception otherwise
      Returns:
      map string to string where are 4 keys (titleBefore,titleAfter,firstName and lastName) with their values (value can be null)
      Throws:
      ParseUserNameException - when method was unable to parse both first name and last name from the rawName
    • isEscaped

      public static boolean isEscaped(String text, int position)
      Return true, if char on position in text is escaped by '\' Return false, if not.
      Parameters:
      text - text in which will be searching
      position - position in text <0-text.length>
      Returns:
      true if char is escaped, false if not
    • serializeMapToString

      public static String serializeMapToString(Map<String,​String> map)
      Serialize map to string
      Parameters:
      map -
      Returns:
      string of escaped map
    • copyAttributeToViAttributeWithoutValue

      public static Attribute copyAttributeToViAttributeWithoutValue(Attribute copyFrom, Attribute copyTo)
    • copyAttributeToVirtualAttributeWithValue

      public static Attribute copyAttributeToVirtualAttributeWithValue(Attribute copyFrom, Attribute copyTo)
    • generateStringsByPattern

      public static List<String> generateStringsByPattern(String pattern) throws WrongPatternException
      Method generates strings by pattern. The pattern is string with square brackets, e.g. "a[1-3]b". Then the content of the brackets is distributed, so the list is [a1b, a2b, a3c]. Multibrackets are aslo allowed. For example "a[00-01]b[90-91]c" generates [a00b90c, a00b91c, a01b90c, a01b91c].
      Parameters:
      pattern -
      Returns:
      list of all generated strings
      Throws:
      WrongPatternException
    • getMessageAuthenticationCode

      public static String getMessageAuthenticationCode(String input)
      Return encrypted version of input in UTF-8 by HmacSHA256
      Parameters:
      input - input to encrypt
      Returns:
      encrypted value
    • sendValidationEmail

      public static void sendValidationEmail(User user, String url, String email, UUID changeUuid, String subject, String content, String customUrlPath, String idp)
      Send validation email related to requested change of users preferred email.
      Parameters:
      user - user to change preferred email for
      url - base URL of running perun instance passed from RPC
      email - new email address to send notification to
      changeUuid - UUID of change request in DB
      subject - Template subject or null
      content - Template message or null
      customUrlPath - custom path to be used in generated URL
      idp - Authentication to be added as query parameter in generated URL
    • sendAccountActivationEmail

      public static void sendAccountActivationEmail(User user, String email, String namespace, String url, UUID uuid, String messageTemplate, String subject, LocalDateTime validityTo)
      Sends email with link to non-authz account activation where user can activate his account by setting a password.
      Parameters:
      user - user to send notification for
      email - user's email to send notification to
      namespace - namespace to reset password in
      url - base URL of Perun instance
      uuid - UUID of account activation request
      messageTemplate - message of the email (use default if null)
      subject - subject of the email (use default if null)
      validityTo - time till link is valid
    • sendPasswordResetEmail

      public static void sendPasswordResetEmail(User user, String email, String namespace, String url, UUID uuid, String messageTemplate, String subject, LocalDateTime validityTo)
      Sends email with link to non-authz password reset GUI where user can reset forgotten password
      Parameters:
      user - user to send notification for
      email - user's email to send notification to
      namespace - namespace to reset password in
      url - base URL of Perun instance
      uuid - UUID of pwd reset request
      messageTemplate - message of the email
      subject - subject of the email
      validityTo - time till link is valid
      Throws:
      InternalErrorException
    • sendAccountActivationConfirmationEmail

      public static void sendAccountActivationConfirmationEmail(User user, String email, String namespace, String login, String subject, String content)
      Sends email to user confirming his password was set and the account was activated.
      Parameters:
      user - user to send notification for
      email - user's email to send notification to
      namespace - namespace where the account was activated
      login - login of user
      subject - Subject from template or null
      content - Message from template or null
    • sendPasswordResetConfirmationEmail

      public static void sendPasswordResetConfirmationEmail(User user, String email, String namespace, String login, String subject, String content)
      Sends email to user confirming his password was changed.
      Parameters:
      user - user to send notification for
      email - user's email to send notification to
      namespace - namespace the password was re-set
      login - login of user
      subject - Subject from template or null
      content - Message from template or null
    • cipherInput

      public static String cipherInput(String plainText, boolean decrypt)
      Return en/decrypted version of input using AES/CBC/PKCS5PADDING cipher. Perun's internal secretKey and initVector are used (you can configure them in perun.properties file).
      Parameters:
      plainText - text to en/decrypt
      decrypt - TRUE = decrypt input / FALSE = encrypt input
      Returns:
      en/decrypted text
      Throws:
      InternalErrorException - if anything fails
    • checkDestinationType

      public static void checkDestinationType(Destination destination) throws WrongPatternException
      Checks whether the destination is not null and is of the right type.
      Parameters:
      destination - destination to check
      Throws:
      InternalErrorException - if destination is null
      WrongPatternException - if destination is not of the right type
    • checkDestination

      public static void checkDestination(Destination destination)
      Checks whether the destinations name has correct syntax.
      Parameters:
      destination - destination to check
      Throws:
      IllegalArgumentException - if destination has invalid value in given destination type.
    • checkHostname

      public static void checkHostname(Host host)
      Checks whether the hostname has correct syntax.
      Parameters:
      host - host to check
      Throws:
      IllegalArgumentException - if host has invalid hostname
    • sendSMS

      public static void sendSMS(PerunSession sess, User user, String message) throws PrivilegeException, UserNotExistsException
      Sends SMS to the phone number of a user with the given message. The phone number is taken from the user attribute urn:perun:user:attribute-def:def:phone.
      Parameters:
      sess - session
      user - receiver of the message
      message - sms message to send
      Throws:
      InternalErrorException - when the attribute value cannot be found or is broken
      PrivilegeException - when the actor has not right to get the attribute
      UserNotExistsException - when given user does not exist
    • sendSMS

      public static void sendSMS(PerunSession sess, Member member, String message) throws PrivilegeException, MemberNotExistsException
      Sends SMS to the phone number of a member with the given message. The phone number is taken from the user attribute urn:perun:member:attribute-def:def:phone.
      Parameters:
      sess - session
      member - receiver of the message
      message - sms message to send
      Throws:
      InternalErrorException - when the attribute value cannot be found or is broken
      PrivilegeException - when the actor has not right to get the attribute
      MemberNotExistsException - when given member does not exist
    • sendSMS

      public static void sendSMS(String telNumber, String message)
      Sends SMS to the phone number with the given message. The sending provides external program for sending sms. Its path is saved in the perun property perun.sms.program.
      Parameters:
      telNumber - phone number of the receiver
      message - sms message to send
      Throws:
      InternalErrorException - when there is something wrong with external program
      IllegalArgumentException - when the phone or message has a wrong format
    • bigDecimalBytesToReadableStringWithMetric

      public static String bigDecimalBytesToReadableStringWithMetric(BigDecimal quota)
      Get BigDecimal number like '1024' in Bytes and create better readable String with metric value like '1K' where K means KiloBytes. Use M,G,T,P,E like multipliers of 1024. If quota is not dividable by 1024 use B (Bytes) without dividing.
      Parameters:
      quota - in big natural number
      Returns:
      string with number and metric
    • toASCII

      public static String toASCII(String input, Character replacement)
      Convert input string (expected UTF-8) to ASCII if possible. Any non-ASCII character is replaced by replacement parameter.
      Parameters:
      input - String to convert from UTF-8 to ASCII.
      replacement - Replacement character used for all non-ASCII chars in input.
      Returns:
      converted string from ascii to something near utf
    • extendDateByPeriod

      public static LocalDate extendDateByPeriod(LocalDate localDate, String period)
      Extends given date by given period.
      Parameters:
      localDate - date to be extended
      period - period used to extend date
      Throws:
      InternalErrorException - when the period has wrong format, allowed format is given by regex "\\+([0-9]+)([dmy]?)"
    • shortenDateByPeriod

      public static LocalDate shortenDateByPeriod(LocalDate localDate, String period)
      Shortens the given date by the given period.
      Parameters:
      localDate - date to be shortened
      period - string of format ([0-9]+)([dmy])
      Returns:
      shortened date
    • getClosestExpirationFromStaticDate

      public static LocalDate getClosestExpirationFromStaticDate(Matcher matcher)
      Returns closest future LocalDate based on values given by matcher. If returned value should fall to 29. 2. of non-leap year, the date is extended to 28. 2. instead.
      Parameters:
      matcher - matcher with day and month values
      Returns:
      Extended date.
    • prepareGracePeriodDate

      public static Pair<Integer,​TemporalUnit> prepareGracePeriodDate(Matcher matcher)
      Prepares grace period date by values from given matcher.
      Parameters:
      matcher - matcher
      Returns:
      pair of field(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS) and amount
      Throws:
      InternalErrorException - when given matcher contains invalid data
      IllegalArgumentException - when matcher does not match gracePeriod format
    • escapeStringForLDAP

      public static String escapeStringForLDAP(String searchString)
      We need to escape some special characters for LDAP filtering. We need to escape these characters: '\\', '*', '(', ')', '\000'
      Parameters:
      searchString - search string which need to be escaped properly
      Returns:
      properly escaped search string
    • validateFullGroupName

      public static void validateFullGroupName(String name)
    • validateGroupName

      public static void validateGroupName(String name)
      Validates group name. To check the group name, this method uses two regexes. A default one, hardcoded in the GroupsManager, and a secondary optional. The secondary regex can be default as a core property named groupNameSecondaryRegex.
      Parameters:
      name - name to be validated
    • validateGroupName

      public static void validateGroupName(String name, String regex)
      Validates given group name against a given regex.
      Parameters:
      name - group name
      regex - regex to be used
    • prepareUserSearchQueryExactMatch

      public static String prepareUserSearchQueryExactMatch()
      Returns search query to search by user name (exact match) based on databased in use.
      Returns:
      search query
    • prepareUserSearchQuerySimilarMatch

      public static String prepareUserSearchQuerySimilarMatch()
      Returns search query to search by user name (similar match) based on databased in use.
      Returns:
      search query
    • prepareSqlWhereForUserMemberSearch

      public static String prepareSqlWhereForUserMemberSearch(String searchString, MapSqlParameterSource namedParams, boolean exactMatch)
      Returns a part of WHERE condition to search users and members in their ids, uuids, logins, ext sources user names and attributes by given search string.
      Parameters:
      searchString - string to search by
      namedParams - parameters used in the query
      exactMatch - if true, searches user name only by exact match
      Returns:
      search query
    • getDividedAttributes

      public static Map<String,​List<String>> getDividedAttributes()
      Takes attributes from CoreConfig used in users or members search and divides them into correct categories based on attribute type (member, user, userExtSource). Then returns map: memberAttributes -> list of member attributes userAttributes -> list of user attributes uesAttributes -> list of userExtSource attributes
      Returns:
      map of attributes
    • getAttributesQuery

      public static Map<String,​Pair<String,​String>> getAttributesQuery(List<String> memberAttributes, List<String> userAttributes, List<String> uesAttributes)
      Prepares query to search users or members by attributes if received attribute list is not empty. Returns map: memberAttributesQueryString -> pair of parts of query to search by member attributes userAttributesQueryString -> pair of parts of query to search by user attributes uesAttributesQueryString -> pair of parts of query to search by userExtSource attributes
      Parameters:
      memberAttributes - member attributes
      userAttributes - user attributes
      uesAttributes - userExtSource attributes
      Returns:
      map of parts of query
    • getMapSqlParameterSourceToSearchUsersOrMembers

      public static MapSqlParameterSource getMapSqlParameterSourceToSearchUsersOrMembers(String searchString, Map<String,​List<String>> attributesToSearchBy)
      Returns MapSqlParameterSource with values added to search members or users.
      Parameters:
      searchString - string used to search by
      attributesToSearchBy - map of attributes used to search for users or members
      Returns:
      filled MapSqlParameterSource
    • sendIdentityAddedAlerts

      public static void sendIdentityAddedAlerts(PerunSession sess, UserExtSource newUes)
      Sends all alerts about an identity being added. Sends an email to the preferred email of the user. Also, if the identity has an email and it is different that the preferred email, another different email is send to this email.
      Parameters:
      sess - session
      newUes - removed userExtSource
    • sendIdentityRemovedAlerts

      public static void sendIdentityRemovedAlerts(PerunSession sess, UserExtSource removedUes, List<Attribute> uesAttrs)
      Sends all alerts about an identity being removed. Sends an email to the preferred email of the user. Also, if the identity has an email and it is different that the preferred email, another different email is send to this email.
      Parameters:
      sess - session
      removedUes - removed userExtSource
      uesAttrs - attributes of the removed userExtSource