Example usage for java.util SortedSet size

List of usage examples for java.util SortedSet size

Introduction

In this page you can find the example usage for java.util SortedSet size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.bibsonomy.recommender.tags.meta.TagsFromFirstWeightedBySecondFilledByThirdTagRecommender.java

@Override
protected void addRecommendedTagsInternal(final Collection<RecommendedTag> recommendedTags,
        final Post<? extends Resource> post) {

    if (firstTagRecommender == null || secondTagRecommender == null || thirdTagRecommender == null) {
        throw new IllegalArgumentException("No tag recommenders available.");
    }/*ww  w .  j a  v  a  2s.c  o  m*/

    /*
     * Get recommendation from first recommender.
     */
    final SortedSet<RecommendedTag> firstRecommendedTags = firstTagRecommender.getRecommendedTags(post);
    log.debug("got " + firstRecommendedTags.size() + " recommendations from " + firstTagRecommender);
    if (log.isDebugEnabled()) {
        log.debug(firstRecommendedTags);
    }

    /*
     * Get recommendation from second tag recommender.
     * 
     * Since we need to get the scores from this recommender for the tags from the first
     * recommender, we use the MapBackedSet, such that we can easily get tags by their name.
     */
    final MapBackedSet<String, RecommendedTag> secondRecommendedTags = new MapBackedSet<String, RecommendedTag>(
            new TopTagsMapBackedSet.DefaultKeyExtractor());
    secondTagRecommender.addRecommendedTags(secondRecommendedTags, post);
    log.debug("got " + secondRecommendedTags.size() + " recommendations from " + secondTagRecommender);

    final double minScore = doFirstRound(recommendedTags, firstRecommendedTags, secondRecommendedTags);
    log.debug("used " + recommendedTags.size()
            + " tags from the first recommender which occured in second recommender");

    final int ctr = doSecondRound(recommendedTags, firstRecommendedTags, secondRecommendedTags, minScore);
    log.debug("used another " + ctr + " tags from the first recommender ");

    final SortedSet<RecommendedTag> thirdRecommendedTags = thirdTagRecommender.getRecommendedTags(post);
    log.debug("got " + thirdRecommendedTags.size() + " recommendations from " + thirdTagRecommender);
    doThirdRound(recommendedTags, thirdRecommendedTags, minScore, ctr);

    if (log.isDebugEnabled()) {
        log.debug("final recommendation: " + recommendedTags);
    }

}

From source file:org.eclipse.skalli.core.user.LocalUserComponent.java

@Override
protected void validateEntity(User entity) throws ValidationException {
    SortedSet<Issue> issues = validate(entity, Severity.FATAL);
    if (issues.size() > 0) {
        throw new ValidationException("User could not be saved due to the following reasons:", issues);
    }/*from w w  w  .  j  a  v a 2  s . c  o m*/
}

From source file:org.apache.hadoop.hbase.regionserver.MemStoreWrapper.java

/**
 * Flushes the snapshot of the memstore.
 * Flushes the mob data to the mob files, and flushes the name of these mob files to HBase.
 * @param snapshot The snapshot of the memstore.
 * @throws IOException/*from   w  w w.  j  a va  2 s  . c o  m*/
 */
private void internalFlushCache(final SortedSet<KeyValue> snapshot) throws IOException {
    if (snapshot.size() == 0) {
        return;
    }
    // generate the files into a temp directory.
    String tempPathString = context.getConfiguration().get(SweepJob.WORKING_FILES_DIR_KEY);
    StoreFile.Writer mobFileWriter = MobUtils.createWriterInTmp(conf, fs, hcd, partitionId.getDate(),
            new Path(tempPathString), snapshot.size(), hcd.getCompactionCompression(),
            partitionId.getStartKey(), cacheConfig);

    String relativePath = mobFileWriter.getPath().getName();
    LOG.info("Create files under a temp directory " + mobFileWriter.getPath().toString());

    byte[] referenceValue = Bytes.toBytes(relativePath);
    int keyValueCount = 0;
    KeyValueScanner scanner = new CollectionBackedScanner(snapshot, KeyValue.COMPARATOR);
    scanner.seek(KeyValue.createFirstOnRow(HConstants.EMPTY_START_ROW));
    Cell cell = null;
    while (null != (cell = scanner.next())) {
        KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
        mobFileWriter.append(kv);
        keyValueCount++;
    }
    scanner.close();
    // Write out the log sequence number that corresponds to this output
    // hfile. The hfile is current up to and including logCacheFlushId.
    mobFileWriter.appendMetadata(Long.MAX_VALUE, false);
    mobFileWriter.close();

    MobUtils.commitFile(conf, fs, mobFileWriter.getPath(), mobFamilyDir, cacheConfig);
    context.getCounter(SweepCounter.FILE_AFTER_MERGE_OR_CLEAN).increment(1);
    // write reference/fileName back to the store files of HBase.
    scanner = new CollectionBackedScanner(snapshot, KeyValue.COMPARATOR);
    scanner.seek(KeyValue.createFirstOnRow(HConstants.EMPTY_START_ROW));
    cell = null;
    while (null != (cell = scanner.next())) {
        List<Tag> existingTags = Tag.asList(cell.getTagsArray(), cell.getTagsOffset(), cell.getTagsLength());
        if (existingTags.isEmpty()) {
            existingTags = new ArrayList<Tag>();
        }
        // the cell whose value is the name of a mob file has such a tag.
        Tag mobRefTag = new Tag(MobConstants.MOB_REFERENCE_TAG_TYPE, HConstants.EMPTY_BYTE_ARRAY);
        existingTags.add(mobRefTag);
        long valueLength = cell.getValueLength();
        byte[] newValue = Bytes.add(Bytes.toBytes(valueLength), referenceValue);

        KeyValue reference = new KeyValue(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
                cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(), cell.getQualifierArray(),
                cell.getQualifierOffset(), cell.getQualifierLength(), cell.getTimestamp(), KeyValue.Type.Put,
                newValue, 0, newValue.length, existingTags);

        Put put = new Put(reference.getRow());
        put.add(reference);
        table.put(put);
        context.getCounter(SweepCounter.RECORDS_UPDATED).increment(1);
    }
    if (keyValueCount > 0) {
        table.flushCommits();
    }
    scanner.close();
}

From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImplTest.java

@Test
public void readEmailTest() throws Exception {
    HashSet<DayReport> daySet = reader.readEmail();
    Assert.assertNotNull(daySet);/*from  w ww. ja va  2s.  com*/
    Assert.assertEquals(2, daySet.size());
    DayReport fromTester = null;
    DayReport fromAnotherTester = null;
    SortedSet<DayReport> sortedDaySet = new TreeSet<DayReport>();
    sortedDaySet.addAll(daySet);
    Assert.assertEquals(2, sortedDaySet.size());
    Iterator<DayReport> iterator = sortedDaySet.iterator();
    while (iterator.hasNext()) {
        fromAnotherTester = iterator.next();
        fromTester = iterator.next();
    }

    Assert.assertNotNull(fromAnotherTester);
    Assert.assertNotNull(fromTester);
    Assert.assertEquals(USER2, fromTester.getPersonId());
    Assert.assertEquals(USER, fromAnotherTester.getPersonId());
    Assert.assertEquals(3, fromTester.getReportList().size());
    Assert.assertEquals(1, fromAnotherTester.getReportList().size());
    Assert.assertEquals(TEST_STRING, fromTester.getReportList().get(0).getWorkDescription());
    Assert.assertEquals(8, fromAnotherTester.getReportList().get(0).getElapsedTime());
    Assert.assertEquals(TEST_STRING2, fromTester.getReportList().get(2).getWorkDescription());

}

From source file:org.cloudata.examples.web.WebKeyRangePartitioner.java

public int getPartition(WritableComparable key, Writable value, int numPartitions) {
    if (confException != null) {
        LOG.error(confException.getMessage(), confException);
        return -1;
    }//w ww. j  a  v  a  2  s .  c  o  m

    if (numPartitions != tabletInfoSet.size()) {
        LOG.error(
                "tablet count(" + tabletInfoSet.size() + ") not equals numPartitions (" + numPartitions + ")");
        return -1;
    }

    if (tabletInfoSet.size() == 0) {
        LOG.error("tablet partition size is zero");
        return -1;
    }
    int partitionNumber = 0;
    Text tKey = (Text) key;

    Row.Key rowKey;

    int keyIndex = tKey.find("\t");
    if (keyIndex < 0) {
        LOG.error("invalid value:" + tKey);
        rowKey = Row.Key.MAX_KEY;
    } else {
        rowKey = new Row.Key(tKey.getBytes(), 0, keyIndex);
    }

    SortedSet<RowKeyItem> tailSet = tabletInfoSet.tailSet(new RowKeyItem(rowKey, 0));
    RowKeyItem item = null;
    if (tailSet.size() > 0) {
        item = tailSet.first();
        partitionNumber = item.index;
    } else {
        item = tabletInfoSet.last();
        partitionNumber = item.index;
    }

    if (partitionNumber >= numPartitions) {
        LOG.info("Partition Number is : " + partitionNumber + ", numPartitions : " + numPartitions
                + ", Row.Key : " + key.toString());
        partitionNumber = numPartitions - 1;
    }
    //LOG.info("tablet partition num:" + partitionNumber);
    count++;
    if (count % 5000 == 0) {
        try {
            System.out.println("Partitioned:" + new String(rowKey.getBytes(), "EUC-KR") + ","
                    + new String(item.rowKey.getBytes(), "EUC-KR"));
        } catch (UnsupportedEncodingException e) {

        }
    }
    return partitionNumber;
}

From source file:com.jd.survey.web.settings.QuestionRowLabelController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
public String updateForm(@PathVariable("id") Long questionId, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {/*from  w w w.j  a v a  2s . com*/
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        Question question = surveySettingsService.question_findById(questionId);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(),
                user)
                && !securityService.userBelongsToDepartment(
                        question.getPage().getSurveyDefinition().getDepartment().getId(), user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        SortedSet<QuestionRowLabel> RowLabels = question.getRowLabels();
        log.info("initial set size" + RowLabels.size());
        for (int i = 1; i <= EMPTY_OPTIONS_COUNT; i++) {

            log.info("adding to set" + i);
            RowLabels.add(new QuestionRowLabel(question, (short) (question.getRowLabels().size() + i)));
        }
        question.setRowLabels(RowLabels);
        uiModel.addAttribute("question", question);
        return "settings/questionRows/update";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.tonguetied.web.KeywordValidator.java

/**
 * This validation method checks if the set of {@link Translation}s for a 
 * {@link Keyword} contains duplicate entries for new values of the 
 * business key.//from ww w.  j  av a2  s . co  m
 * 
 * @param translations the set of {@link Translation}s to validate
 * @param predicate the predicate to evaluate
 * @param errors contextual state about the validation process (never null)
 */
protected void validateDuplicates(SortedSet<Translation> translations, final TranslationPredicate predicate,
        Errors errors) {
    Collection<Translation> output;
    if (translations.size() > 1) {
        output = CollectionUtils.select(translations, predicate);
        if (output.size() > 0) {
            final String[] errorArgs = new String[] { getLanguageName(predicate.getLanguage()),
                    getCountryName(predicate.getCountry()), getBundleName(predicate.getBundle()) };
            errors.rejectValue(FIELD_TRANSLATIONS, "error.duplicate.translations", errorArgs, "default");
        }
    }
}

From source file:com.jd.survey.web.settings.QuestionColumnLabelController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
public String updateForm(@PathVariable("id") Long questionId, Principal principal,
        HttpServletRequest httpServletRequest, Model uiModel) {
    log.info("updateForm(): questionId=" + questionId);
    try {//from  ww  w  .j  a  v a 2s  .c  om
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        Question question = surveySettingsService.question_findById(questionId);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(),
                user)
                && !securityService.userBelongsToDepartment(
                        question.getPage().getSurveyDefinition().getDepartment().getId(), user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        SortedSet<QuestionColumnLabel> ColumnLabels = question.getColumnLabels();
        log.info("initial set size" + ColumnLabels.size());
        for (int i = 1; i <= EMPTY_OPTIONS_COUNT; i++) {

            log.info("adding to set" + i);
            ColumnLabels
                    .add(new QuestionColumnLabel(question, (short) (question.getColumnLabels().size() + i)));
        }
        question.setColumnLabels(ColumnLabels);
        uiModel.addAttribute("question", question);
        return "settings/questionCols/update";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.LexGrid.LexBIG.example.ScoreTerm.java

/**
 * Returns a score providing a relative comparison of the first set of words
 * against the second.//  w w w.j  ava2  s  . co  m
 * <p>
 * Currently the score is evaluated as a simple percentage based on number
 * of words in the first set that are also in the second (order
 * independent). This could be enhanced to take order into account, etc.
 * 
 * @param wordsToCompare
 * @param wordsToCompareAgainst
 * @return The score (a percentage); a higher value indicates a stronger
 *         match.
 */
protected float score(SortedSet wordsToCompare, SortedSet wordsToCompareAgainst) {
    int totalWords = wordsToCompare.size();
    int matchWords = 0;
    for (Iterator words = wordsToCompare.iterator(); words.hasNext();) {
        String word = words.next().toString();
        if (wordsToCompareAgainst.contains(word))
            matchWords++;
    }
    return ((float) matchWords / (float) totalWords) * 100;
}

From source file:com.vrem.wifianalyzer.wifi.band.WiFiChannelCountryGHZ5Test.java

@Test
public void testChannelsAustraliaCanada() throws Exception {
    final SortedSet<Integer> exclude = new TreeSet<>(Arrays.asList(120, 124, 128));
    final int expectedSize = CHANNELS_SET1.size() + CHANNELS_SET2.size() + CHANNELS_SET3.size()
            - exclude.size();
    List<String> countries = Arrays.asList("AU", "CA");
    IterableUtils.forEach(countries, new Closure<String>() {
        @Override//from w  w w.j a va  2 s  . co  m
        public void execute(String country) {
            Set<Integer> actual = fixture.findChannels(country);
            assertEquals(expectedSize, actual.size());
            assertTrue(actual.containsAll(CHANNELS_SET1));
            assertTrue(actual.containsAll(CHANNELS_SET3));
            assertFalse(actual.containsAll(exclude));
        }
    });
}