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.ctriposs.rest4j.common.testutils.DataAssert.java

/**
 * Asserts that two {@link DataMap}s are equal, subject to the {@code excludedProperties} and
 * {@code nullShouldEqualEmptyListOrMap} arguments.
 *
 * @param actualMap the {@link DataMap} we are checking
 * @param expectedMap the expected {@link DataMap}
 * @param excludedProperties the properties that will be ignored while checking the two DataMaps
 * @param nullShouldEqualEmptyListOrMap true if null should equal an empty {@link DataMap} or {@link DataList}
 *//* w  w w .  ja v a2  s . c  o m*/
public static void assertDataMapsEqual(DataMap actualMap, DataMap expectedMap, Set<String> excludedProperties,
        boolean nullShouldEqualEmptyListOrMap) {
    if (excludedProperties == null) {
        excludedProperties = Collections.emptySet();
    }

    if (actualMap == null || expectedMap == null) {
        Assert.assertEquals(actualMap, expectedMap, "Only one of the data maps is null!");
        return;
    }

    Set<String> failKeys = new HashSet<String>();

    // Assert key by key so it's easy to debug on assertion failure
    Set<String> allKeys = new HashSet<String>(actualMap.keySet());
    allKeys.addAll(expectedMap.keySet());
    for (String key : allKeys) {
        if (excludedProperties.contains(key)) {
            continue;
        }

        Object actualObject = actualMap.get(key);
        Object expectedObject = expectedMap.get(key);
        if (actualObject == null) {
            if (nullShouldEqualEmptyListOrMap && isEmptyListOrMap(expectedObject)) {
                continue;
            }
            if (expectedObject != null) {
                failKeys.add(key);
            }
        } else if (!actualObject.equals(expectedObject)) {
            if (nullShouldEqualEmptyListOrMap && expectedObject == null && isEmptyListOrMap(actualObject)) {
                continue;
            }
            failKeys.add(key);
        }
    }

    if (!failKeys.isEmpty()) {
        List<String> errorMessages = new ArrayList<String>();
        errorMessages.add(failKeys.size() + " properties don't match:");
        for (String k : failKeys) {
            errorMessages.add("\tMismatch on property \"" + k + "\", expected:<" + expectedMap.get(k)
                    + "> but was:<" + actualMap.get(k) + ">");
        }
        Assert.fail(StringUtils.join(errorMessages, ERROR_MESSAGE_SEPARATOR));
    }
}

From source file:com.mirth.connect.server.builders.JavaScriptBuilder.java

private static void appendAttachmentFunctions(StringBuilder builder, Set<String> scriptOptions) {
    // Helper function to access attachments (returns List<Attachment>)
    builder.append("function getAttachments() {");
    builder.append("return AttachmentUtil.getMessageAttachments(connectorMessage);");
    builder.append("}\n");

    // Helper function to set attachment
    if (scriptOptions != null && scriptOptions.contains("useAttachmentList")) {

        builder.append("function addAttachment(data, type) {\n");
        builder.append("return AttachmentUtil.addAttachment(mirth_attachments, data, type);\n");
        builder.append("}\n");
    } else {//from w w w.  j ava 2  s  .c  om
        builder.append("function addAttachment(data, type) {\n");
        builder.append("return AttachmentUtil.createAttachment(connectorMessage, data, type);\n");
        builder.append("}\n");
    }
}

From source file:bioLockJ.util.MetadataUtil.java

/**
 * When a new column is added to metadata, this method will add the column, with all row values.
 * The updated file is output to the "outputDir" to be picked up by the next executor.
 * @param name/* w  ww  .j  a v  a2s . co  m*/
 * @param map
 * @param fileDir
 * @throws Exception
 */
public static void addNumericColumn(final String name, final Map<String, Integer> map, final File fileDir)
        throws Exception {
    if (getAttributeNames().contains(name)) {
        Log.out.warn("Metadata already contains column [" + name + "] so this data will not be added to "
                + metadataFile.getName());
        return;
    }

    numericFields.add(name);

    final BufferedReader reader = new BufferedReader(new FileReader(metadataFile));
    metadataFile = new File(fileDir.getAbsolutePath() + File.separator + metadataFile.getName());
    final BufferedWriter writer = new BufferedWriter(new FileWriter(metadataFile));

    Log.out.info("Adding new attribute [" + name + "] to metadata");
    boolean isHeaderRow = true;
    try {
        final Set<String> keys = map.keySet();
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            final StringTokenizer st = new StringTokenizer(line, Constants.TAB_DELIM);
            if (isHeaderRow) {
                isHeaderRow = false;
                line += Constants.TAB_DELIM + name;
            } else {
                final String id = st.nextToken();
                if (keys.contains(id)) {
                    line += Constants.TAB_DELIM + map.get(id);
                } else {
                    line += Constants.TAB_DELIM + Config.requireString(Config.INPUT_NULL_VALUE);
                }
            }

            writer.write(line + Constants.RETURN);
        }
    } catch (final Exception ex) {
        Log.out.error("Error occurred updating metadata with new attribute [" + name + "]", ex);
    } finally {
        reader.close();
        writer.close();
        refresh();
    }
}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java

/** Builds a multimap of named SQL inputs
 * @param context the analytic context retrieved from the 
 * @return A multi map of Java RDDs against name (with input name built as resource_name:data_service if not present)
 *///  ww  w. j  av a  2 s  . c om
@SuppressWarnings("unchecked")
public static Multimap<String, DataFrame> buildBatchSparkSqlInputs(final IAnalyticsContext context,
        final Optional<ProcessingTestSpecBean> maybe_test_spec, final SQLContext spark_sql_context,
        final Set<String> exclude_names) {
    final AnalyticThreadJobBean job = context.getJob().get();

    final Multimap<String, DataFrame> mutable_builder = HashMultimap.create();

    transformInputBean(Optionals.ofNullable(job.inputs()).stream(), maybe_test_spec)
            .filter(input -> !exclude_names.contains(input.name())).forEach(Lambdas.wrap_consumer_u(input -> {
                Optional<SparkSqlAccessContext> maybe_input_format_info = context
                        .getServiceInput(SparkSqlAccessContext.class, Optional.empty(), job, input);
                maybe_input_format_info.flatMap(input_format_info -> input_format_info.getAccessConfig())
                        .map(info_objects -> (Function<SQLContext, DataFrame>) info_objects.get(input.name()))
                        .ifPresent(rdd_getter -> {
                            mutable_builder.put(input.name(), rdd_getter.apply(spark_sql_context));
                        });
            }));

    return mutable_builder;
}

From source file:com.streak.logging.utils.AnalysisUtility.java

public static TableSchema createSchema(LogsFieldExporterSet exporterSet) {
    Set<String> fieldNames = new HashSet<String>();

    List<LogsFieldExporter> exporters = exporterSet.getExporters();
    TableSchema schema = new TableSchema();
    schema.setFields(new ArrayList<TableFieldSchema>());

    for (LogsFieldExporter exporter : exporters) {
        for (int i = 0; i < exporter.getFieldCount(); i++) {
            String fieldName = exporter.getFieldName(i);
            String fieldMode = "NULLABLE";
            String fieldType = exporter.getFieldType(i).toLowerCase().intern();

            if (fieldNames.contains(fieldName)) {
                throw new InvalidFieldException(
                        "BigqueryFieldExporterSet " + exporterSet.getClass().getCanonicalName()
                                + " defines multiple fields with name " + exporter.getFieldName(i));
            }/*from www .j a  v a  2s.c  o  m*/
            fieldNames.add(fieldName);

            if (exporter.getFieldRepeated(i)) {
                fieldMode = "REPEATED";
            }

            List<TableFieldSchema> subfields = null;
            if (fieldType.equals("record")) {
                subfields = exporter.getFieldFields(i);
            }

            TableFieldSchema tfs = new TableFieldSchema();
            tfs.setName(fieldName);
            tfs.setType(fieldType);
            tfs.setMode(fieldMode);

            if (subfields != null) {
                tfs.setFields(subfields);
            }
            schema.getFields().add(tfs);
        }
    }
    return schema;
}

From source file:com.gongpingjia.carplay.service.util.ActivityUtil.java

private static List<ActivityWeight> sortActivityList(List<Activity> activities, Date currentTime,
        Landmark nowLandmark, double maxDistance, long maxPubTime, int genderType, Set<String> toRemoveSet) {
    ArrayList<ActivityWeight> awList = new ArrayList<>(activities.size());
    for (Activity activity : activities) {
        Map<String, Object> user = activity.getOrganizer();

        ///*ww w . jav a2  s.  c  o m*/
        if (genderType == 0) {
            if (!StringUtils.equals(String.valueOf(user.get("gender")), Constants.UserGender.MALE)) {
                continue;
            }
        } else if (genderType == 1) {
            if (!StringUtils.equals(String.valueOf(user.get("gender")), Constants.UserGender.FEMALE)) {
                continue;
            }
        }
        if (null != toRemoveSet && !toRemoveSet.isEmpty()) {
            if (toRemoveSet.contains(activity.getActivityId())) {
                continue;
            }
        }

        ActivityWeight aw = new ActivityWeight(activity);
        //  ?
        if (StringUtils.equals(String.valueOf(user.get("licenseAuthStatus")), Constants.AuthStatus.ACCEPT)) {
            aw.setCarOwnerFlag(true);
        }
        //??
        if (StringUtils.equals(String.valueOf(user.get("photoAuthStatus")), Constants.AuthStatus.ACCEPT)) {
            aw.setAvatarFlag(true);
        }
        //TODO
        //? ????

        //???
        initWeight(currentTime, nowLandmark, aw, maxDistance, maxPubTime);
        awList.add(aw);
    }
    Collections.sort(awList);
    return awList;
}

From source file:edu.wpi.checksims.util.PairGenerator.java

/**
 * Generate all possible unique, unordered pairs of submissions.
 *
 * @param submissions Submissions to generate pairs from
 * @return Set of all unique, unordered pairs of submissions
 *//*from ww w . j av  a2  s  .c  om*/
public static Set<Pair<Submission, Submission>> generatePairs(Set<Submission> submissions) {
    checkNotNull(submissions);
    checkArgument(submissions.size() >= 2, "Cannot generate pairs with less than 2 submissions!");

    Set<Pair<Submission, Submission>> pairs = new HashSet<>();

    List<Submission> remaining = new ArrayList<>();
    remaining.addAll(submissions);

    while (remaining.size() >= 2) {
        // Get the first submission in the list and remove it
        Submission first = remaining.get(0);
        remaining.remove(0);

        // Form a pair for every remaining submission by pairing with the first, removed submission
        for (Submission submission : remaining) {
            Pair<Submission, Submission> pair = Pair.of(first, submission);
            Pair<Submission, Submission> reversed = Pair.of(submission, first);

            // Something's wrong, we've made a duplicate pair (but reversed)
            // Should never happen
            if (pairs.contains(reversed)) {
                throw new RuntimeException("Internal error in pair generation: duplicate pair produced!");
            }

            // Add the newly-generated pair to our return
            pairs.add(pair);
        }
    }

    return pairs;
}

From source file:biz.netcentric.cq.tools.actool.helper.PurgeHelper.java

public static String deleteAcesFromAuthorizables(final Session session, final Set<String> authorizabeIDs,
        final Set<AclBean> aclBeans) throws UnsupportedRepositoryOperationException, RepositoryException,
        AccessControlException, PathNotFoundException, AccessDeniedException, LockException, VersionException {

    StopWatch sw = new StopWatch();
    sw.start();/*ww  w  .  j a v  a 2s  .  c  o m*/
    StringBuilder message = new StringBuilder();
    AccessControlManager aMgr = session.getAccessControlManager();
    long aceCounter = 0;

    for (AclBean aclBean : aclBeans) {
        if (aclBean != null) {
            for (AccessControlEntry ace : aclBean.getAcl().getAccessControlEntries()) {
                String authorizableId = ace.getPrincipal().getName();
                if (authorizabeIDs.contains(authorizableId)) {
                    String parentNodePath = aclBean.getParentPath();
                    String acePath = aclBean.getJcrPath();
                    aclBean.getAcl().removeAccessControlEntry(ace);
                    aMgr.setPolicy(aclBean.getParentPath(), aclBean.getAcl());
                    AcHelper.LOG.info("removed ACE {} from ACL of node: {}", acePath, parentNodePath);
                    message.append("removed ACE of principal: " + authorizableId + " from ACL of node: "
                            + parentNodePath + "\n");
                    aceCounter++;
                }
            }
        }
    }
    sw.stop();
    long executionTime = sw.getTime();
    message.append("\n\nDeleted: " + aceCounter + " ACEs in repository");
    message.append("\nExecution time: " + executionTime + " ms");
    return message.toString();
}

From source file:com.adguard.android.contentblocker.ServiceApiClient.java

/**
 * Downloads filter versions.//from  w  ww  .j a va2  s  .  c o  m
 *
 * @param filters list
 * @return filters list with downloaded versions
 */
public static List<FilterList> downloadFilterVersions(Context context, List<FilterList> filters)
        throws IOException, JSONException {
    String downloadUrl = RawResources.getCheckFilterVersionsUrl(context);
    LOG.info("Sending request to {}", downloadUrl);
    String response = downloadString(downloadUrl);
    if (StringUtils.isBlank(response)) {
        return null;
    }

    Set<Integer> filterIds = new HashSet<>(filters.size());
    for (FilterList filter : filters) {
        filterIds.add(filter.getFilterId());
    }

    Map map = readValue(response, Map.class);
    if (map == null || !map.containsKey("filters")) {
        LOG.error("Filters parse error! Response:\n{}", response);
        return null;
    }

    ArrayList filterList = (ArrayList) map.get("filters");
    List<FilterList> result = new ArrayList<>(filters.size());
    String[] parsePatterns = { "yyyy-MM-dd'T'HH:mm:ssZ" };

    for (Object filterObj : filterList) {
        Map filter = (Map) filterObj;
        int filterId = (int) filter.get("filterId");
        if (!filterIds.contains(filterId)) {
            continue;
        }
        FilterList list = new FilterList();
        list.setName((String) filter.get("name"));
        list.setDescription((String) filter.get("description"));
        list.setFilterId(filterId);
        list.setVersion((String) filter.get("version"));
        try {
            String timeUpdated = (String) filter.get("timeUpdated");
            list.setTimeUpdated(DateUtils.parseDate(timeUpdated, parsePatterns));
        } catch (ParseException e) {
            LOG.error("Unable to parse date from filters:\n", e);
        }
        result.add(list);
    }

    return result;

}

From source file:freebase.api.FreebaseAPI.java

public static void removeDuplicates(String filepath) {
    final List<String> file = Utils.readFileLineByLine(filepath, true);
    final List<String> file_all = Utils.readFileLineByLine(filepath + ".all", true);
    Set<String> mids = new HashSet<>();
    StringBuilder fileout_str = new StringBuilder();
    StringBuilder fileout_all_str = new StringBuilder();
    int duplicateCounts = 0;
    System.out.println("Removing duplicates from " + filepath);
    for (int i = 0; i < file_all.size(); i++) {
        String line = file_all.get(i);
        String[] split = line.split("\\t");
        String mid = split[1];//from   w ww .  ja  va2  s  . c om
        //            System.out.println("mid=" + mid);
        if (!mids.contains(mid)) {
            fileout_str.append(file.get(i)).append(NEWLINE);
            fileout_all_str.append(line).append(NEWLINE);
            mids.add(mid);
        } else {
            duplicateCounts++;
        }
    }
    System.out.println("Writing to file...");
    Utils.writeDataIntoFile(fileout_str.toString(), filepath + ".2");
    Utils.writeDataIntoFile(fileout_all_str.toString(), filepath + ".all.2");

    System.out.println("Duplicates# :" + duplicateCounts);
}