List of usage examples for java.util Set isEmpty
boolean isEmpty();
From source file:br.com.suricattus.surispring.spring.security.util.SecurityUtil.java
/** * Method that checks if the user holds <b>all</b> of the given roles. * Returns <code>true</code>, iff the user holds all roles, * <code>false</code> if no roles are given or the first non-matching role * is found//from w ww . j a va 2 s .c om * * @param requiredRoles a comma seperated list of roles * @return true if all of the given roles are granted to the current user, * false otherwise or if no roles are specified at all. */ public static boolean hasAllRoles(final String requiredRoles) { Set<String> requiredAuthorities = parseAuthorities(requiredRoles); if (requiredAuthorities.isEmpty()) return false; Set<String> userAuthorities = getUserAuthorities(); for (String requiredAuthority : requiredAuthorities) { if (!userAuthorities.contains(requiredAuthority)) return false; } return true; }
From source file:br.com.suricattus.surispring.spring.security.util.SecurityUtil.java
/** * Method that checks if <b>none</b> of the given roles is hold by the user. * Returns <code>true</code> if no roles are given, or none of the given * roles match the users roles. Returns <code>false</code> on the first * matching role.//from w ww .j a v a 2 s.com * * @param notGrantedRoles * a comma seperated list of roles * @return true if none of the given roles is granted to the current user, * false otherwise */ public static boolean hasNoRole(final String notGrantedRoles) { Set<String> parsedAuthorities = parseAuthorities(notGrantedRoles); if (parsedAuthorities.isEmpty()) return true; Set<String> userAuthorities = getUserAuthorities(); for (String notGrantedAuthority : parsedAuthorities) { if (userAuthorities.contains(notGrantedAuthority)) return false; } return true; }
From source file:com.stratio.crossdata.core.utils.ParserUtils.java
/** * Get the best matches for a string {@code str} given a set of words to compare against and a maximum Levenshtein * distance./*from w ww. j av a 2 s . c o m*/ * * @param str The word to get the matches for. * @param words The set of candidate words. * @param maxDistance The maximum Levenshtein distance. * @return A set of matching words within distance. */ public static Set<String> getBestMatches(String str, Set<String> words, int maxDistance) { int limit = maxDistance + 1; int currentLimit = 1; Set<String> result = new HashSet<>(); while (result.isEmpty() && currentLimit < limit) { for (String word : words) { int distance = StringUtils.getLevenshteinDistance(str, word, maxDistance); if ((distance > -1) && (distance < currentLimit)) { result.add(word); } } currentLimit++; } return result; }
From source file:it.univaq.incipict.profilemanager.common.utility.Utility.java
public static HashMap<Profile, Double> getEuclideanDistances(List<Profile> profilesList, User user) { Map<Profile, Double> result = new HashMap<Profile, Double>(); Set<ProfileInformation> profileInformationSet; Set<Information> userInformationSet; // Retrieve user information set userInformationSet = user.getInformationSet(); if (userInformationSet.isEmpty()) { return (HashMap<Profile, Double>) result; }//from ww w . j av a2 s .co m // For each Profile for (Profile profile : profilesList) { profileInformationSet = profile.getProfileInformationSet(); int vectorsLenght = Math.max(profileInformationSet.size(), userInformationSet.size()); RealVector ranksRealVector = new ArrayRealVector(new double[] {}); RealVector userInformationVector = new ArrayRealVector(new double[] {}); // Loop userInformationSet and // profileInformationSet (i.e. one specific column vector in the // knowledge base representation) for (Information information : userInformationSet) { Long x = information.getId(); for (ProfileInformation profileInformation : profileInformationSet) { Long y = profileInformation.getInformation().getId(); // User selected information was stored in a RealVector at same // position of relative ranksVector // This permit to calculate Euclidean distance right. if (x == y) { userInformationVector = userInformationVector.append(1d); // Associated:1, Else:0 ranksRealVector = ranksRealVector.append(profileInformation.getRank()); profileInformationSet.remove(profileInformation); break; } } } // At this point we aren't interested to elements position // because every other information worth zero. // Euclidean distance are not influenced from position of 0-elements in // a "sub-vector". // if they are all zeros. // => Append the zeros until completion of the length of the vectors userInformationVector = userInformationVector .append(new double[vectorsLenght - userInformationSet.size()]); for (ProfileInformation profileInformation : profileInformationSet) { // Append the remaining elements of this set (profileInformationSet) ranksRealVector = ranksRealVector.append(profileInformation.getRank()); } // Calculate Euclidean Distance double distance = userInformationVector.getDistance(ranksRealVector); // add the distance to Distance's Map result.put(profile, distance); } // END, goto Next Profile // return the HashMap sorted by value (ASC) return (HashMap<Profile, Double>) MapUtil.sortByValueASC(result); }
From source file:edu.kit.dama.dataworkflow.util.DataWorkflowTaskUtils.java
/** * Print the provided list of DataWorkflow tasks to StdOut, either in a basic * tabular view or in verbose mode, in a detailed representation. * * @param pTasks The list of tasks to print out. * @param pVerbose TRUE = print detailed view, FALSE = print basic tabular * view./*from w w w. j av a2 s . c o m*/ */ public static void printTaskList(List<DataWorkflowTask> pTasks, boolean pVerbose) { if (!pVerbose) { //do table listing //Headers: ID | STATUS | LAST_MODIFIED //Lengths: 10 | 34 | 34 StringBuilder listing = new StringBuilder(); listing.append(StringUtils.center("Task ID", 10)).append("|").append(StringUtils.center("Status", 34)) .append("|").append(StringUtils.center("Last Modified", 34)).append("\n"); for (DataWorkflowTask task : pTasks) { listing.append(StringUtils.center(Long.toString(task.getId()), 10)).append("|") .append(StringUtils.center(task.getStatus().toString(), 34)).append("|") .append(StringUtils.center(new SimpleDateFormat().format(task.getLastUpdate()), 34)) .append("\n"); } System.out.println(listing.toString()); } else { //do detailed listing //ID: <ID> Status: <STATUS> Last Update: <LAST_UPDATE> //Config: <CONFIG_ID> Environment: <ID> Predecessor: <ID> //Group: <GID> Executor: <UID> Contact: <EMAIL> //Investigation: <ID> //InputDir: <URL> //OutputDir: <URL> //WorkingDir: <URL> //TempDir: <URL> //Input Objects // Object | View // OID 1 | default // OID 2 | default //Transfers // Object | TransferId // OID 1 | 123 //-------------------------------------------------------------- StringBuilder builder = new StringBuilder(); for (DataWorkflowTask task : pTasks) { builder.append(StringUtils.rightPad("Id: " + task.getId(), 40)) .append(StringUtils.rightPad( "Predecessor: " + ((task.getPredecessor() != null) ? task.getPredecessor().getId() : "-"), 40)) .append("\n").append(StringUtils.rightPad("Status: " + task.getStatus(), 40)) .append(StringUtils.rightPad( "Last Update: " + new SimpleDateFormat().format(task.getLastUpdate()), 40)) .append("\n") .append(StringUtils.rightPad("Configuration: " + ((task.getConfiguration() != null) ? task.getConfiguration().getId() : "-"), 40)) .append(StringUtils.rightPad("Environment: " + ((task.getExecutionEnvironment() != null) ? task.getExecutionEnvironment().getId() : "-"), 40)) .append("\n").append(StringUtils.rightPad("Group: " + task.getExecutorGroupId(), 40)) .append(StringUtils.rightPad("User: " + task.getExecutorId(), 40)).append("\n") .append(StringUtils.rightPad("Contact UserId: " + ((task.getContactUserId() != null) ? task.getContactUserId() : "-"), 80)) .append("\n") .append(StringUtils.rightPad("InvestigationId: " + task.getInvestigationId(), 80)) .append("\n").append(StringUtils.rightPad("Input Dir:", 15)) .append(StringUtils.abbreviateMiddle(task.getInputDirectoryUrl(), "...", 65)).append("\n") .append(StringUtils.rightPad("Output Dir:", 15)) .append(StringUtils.abbreviateMiddle(task.getOutputDirectoryUrl(), "...", 65)).append("\n") .append(StringUtils.rightPad("Working Dir:", 15)) .append(StringUtils.abbreviateMiddle(task.getWorkingDirectoryUrl(), "...", 65)).append("\n") .append(StringUtils.rightPad("Temp Dir:", 15)) .append(StringUtils.abbreviateMiddle(task.getTempDirectoryUrl(), "...", 65)).append("\n") .append(StringUtils.rightPad("Input Objects:", 80)).append("\n") .append(StringUtils.center("ObjectId", 39)).append("|") .append(StringUtils.center("View", 40)).append("\n"); try { Properties objectViewMap = task.getObjectViewMapAsObject(); Set<Entry<Object, Object>> entries = objectViewMap.entrySet(); if (entries.isEmpty()) { builder.append(StringUtils.center("---", 39)).append("|") .append(StringUtils.center("---", 40)).append("\n"); } else { for (Entry<Object, Object> entry : entries) { builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|") .append(StringUtils.center((String) entry.getValue(), 40)).append("\n"); } } } catch (IOException ex) { LOGGER.error("Failed to deserialize object-view map of DataWorkflow task " + task.getId(), ex); builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40)) .append("\n"); } builder.append(StringUtils.rightPad("Transfers:", 80)).append("\n") .append(StringUtils.center("ObjectId", 39)).append("|") .append(StringUtils.center("TransferId", 40)).append("\n"); try { Properties objectTransferMap = task.getObjectTransferMapAsObject(); Set<Entry<Object, Object>> entries = objectTransferMap.entrySet(); if (entries.isEmpty()) { builder.append(StringUtils.center("---", 39)).append("|") .append(StringUtils.center("---", 40)).append("\n"); } else { for (Entry<Object, Object> entry : entries) { builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|") .append(StringUtils.center((String) entry.getValue(), 40)).append("\n"); } } } catch (IOException ex) { LOGGER.error("Failed to deserialize object-transfer map of DataWorkflow task " + task.getId(), ex); builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40)) .append("\n"); } //add closing line builder.append(StringUtils.leftPad("", 80, '-')).append("\n"); } System.out.println(builder.toString()); } }
From source file:com.task.springsec.SecurityUtil.java
/** * Return true if the authenticated principal is granted NONE of the roles * specified in authorities./*from w w w .j a v a2 s . com*/ * * @param authorities A comma separated list of roles which the user must * have been granted NONE. * @return true if the authenticated principal is granted authorities * of NONE the specified roles. */ public static boolean isNoneGranted(String authorities) { if (null == authorities || "".equals(authorities)) { return false; } final Collection<? extends GrantedAuthority> granted = getPrincipalAuthorities(); final Set grantedCopy = retainAll(granted, parseAuthorities(authorities)); return grantedCopy.isEmpty(); }
From source file:com.task.springsec.SecurityUtil.java
/** * Return true if the authenticated principal is granted ANY of the roles * specified in authorities.//from w w w .ja v a2s. c o m * * @param authorities A comma separated list of roles which the user must have * been granted ANY. * @return true true if the authenticated principal is granted authorities * of ALL the specified roles. */ public static boolean isAnyGranted(String authorities) { if (null == authorities || "".equals(authorities)) { return false; } final Collection<? extends GrantedAuthority> granted = getPrincipalAuthorities(); final Set grantedCopy = retainAll(granted, parseAuthorities(authorities)); return !grantedCopy.isEmpty(); }
From source file:com.shazam.shazamcrest.matcher.GsonProvider.java
/** * Returns a {@link Gson} instance containing {@link ExclusionStrategy} based on the object types to ignore during * serialisation./*from ww w .jav a 2s . co m*/ * * @param typesToIgnore the object types to exclude from serialisation * @param circularReferenceTypes cater for circular referenced objects * @return an instance of {@link Gson} */ public static Gson gson(final List<Class<?>> typesToIgnore, final List<Matcher<String>> fieldsToIgnore, Set<Class<?>> circularReferenceTypes) { final GsonBuilder gsonBuilder = initGson(); if (!circularReferenceTypes.isEmpty()) { registerCircularReferenceTypes(circularReferenceTypes, gsonBuilder); } gsonBuilder.registerTypeAdapter(Optional.class, new OptionalSerializer()); registerSetSerialisation(gsonBuilder); registerMapSerialisation(gsonBuilder); markSetAndMapFields(gsonBuilder); registerExclusionStrategies(gsonBuilder, typesToIgnore, fieldsToIgnore); return gsonBuilder.create(); }
From source file:internal.static_util.scorer.TermRelatednessScorer.java
/** * Given a word and a set of its related relatedTerms, returns an ordered list of relatedTerms ranked from most relevant to least. * * @param original The word you want to find ranked relatedTerms for * @param relatedTerms The set of terms related to the original * @param minRelevanceRatio An optional parameter for the minimum a synonym must score to be returned. If none * given, .50 is assumed. * @return A list of scoredTerms, in descending order of their scores. *///www.ja v a 2 s . c o m public static List<ScoredTerm> getRankedTermsWithScores(String original, Set<String> relatedTerms, double minRelevanceRatio) { // Handle null/empty cases if (original == null || relatedTerms == null || relatedTerms.isEmpty()) { return Collections.EMPTY_LIST; } // A HashMap with the word as the key, and its corresponding score List<ScoredTerm> scoredTerms = Collections.synchronizedList(new ArrayList<>()); // Open up a parallel stream on the relatedTerms to perform the doc search on them all relatedTerms.parallelStream().forEach(term -> scoredTerms.add(new ScoredTerm(term, score(original, term)))); // TODO: NOTICE: if the change is made to use a 'top ten' type, refactor to just take first 'x' relatedTerms // Trim the fat - anything below relevance rank gets the D List<ScoredTerm> relevantTerms = getRelevantTerms(scoredTerms, minRelevanceRatio); // Use common.data.ScoredTerm's built-in comparator for sorting purposes // It is by default in ascending order; we want most relevant first, so reverse it Collections.sort(relevantTerms, Comparator.reverseOrder()); // If there were no relevant relatedTerms, return null. // TODO: throw a NoRelevantTerms exception? return relevantTerms.size() > 0 ? relevantTerms : Collections.EMPTY_LIST; }
From source file:com.linuxbox.enkive.teststats.StatsMonthGrainTest.java
@BeforeClass public static void setUp() throws ParseException, GathererException { coll = TestHelper.GetTestCollection(); client = TestHelper.BuildClient();//from w ww. ja v a2 s . co m grain = new MonthConsolidator(client); // clean up if week was run... Map<String, Object> queryMap = new HashMap<String, Object>(); queryMap.put(CONSOLIDATION_TYPE, CONSOLIDATION_DAY); StatsQuery statsQuery = new MongoStatsQuery(null, CONSOLIDATION_DAY, null); Set<Object> ids = new HashSet<Object>(); for (Map<String, Object> mapToDelete : client.queryStatistics(statsQuery)) { ids.add(mapToDelete.get("_id")); } if (!ids.isEmpty()) { client.remove(ids); } // TODO List<Map<String, Object>> stats = (new DayConsolidator(client)).consolidateData(); Map<String, Object> timeMap = new HashMap<String, Object>(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); cal.set(Calendar.DAY_OF_MONTH, 1); for (int i = 0; i < 10; i++) { if (i == 5) { cal.add(Calendar.MONTH, -1); } timeMap.put(CONSOLIDATION_MAX, cal.getTime()); timeMap.put(CONSOLIDATION_MIN, cal.getTime()); for (Map<String, Object> data : stats) { data.put(STAT_TIMESTAMP, timeMap); } client.storeData(stats); } dataCount = coll.count(); }