Example usage for java.util Set contains

List of usage examples for java.util Set contains

Introduction

In this page you can find the example usage for java.util Set contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:com.taobao.android.builder.tools.manifest.ManifestHelper.java

public static List<ManifestProvider> getBundleManifest(AppVariantContext appVariantContext,
        AtlasDependencyTree dependencyTree, AtlasExtension atlasExtension) {

    Set<String> notMergedArtifacts = getNotMergedBundles(atlasExtension);

    List<ManifestProvider> bundleProviders = new ArrayList<>();

    for (AwbBundle awbBundle : dependencyTree.getAwbBundles()) {
        String cord = String.format("%s:%s", awbBundle.getResolvedCoordinates().getGroupId(),
                awbBundle.getResolvedCoordinates().getArtifactId());

        if (null != notMergedArtifacts && notMergedArtifacts.contains(cord)) {
            continue;
        }//ww  w .ja  va 2s  .  c  om

        bundleProviders.add(createManifestProvider(awbBundle.getAndroidLibrary(), appVariantContext));

        for (AndroidLibrary androidLibrary : awbBundle.getAndroidLibraries()) {
            bundleProviders.add(createManifestProvider(androidLibrary, appVariantContext));
        }

    }

    return bundleProviders;

}

From source file:com.act.lcms.db.analysis.AnalysisHelper.java

private static Map<Pair<String, Double>, MS1ScanForWellAndMassCharge> getMultipleMS1s(MS1 ms1,
        Set<Pair<String, Double>> metlinMasses, String ms1File)
        throws ParserConfigurationException, IOException, XMLStreamException {

    // In order for this to sit well with the data model we'll need to ensure the keys are all unique.
    Set<String> uniqueKeys = new HashSet<>();
    metlinMasses.stream().map(Pair::getLeft).forEach(x -> {
        if (uniqueKeys.contains(x)) {
            throw new RuntimeException(
                    String.format("Assumption violation: found duplicate metlin mass keys: %s", x));
        }//  w  w  w.  ja va 2 s .c om
        uniqueKeys.add(x);
    });

    Iterator<LCMSSpectrum> ms1Iterator = new LCMSNetCDFParser().getIterator(ms1File);

    Map<Double, List<XZ>> scanLists = new HashMap<>(metlinMasses.size());
    // Initialize reading buffers for all of the target masses.
    metlinMasses.forEach(x -> {
        if (!scanLists.containsKey(x.getRight())) {
            scanLists.put(x.getRight(), new ArrayList<>());
        }
    });
    // De-dupe by mass in case we have exact duplicates, sort for well-ordered extractions.
    List<Double> sortedMasses = new ArrayList<>(scanLists.keySet());

    /* Note: this operation is O(n * m) where n is the number of (mass, intensity) readings from the scan
     * and m is the number of mass targets specified.  We might be able to get this down to O(m log n), but
     * we'll save that for once we get this working at all. */

    while (ms1Iterator.hasNext()) {
        LCMSSpectrum timepoint = ms1Iterator.next();

        // get all (mz, intensity) at this timepoint
        List<Pair<Double, Double>> intensities = timepoint.getIntensities();

        // for this timepoint, extract each of the ion masses from the METLIN set
        for (Double ionMz : sortedMasses) {
            // this time point is valid to look at if its max intensity is around
            // the mass we care about. So lets first get the max peak location
            double intensityForMz = ms1.extractMZ(ionMz, intensities);

            // the above is Pair(mz_extracted, intensity), where mz_extracted = mz
            // we now add the timepoint val and the intensity to the output
            XZ intensityAtThisTime = new XZ(timepoint.getTimeVal(), intensityForMz);
            scanLists.get(ionMz).add(intensityAtThisTime);
        }
    }

    Map<Pair<String, Double>, MS1ScanForWellAndMassCharge> finalResults = new HashMap<>(metlinMasses.size());

    /* Note: we might be able to squeeze more performance out of this by computing the
     * stats once per trace and then storing them.  But the time to compute will probably
     * be dwarfed by the time to extract the data (assuming deduplication was done ahead
     * of time), so we'll leave it as is for now. */
    for (Pair<String, Double> pair : metlinMasses) {
        String label = pair.getLeft();
        Double mz = pair.getRight();
        MS1ScanForWellAndMassCharge result = new MS1ScanForWellAndMassCharge();

        result.setMetlinIons(Collections.singletonList(label));
        result.getIonsToSpectra().put(label, scanLists.get(mz));
        ms1.computeAndStorePeakProfile(result, label);

        // DO NOT use isGoodPeak here.  We want positive and negative results alike.

        // There's only one ion in this scan, so just use its max.
        Double maxIntensity = result.getMaxIntensityForIon(label);
        result.setMaxYAxis(maxIntensity);
        // How/why is this not IonsToMax?  Just set it as such for this.
        result.setIndividualMaxIntensities(Collections.singletonMap(label, maxIntensity));

        finalResults.put(pair, result);
    }

    return finalResults;
}

From source file:com.frostwire.vuze.VuzeDownloadFactory.java

private static void setupPartialSelection(DownloadManager dm, Set<String> paths) {
    DiskManagerFileInfo[] infs = dm.getDiskManagerFileInfoSet().getFiles();

    try {/* www  .  ja  v  a 2  s  .co  m*/
        dm.getDownloadState().suppressStateSave(true);

        if (paths == null || paths.isEmpty()) {
            for (DiskManagerFileInfo inf : infs) {
                if (inf.isSkipped()) { // I don't want to trigger any internal logic
                    inf.setSkipped(false);
                }
            }
        } else {
            String savePath = dm.getSaveLocation().getPath();
            for (DiskManagerFileInfo inf : infs) {
                String path = inf.getFile(false).getPath();
                path = VuzeDownloadManager.removePrefixPath(savePath, path);
                inf.setSkipped(!paths.contains(path));
            }
        }
    } finally {
        dm.getDownloadState().suppressStateSave(false);
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardSyncer.java

/**
 * Note: This method has package level access, solely for testing purposes.
 * /*from w  w  w  .j  ava 2s  .co m*/
 * @param lease Candidate shard we are considering for deletion.
 * @param currentKinesisShardIds
 * @return true if neither the shard (corresponding to the lease), nor its parents are present in
 *         currentKinesisShardIds
 * @throws KinesisClientLibIOException Thrown if currentKinesisShardIds contains a parent shard but not the child
 *         shard (we are evaluating for deletion).
 */
static boolean isCandidateForCleanup(KinesisClientLease lease, Set<String> currentKinesisShardIds)
        throws KinesisClientLibIOException {
    boolean isCandidateForCleanup = true;

    if (currentKinesisShardIds.contains(lease.getLeaseKey())) {
        isCandidateForCleanup = false;
    } else {
        LOG.info("Found lease for non-existent shard: " + lease.getLeaseKey() + ". Checking its parent shards");
        Set<String> parentShardIds = lease.getParentShardIds();
        for (String parentShardId : parentShardIds) {

            // Throw an exception if the parent shard exists (but the child does not).
            // This may be a (rare) race condition between fetching the shard list and Kinesis expiring shards. 
            if (currentKinesisShardIds.contains(parentShardId)) {
                String message = "Parent shard " + parentShardId + " exists but not the child shard "
                        + lease.getLeaseKey();
                LOG.info(message);
                throw new KinesisClientLibIOException(message);
            }
        }
    }

    return isCandidateForCleanup;
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.tools.R2RMLToolkit.java

/**
 * The IRI-safe version of a string is obtained by applying the following
 * transformation in [RFC3987]./*from  www  .jav a  2  s.  c om*/
 * 
 * @throws R2RMLDataError
 * @throws MalformedURLException
 */
public static String getIRISafeVersion(String value) {
    // Any character that is not in the iunreserved production
    // iunreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" / ucschar
    StringBuffer buff = new StringBuffer(value.length());
    Set<Character> unreservedChars = new HashSet<Character>();

    unreservedChars.add('-');
    unreservedChars.add('.');
    unreservedChars.add('_');
    unreservedChars.add('~');
    unreservedChars.add('*');
    unreservedChars.add('\'');
    unreservedChars.add('(');
    unreservedChars.add(')');
    unreservedChars.add('!');
    unreservedChars.add('=');

    for (int i = 0; i < value.length(); i++) {
        char c = value.charAt(i);
        if (!(Character.isDigit(c) || Character.isLetter(c) || unreservedChars.contains(c))) {
            // Percent-encode each octet
            buff.append('%');
            buff.append(Integer.toHexString(c).toUpperCase());
        } else {
            buff.append(c);
        }
    }
    return buff.toString();
}

From source file:edu.jhuapl.openessence.web.util.ControllerUtils.java

/**
 * Check if the specified user is authorized to access the given data source.
 *
 * @param authentication user's authentication
 *///  w w w  . j av  a  2  s  .  c  o m
public static boolean isUserAuthorized(Authentication authentication, JdbcOeDataSource ds) {
    Set<String> roles = ds.getRoles();
    if (roles == null || roles.isEmpty()) {
        return true;
    }

    for (GrantedAuthority eachAuthority : authentication.getAuthorities()) {
        if (roles.contains(eachAuthority.toString())) {
            return true;
        }
    }

    return false;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignHelper.java

private static Predicate<String> getNoCompressPredicate(String srcPath) throws IOException {
    Set<String> noCompressEntries = new HashSet<>();
    ZipFile zipFile = new ZipFile(srcPath);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        if (zipEntry.getMethod() == 0) {
            if (zipEntry.getName().endsWith(".so")) {
                nativeLibrariesPackagingMode = NativeLibrariesPackagingMode.UNCOMPRESSED_AND_ALIGNED;
            }/*  w w w  .  j av a 2  s  . co  m*/
            noCompressEntries.add(zipEntry.getName());
        }
    }
    return s -> noCompressEntries.contains(s);
}

From source file:fr.landel.utils.io.InternalFileSystemUtils.java

/**
 * Create filename filter for directory tree.
 * /*w w w  .  j  a v  a 2  s .  c o m*/
 * @param exts
 *            The allowed extensions
 * @return The filter
 */
public static FilenameFilter createFilenameFilter(final String... exts) {
    Assertor.that(exts).isNotEmpty(ERROR_PARAM_NULL).and().not()
            .contains(null, "extensions array cannot contains 'null'").orElseThrow();

    final Set<String> allowedExts = new HashSet<>();
    for (String ext : exts) {
        allowedExts.add(ext.toLowerCase());
    }
    return new FilenameFilter() {
        @Override
        public boolean accept(final File file, final String name) {
            final String ext = InternalFileSystemUtils.getExtensionPart(name);
            if (ext != null) {
                return allowedExts.contains(ext.toLowerCase());
            }
            return false;
        }
    };
}

From source file:com.aurel.track.item.history.HistorySaverBL.java

/**
 * Gets the localized field changes/* ww w . j a v  a  2s.  c  o  m*/
 * @param afterItemSaveEventParam
 * @param locale
 * @param history true for history, false for e-mail
 * @return
 */
public static SortedMap<Integer, FieldChange> getLocalizedFieldChanges(
        AfterItemSaveEventParam afterItemSaveEventParam, Locale locale, boolean history) {
    SortedMap<Integer, FieldChange> fieldChangeMap = new TreeMap<Integer, FieldChange>();
    TWorkItemBean workItemBean = afterItemSaveEventParam.getWorkItemNew();
    TWorkItemBean workItemBeanOriginal = afterItemSaveEventParam.getWorkItemOld();
    Map<Integer, TFieldConfigBean> fieldConfigsMap = afterItemSaveEventParam.getFieldConfigs();
    Set<Integer> explicitHistoryFields = getHardCodedExplicitHistoryFields();
    //the attachment changes are also explicitly historized
    Set<Integer> attachmentHistoryFields = HistoryLoaderBL.getAttachmentHistoryFields();
    for (Integer fieldID : afterItemSaveEventParam.getInterestingFields()) {
        FieldChange fieldChange = new FieldChange();
        fieldChange.setFieldID(fieldID);
        //pseudo fields:attachment history
        if (attachmentHistoryFields.contains(fieldID)) {
            String fieldLabel = null;
            if (history) {
                fieldLabel = LocalizeUtil.getLocalizedTextFromApplicationResources(
                        HistoryLoaderBL.getHistoryFieldKey(fieldID), locale);
            } else {
                fieldLabel = LocalizeUtil.getLocalizedTextFromApplicationResources(
                        "admin.customize.automail.trigger.lbl.fieldType.attachment", locale);
            }
            fieldChange.setLocalizedFieldLabel(fieldLabel);
            fieldChange.setExplicitHistory(true);
            String newStringValue = workItemBean.getAttachment();
            fieldChange.setNewShowValue(newStringValue);
            if (workItemBeanOriginal != null) {
                String oldStringValue = workItemBeanOriginal.getAttachment();
                fieldChange.setOldShowValue(oldStringValue);
                fieldChange.setChanged(EqualUtils.notEqual(newStringValue, oldStringValue));
            } else {
                fieldChange.setChanged(true);
            }
        } else {
            IFieldTypeRT fieldType = FieldTypeManager.getFieldTypeRT(fieldID);
            Object newValue = workItemBean.getAttribute(fieldID);
            Object oldValue = null;
            if (workItemBeanOriginal != null) {
                oldValue = workItemBeanOriginal.getAttribute(fieldID);
            }
            TFieldConfigBean fieldConfigBean = fieldConfigsMap.get(fieldID);
            String fieldLabel = fieldConfigBean.getLabel();
            if (locale != null && !locale.equals(afterItemSaveEventParam.getLocale())) {
                fieldLabel = FieldRuntimeBL.localizeFieldConfig(fieldConfigBean.getObjectID(), locale);
                if (fieldLabel == null) {
                    LOGGER.debug("Field label is null for locale " + locale + " fall back to "
                            + fieldConfigBean.getLabel());
                    fieldLabel = fieldConfigBean.getLabel();
                }
            }
            fieldChange.setLocalizedFieldLabel(fieldLabel);
            fieldChange.setExplicitHistory(
                    explicitHistoryFields.contains(fieldID) || fieldConfigBean.isHistoryString());
            //get the new value to show
            fieldChange.setNewShowValue(fieldType.getShowValue(newValue, locale));
            if ((workItemBeanOriginal != null && fieldType.valueModified(newValue, oldValue)) ||
            //the rare case when the comment field is present on the create screen 
                    (workItemBeanOriginal == null && fieldID.intValue() == SystemFields.COMMENT
                            && newValue != null && !"".equals(newValue))) {
                //get the old value to show and set the changed flag.
                //the old value and change flag is set only by edit mode when the value is really changed
                //or by create mode when Comment is specified             
                fieldChange.setOldShowValue(fieldType.getShowValue(oldValue, locale));
                fieldChange.setChanged(true);
                LOGGER.debug("FieldID " + fieldID + " oldValue " + oldValue + " newValue " + newValue);
            }
        }
        fieldChangeMap.put(fieldID, fieldChange);
    }
    return fieldChangeMap;
}

From source file:at.alladin.rmbt.shared.Helperfunctions.java

/**
 * /*  w  w  w . j  a  v  a  2s .com*/
 * @param json
 * @param excludeKeys
 * @return
 */
@SuppressWarnings("unchecked")
public static String json2hstore(JSONObject json, Set<String> excludeKeys) {
    StringBuilder result = new StringBuilder();

    Iterator<String> jsonIterator = json.keys();

    try {
        boolean isFirst = true;
        while (jsonIterator.hasNext()) {
            String key = jsonIterator.next();

            if (excludeKeys == null || !excludeKeys.contains(key)) {
                if (!isFirst) {
                    if (json.opt(key) instanceof JSONObject) {
                        result.append(", \"" + key + "\" => \""
                                + json2hstore(json.optJSONObject(key), excludeKeys) + "\"");
                    } else {
                        Object data = json.get(key);
                        if (data != null) {
                            if (data instanceof String) {
                                data = "\""
                                        + ((String) data).replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'")
                                        + "\"";
                            } else if (data instanceof JSONArray) {
                                data = "\"" + ((JSONArray) data).toString().replaceAll("\"", "\\\\\"")
                                        .replaceAll("'", "\\\\'") + "\"";
                            }
                        }
                        result.append(", \"" + key + "\" => " + data);
                        //result.append(", \"" + key + "\" => \"" + json.getString(key).replaceAll("\"","\\\\\"").replaceAll("'","\\\\'") + "\"");   
                    }
                } else {
                    isFirst = false;
                    if (json.opt(key) instanceof JSONObject) {
                        result.append("\"" + key + "\" => \""
                                + json2hstore(json.optJSONObject(key), excludeKeys) + "\"");
                    } else {
                        Object data = json.get(key);
                        if (data != null) {
                            if (data instanceof String) {
                                data = "\""
                                        + ((String) data).replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'")
                                        + "\"";
                            } else if (data instanceof JSONArray) {
                                data = "\"" + ((JSONArray) data).toString().replaceAll("\"", "\\\\\"")
                                        .replaceAll("'", "\\\\'") + "\"";
                            }
                        }
                        result.append("\"" + key + "\" => " + data);
                        //result.append("\"" + key + "\" => \"" + json.getString(key).replaceAll("\"","\\\\\"").replaceAll("'","\\\\'") + "\"");
                    }
                }
            }
        }
    } catch (JSONException e) {
        return null;
    }

    return result.toString();
}