List of usage examples for java.util Collection isEmpty
boolean isEmpty();
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private static Address[] toAddressArray(Collection<InternetAddress> c) { if (c == null || c.isEmpty()) { return new Address[0]; }/*from w ww .ja va 2 s .c o m*/ final Address[] addresses = new Address[c.size()]; c.toArray(addresses); return addresses; }
From source file:com.acc.storefront.tags.Functions.java
/** * JSP EL Function to get an Image for a Store in a specific format * /*from www. ja va 2 s . c o m*/ * @param store * the store * @param format * the desired image format * @return the image */ public static ImageData getImageForStoreAndFormat(final PointOfServiceData store, final String format) { if (store != null && format != null) { final Collection<ImageData> images = store.getStoreImages(); if (images != null && !images.isEmpty()) { for (final ImageData image : images) { if (format.equals(image.getFormat())) { return image; } } } } return null; }
From source file:com.doculibre.constellio.plugins.PluginFactory.java
public static boolean isValidPlugin(String name) { boolean validPlugin; File pluginsDir = getPluginsDir(); File pluginDir = new File(pluginsDir, name); if (!pluginDir.exists() || pluginDir.isFile()) { validPlugin = false;//from www . java 2 s . co m } else { Collection<File> pluginJarFiles = FileUtils.listFiles(pluginDir, new String[] { "jar" }, false); // Accept only one root dir jar File pluginJarFile = pluginJarFiles.isEmpty() ? null : pluginJarFiles.iterator().next(); if (pluginJarFile != null) { validPlugin = true; } else { validPlugin = false; } } return validPlugin; }
From source file:com.flexive.shared.media.impl.FxMimeType.java
/** * This is a helper method for mime type detection based on medsea's mimeutils * Mime type detection based on header bytes and filenames, the latter is used as a * fallback if header detection fails/* w w w . j av a 2s . com*/ * * @param header the file header as a byte array * @param fileName the file name as a String * @return the FxMimeType constructed from the input * @since 3.1.2 */ @SuppressWarnings({ "unchecked" }) public static FxMimeType detectMimeType(byte[] header, String fileName) { MimeType mt; initialize(); // try and find the mimetype from the given file header Collection<MimeType> detected = MimeUtil.getMimeTypes(header); if (!detected.isEmpty()) { mt = MimeUtil.getMostSpecificMimeType(detected); if (!"application/octet-stream".equals(mt.toString())) { return new FxMimeType(mt.getMediaType(), mt.getSubType()); } } // extension based detection if (LOG.isDebugEnabled()) { LOG.debug("Failed to detect file's mime type from header, trying a file extension match: " + fileName); } // check manual extension replacement table if (fileName != null && fileName.indexOf('.') != -1) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1); if (EXT_REPLACEMENTS.containsKey(extension.toLowerCase())) { return new FxMimeType(EXT_REPLACEMENTS.get(extension)); } } // use extension detector from mime-utils if (StringUtils.isNotBlank(fileName)) { detected = MimeUtil.getMimeTypes(fileName); } if (detected.isEmpty()) { return new FxMimeType(UNKNOWN); } // the first mime-type from mime-util's mapping table is usually fine mt = detected.iterator().next(); return new FxMimeType(mt.getMediaType(), mt.getSubType()); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step9AgreementCollector.java
@SuppressWarnings("unchecked") public static void computeObservedAgreement(File goldDataFolder, File outputDir) throws Exception { // iterate over query containers for (File f : FileUtils.listFiles(goldDataFolder, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { // only non-empty and annotated results // No annotations found for document: clueWebID: clueweb12-1407wb-22-10643, queryID: 1006 // <clueWebID>clueweb12-1407wb-22-10643</clueWebID> // <score>5.93809186</score> // <additionalInfo>indri</additionalInfo> // <plainText></plainText> if (rankedResult.plainText != null && !rankedResult.plainText.isEmpty()) { if (rankedResult.mTurkRelevanceVotes.isEmpty()) { // throw new IllegalStateException("No annotations found for document: " System.err.println("No annotations found for document: " + "clueWebID: " + rankedResult.clueWebID + ", queryID: " + queryResultContainer.qID); } else { // first, get all the sentence IDs byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); // for each sentence, we'll collect all its annotations TreeMap<Integer, SortedMap<String, String>> sentencesAndRelevanceAnnotations = collectSentenceIDs( jCas);//from w w w . ja v a2 s . com // now we will the map with mturk annotations // the list of true/false for each sentence will be consistent (the annotator ordering remains) for (QueryResultContainer.MTurkRelevanceVote mTurkRelevanceVote : rankedResult.mTurkRelevanceVotes) { for (QueryResultContainer.SingleSentenceRelevanceVote sentenceRelevanceVote : mTurkRelevanceVote.singleSentenceRelevanceVotes) { String sentenceIDString = sentenceRelevanceVote.sentenceID; if (sentenceIDString == null || sentenceIDString.isEmpty()) { throw new IllegalStateException("Empty sentence ID for turker " + mTurkRelevanceVote.turkID + ", HIT: " + mTurkRelevanceVote.hitID + ", clueWebID: " + rankedResult.clueWebID + ", queryID: " + queryResultContainer.qID); } else { Integer sentenceIDInt = Integer.valueOf(sentenceIDString); String value = sentenceRelevanceVote.relevant; // add to the list // sanity check first if (sentencesAndRelevanceAnnotations.get(sentenceIDInt) .containsKey(mTurkRelevanceVote.turkID)) { System.err.println("Annotations for sentence " + sentenceIDInt + " for turker " + mTurkRelevanceVote.turkID + " are duplicate"); } sentencesAndRelevanceAnnotations.get(sentenceIDInt) .put(mTurkRelevanceVote.turkID, value); } } } // for (Map.Entry<Integer, SortedMap<String, String>> entry : sentencesAndRelevanceAnnotations // .entrySet()) { // System.out.println(entry.getKey() + ": " + entry.getValue()); // } // we collect only the "clean" ones Map<Integer, SortedMap<String, String>> cleanSentencesAndRelevanceAnnotations = new HashMap<>(); // sanity check -- all sentences are covered with the same number of annotations for (Map.Entry<Integer, SortedMap<String, String>> entry : sentencesAndRelevanceAnnotations .entrySet()) { SortedMap<String, String> singleSentenceAnnotations = entry.getValue(); // remove empty sentences if (singleSentenceAnnotations.values().isEmpty()) { // throw new IllegalStateException( System.err.println("Empty annotations for sentence, " + "sentenceID: " + entry.getKey() + ", " + "clueWebID: " + rankedResult.clueWebID + ", queryID: " + queryResultContainer.qID + "; number of assignments: " + singleSentenceAnnotations.values().size() + ", expected: " + NUMBER_OF_TURKERS_PER_HIT + ". Sentence will be skipped in evaluation"); } else if (singleSentenceAnnotations.values().size() != NUMBER_OF_TURKERS_PER_HIT) { System.err.println("Inconsistent annotations for sentences, " + "sentenceID: " + entry.getKey() + ", " + "clueWebID: " + rankedResult.clueWebID + ", queryID: " + queryResultContainer.qID + "; number of assignments: " + singleSentenceAnnotations.values().size() + ", expected: " + NUMBER_OF_TURKERS_PER_HIT + ". Sentence will be skipped in evaluation"); } else { cleanSentencesAndRelevanceAnnotations.put(entry.getKey(), entry.getValue()); } } // fill the annotation study CodingAnnotationStudy study = new CodingAnnotationStudy(NUMBER_OF_TURKERS_PER_HIT); study.addCategory("true"); study.addCategory("false"); for (SortedMap<String, String> singleSentenceAnnotations : cleanSentencesAndRelevanceAnnotations .values()) { // only non-empty sentences Collection<String> values = singleSentenceAnnotations.values(); if (!values.isEmpty() && values.size() == NUMBER_OF_TURKERS_PER_HIT) { study.addItemAsArray(values.toArray()); } } // System.out.println(study.getCategories()); // Fleiss' multi-pi. FleissKappaAgreement fleissKappaAgreement = new FleissKappaAgreement(study); double percentage; try { percentage = fleissKappaAgreement.calculateObservedAgreement(); } catch (InsufficientDataException ex) { // dkpro-statistics feature, see https://github.com/dkpro/dkpro-statistics/issues/24 percentage = 1.0; } if (!Double.isNaN(percentage)) { rankedResult.observedAgreement = percentage; // System.out.println(sentencesAndRelevanceAnnotations.values()); } else { System.err.println("Observed agreement is NaN."); } } } } // and save the query to output dir File outputFile = new File(outputDir, queryResultContainer.qID + ".xml"); FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8"); System.out.println("Finished " + outputFile); } }
From source file:etymology.util.EtyMath.java
public static double getMean(Collection<Double> values) { if (values == null || values.isEmpty()) { return 0; }//from w w w .j a v a 2 s. c o m double val = 0.0; for (double value : values) { val += value; } return val / values.size(); }
From source file:com.marvelution.jira.plugins.hudson.utils.UserUtils.java
/** * Helper method to check if the given {@link User} is a member of at least one of the groups in the * {@link Collection}/*from ww w . j a v a 2 s . co m*/ * * @param user the {@link User} to check * @param groupNames the {@link Collection} of groupnames to check against * @param crowdService the {@link CrowdService} implementation * @return <code>true</code> if the {@link User} is a member of at least one group, <code>false</code> otherwise */ public static boolean isUserMemberOfAtleastOneGroup(final User user, Collection<String> groupNames, final CrowdService crowdService) { if (user == null) { throw new IllegalArgumentException("Invalid User variable"); } if (groupNames == null || groupNames.isEmpty()) { return false; } for (String groupName : groupNames) { if (crowdService.isUserMemberOfGroup(user.getName(), groupName)) { return true; } } // Still here? Then we where not a member of any of the groups in the collection return false; }
From source file:com.the3.base.repository.DynamicSpecifications.java
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) { return new Specification<T>() { @Override//from www.j a va 2s .c o m public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (filters != null && !filters.isEmpty()) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
From source file:com.net2plan.utils.CollectionUtils.java
/** * Checks whether all elements of a collection are present in another one. * * @param <A> Key type// w ww .j a v a2s . c om * @param container Container collection * @param collection Collection with elements to be checked * @return {@code true} if all elements in {@code collection} are present in {@code container}, and {@code false} otherwise. If {@code container} is empty, it will return {@code false} */ public static <A> boolean containsAll(Collection<A> container, Collection<A> collection) { if (container.isEmpty()) return false; Set<A> set = new LinkedHashSet<A>(container); set.removeAll(collection); return set.isEmpty(); }
From source file:com.github.horrorho.liquiddonkey.cloud.data.FileGroups.java
public static ChunkServer.FileGroups from(HttpClient client, Core core, String mmeAuthToken, Snapshot snapshot) throws BadDataException, IOException { logger.trace("<< get() < dsPrsID: {} udid: {} snapshot: {} files: {}", snapshot.dsPrsID(), snapshot.backupUDID(), snapshot.snapshotID(), snapshot.filesCount()); if (!core.dsPrsID().equals(snapshot.dsPrsID())) { logger.error("-- from() > dsPrsID mismatch, core: {} snapshot: {}", core.dsPrsID(), snapshot.dsPrsID()); }/*from w w w .j av a 2 s. c o m*/ // Signatures represent unique files hashes. // Discard duplicate signatures. Collisions unlikely. // Null signatures are empty files/ non-downloadables. Collection<ICloud.MBSFile> unique = snapshot.files().stream().filter(ICloud.MBSFile::hasSignature) .collect(Collectors.toCollection(HashSet::new)); logger.debug("-- get() > rationalized count: {}", unique.size()); List<ICloud.MBSFileAuthToken> authTokens = unique.isEmpty() ? new ArrayList<>() : fileGroupsClient.getFiles(client, snapshot.dsPrsID(), mmeAuthToken, core.mobileBackupUrl(), snapshot.backupUDID(), Integer.toString(snapshot.snapshotID()), unique); ICloud.MBSFileAuthTokens tokens = fileIdToSignatureAuthTokens(unique, authTokens); ChunkServer.FileGroups fileGroups = authTokens.isEmpty() ? ChunkServer.FileGroups.getDefaultInstance() : fileGroupsClient.authorizeGet(client, snapshot.dsPrsID(), core.contentUrl(), tokens); logger.trace(">> get() > fileGroups: {}", fileGroups.getFileGroupsCount()); return fileGroups; }