List of usage examples for java.util SortedSet add
boolean add(E e);
From source file:org.wallride.service.PageService.java
@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true) public Page createPage(PageCreateRequest request, Post.Status status, AuthorizedUser authorizedUser) { LocalDateTime now = LocalDateTime.now(); String code = request.getCode(); if (code == null) { try {// w ww. j a v a 2 s .c o m code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale()); } catch (ParseException e) { throw new ServiceException(e); } } if (!StringUtils.hasText(code)) { if (!status.equals(Post.Status.DRAFT)) { throw new EmptyCodeException(); } } if (!status.equals(Post.Status.DRAFT)) { Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage()); if (duplicate != null) { throw new DuplicateCodeException(code); } } Page page = new Page(); if (!status.equals(Post.Status.DRAFT)) { page.setCode(code); page.setDraftedCode(null); } else { page.setCode(null); page.setDraftedCode(code); } Page parent = (request.getParentId() != null) ? pageRepository.findOneByIdAndLanguage(request.getParentId(), request.getLanguage()) : null; int rgt = 0; if (parent == null) { rgt = pageRepository.findMaxRgt(); rgt++; } else { rgt = parent.getRgt(); pageRepository.unshiftRgt(rgt); pageRepository.unshiftLft(rgt); } page.setParent(parent); Media cover = null; if (request.getCoverId() != null) { cover = entityManager.getReference(Media.class, request.getCoverId()); } page.setCover(cover); page.setTitle(request.getTitle()); page.setBody(request.getBody()); page.setAuthor(entityManager.getReference(User.class, authorizedUser.getId())); LocalDateTime date = request.getDate(); if (Post.Status.PUBLISHED.equals(status)) { if (date == null) { date = now; } else if (date.isAfter(now)) { status = Post.Status.SCHEDULED; } } page.setDate(date); page.setStatus(status); page.setLanguage(request.getLanguage()); page.getCategories().clear(); SortedSet<Category> categories = new TreeSet<>(); for (long categoryId : request.getCategoryIds()) { categories.add(entityManager.getReference(Category.class, categoryId)); } page.setCategories(categories); page.getTags().clear(); Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags()); if (!CollectionUtils.isEmpty(tagNames)) { for (String tagName : tagNames) { Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage()); if (tag == null) { tag = new Tag(); tag.setName(tagName); tag.setLanguage(request.getLanguage()); page.setCreatedAt(now); page.setCreatedBy(authorizedUser.toString()); page.setUpdatedAt(now); page.setUpdatedBy(authorizedUser.toString()); tag = tagRepository.saveAndFlush(tag); } page.getTags().add(tag); } } page.getRelatedPosts().clear(); Set<Post> relatedPosts = new HashSet<>(); for (long relatedId : request.getRelatedPostIds()) { relatedPosts.add(entityManager.getReference(Post.class, relatedId)); } page.setRelatedToPosts(relatedPosts); Seo seo = new Seo(); seo.setTitle(request.getSeoTitle()); seo.setDescription(request.getSeoDescription()); seo.setKeywords(request.getSeoKeywords()); page.setSeo(seo); page.setLft(rgt); page.setRgt(rgt + 1); List<Media> medias = new ArrayList<>(); if (StringUtils.hasText(request.getBody())) { // Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix(); Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix)); Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody()); while (mediaUrlMatcher.find()) { Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1)); medias.add(media); } } page.setMedias(medias); page.setCreatedAt(now); page.setCreatedBy(authorizedUser.toString()); page.setUpdatedAt(now); page.setUpdatedBy(authorizedUser.toString()); page.getCustomFieldValues().clear(); if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) { for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) { CustomFieldValue value = new CustomFieldValue(); value.setCustomField(entityManager.getReference(CustomField.class, valueForm.getCustomFieldId())); value.setPost(page); if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) { if (!ArrayUtils.isEmpty(valueForm.getTextValues())) { value.setTextValue(String.join(",", valueForm.getTextValues())); } else { value.setTextValue(null); } } else { value.setTextValue(valueForm.getTextValue()); } value.setStringValue(valueForm.getStringValue()); value.setNumberValue(valueForm.getNumberValue()); value.setDateValue(valueForm.getDateValue()); value.setDatetimeValue(valueForm.getDatetimeValue()); if (!value.isEmpty()) { page.getCustomFieldValues().add(value); } } } return pageRepository.save(page); }
From source file:com.spotify.heroic.suggest.elasticsearch.SuggestBackendKV.java
@Override public AsyncFuture<TagValuesSuggest> tagValuesSuggest(final TagValuesSuggest.Request request) { return connection.doto((final Connection c) -> { final BoolQueryBuilder bool = boolQuery(); if (!(request.getFilter() instanceof TrueFilter)) { bool.must(filter(request.getFilter())); }//from w w w .j a v a 2 s.co m for (final String e : request.getExclude()) { bool.mustNot(termQuery(TAG_SKEY_RAW, e)); } final QueryBuilder query = bool.hasClauses() ? bool : matchAllQuery(); final SearchRequestBuilder builder = c.search(TAG_TYPE).setSize(0).setQuery(query).setTimeout(TIMEOUT); final OptionalLimit limit = request.getLimit(); final OptionalLimit groupLimit = request.getGroupLimit(); { final TermsAggregationBuilder terms = AggregationBuilders.terms("keys").field(TAG_SKEY_RAW); limit.asInteger().ifPresent(l -> terms.size(l + 1)); builder.addAggregation(terms); // make value bucket one entry larger than necessary to figure out when limiting // is applied. final TermsAggregationBuilder cardinality = AggregationBuilders.terms("values").field(TAG_SVAL_RAW); groupLimit.asInteger().ifPresent(l -> cardinality.size(l + 1)); terms.subAggregation(cardinality); } return bind(builder.execute()).directTransform((SearchResponse response) -> { final List<TagValuesSuggest.Suggestion> suggestions = new ArrayList<>(); if (response.getAggregations() == null) { return TagValuesSuggest.of(Collections.emptyList(), Boolean.FALSE); } final Terms terms = response.getAggregations().get("keys"); final List<Bucket> buckets = terms.getBuckets(); for (final Terms.Bucket bucket : limit.limitList(buckets)) { final Terms valueTerms = bucket.getAggregations().get("values"); final List<Bucket> valueBuckets = valueTerms.getBuckets(); final SortedSet<String> result = new TreeSet<>(); for (final Terms.Bucket valueBucket : valueBuckets) { result.add(valueBucket.getKeyAsString()); } final SortedSet<String> values = groupLimit.limitSortedSet(result); final boolean limited = groupLimit.isGreater(valueBuckets.size()); suggestions.add(new TagValuesSuggest.Suggestion(bucket.getKeyAsString(), values, limited)); } return TagValuesSuggest.of(ImmutableList.copyOf(suggestions), limit.isGreater(buckets.size())); }); }); }
From source file:com.revetkn.ios.analyzer.ArtworkAnalyzer.java
protected SortedSet<File> extractIncorrectlySizedRetinaImageFiles(ApplicationArtwork applicationArtwork) { SortedSet<File> incorrectlySizedRetinaImageFiles = new TreeSet<File>(); for (File retinaImageFile : applicationArtwork.getRetinaImageFiles()) { ImageMetrics imageMetrics = applicationArtwork.getAllImageFilesWithMetrics().get(retinaImageFile); if (imageMetrics.getWidth() % 2 != 0 || imageMetrics.getHeight() % 2 != 0) incorrectlySizedRetinaImageFiles.add(retinaImageFile); }/*ww w . ja v a2s .c om*/ return incorrectlySizedRetinaImageFiles; }
From source file:gov.nih.nci.caintegrator.studyQueryService.germline.ObjectQueryHandler.java
public List<String> getChromosomes() { if (CHROMOSOME_LIST == null) { Session session = null;/*from www . j a v a2 s. c o m*/ try { session = getSessionFactory().getCurrentSession(); } catch (HibernateException e) { logger.error(e); } catch (Exception e) { logger.error(e); } /* The below code is extremely slow. Hence commented out. At the same time, we do not have a class that is mapped to CHR_START_END table. So as a temp solution use direct SQL query */ /* Criteria crit = session.createCriteria(SNPAnnotation.class ); crit.setProjection(Projections.property("chromosomeName")); List<String> values = crit.list(); */ SQLQuery q = session.createSQLQuery("SELECT CHROMOSOME FROM CHR_START_END"); q.addScalar("CHROMOSOME", Hibernate.STRING); q.list(); List<String> values = q.list(); /* now sort them and place 'em in CHROMOSOME_LIST */ CHROMOSOME_LIST = new ArrayList<String>(); String[] sortedChrs = new String[22]; SortedSet<String> sexChromosomes = new TreeSet<String>(); for (int i = 0; i < values.size(); i++) { String chr = values.get(i); try { int index = Integer.parseInt(chr) - 1; sortedChrs[index] = chr; } catch (NumberFormatException e) { sexChromosomes.add(chr); // either X, Y, or MT } } for (int i = 0, j = 0; i < sortedChrs.length; i++) { String sortedChr = sortedChrs[i]; CHROMOSOME_LIST.add(j++, sortedChr); } CHROMOSOME_LIST.addAll(sexChromosomes); } return CHROMOSOME_LIST; }
From source file:com.jaspersoft.jasperserver.ws.axis2.scheduling.ReportJobBeanTraslator.java
protected SortedSet toByteSet(int[] values) { SortedSet set; if (values == null || values.length == 0) { set = null;//from w ww .j a va 2s .c om } else { set = new TreeSet(); for (int i = 0; i < values.length; i++) { set.add(new Byte((byte) values[i])); } } return set; }
From source file:com.puppycrawl.tools.checkstyle.Checker.java
/** * Processes a set of files with all FileSetChecks. * Once this is done, it is highly recommended to call for * the destroy method to close and remove the listeners. * @param files the list of files to be audited. * @return the total number of errors found * @throws CheckstyleException if error condition within Checkstyle occurs * @see #destroy()/* w w w.java2 s. c o m*/ */ public int process(List<File> files) throws CheckstyleException { // Prepare to start fireAuditStarted(); for (final FileSetCheck fsc : fileSetChecks) { fsc.beginProcessing(charset); } // Process each file for (final File file : files) { if (!CommonUtils.matchesFileExtension(file, fileExtensions)) { continue; } final String fileName = file.getAbsolutePath(); fireFileStarted(fileName); final SortedSet<LocalizedMessage> fileMessages = Sets.newTreeSet(); try { final FileText theText = new FileText(file.getAbsoluteFile(), charset); for (final FileSetCheck fsc : fileSetChecks) { fileMessages.addAll(fsc.process(file, theText)); } } catch (final IOException ioe) { LOG.debug("IOException occurred.", ioe); fileMessages.add(new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "general.exception", new String[] { ioe.getMessage() }, null, getClass(), null)); } fireErrors(fileName, fileMessages); fireFileFinished(fileName); } // Finish up for (final FileSetCheck fsc : fileSetChecks) { // It may also log!!! fsc.finishProcessing(); } for (final FileSetCheck fsc : fileSetChecks) { // It may also log!!! fsc.destroy(); } final int errorCount = counter.getCount(); fireAuditFinished(); return errorCount; }
From source file:org.wallride.service.PageService.java
@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true) public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) { postRepository.lock(request.getId()); Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage()); LocalDateTime now = LocalDateTime.now(); String code = request.getCode(); if (code == null) { try {//w w w . j av a2 s . c o m code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale()); } catch (ParseException e) { throw new ServiceException(e); } } if (!StringUtils.hasText(code)) { if (!page.getStatus().equals(Post.Status.DRAFT)) { throw new EmptyCodeException(); } } if (!page.getStatus().equals(Post.Status.DRAFT)) { Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage()); if (duplicate != null && !duplicate.equals(page)) { throw new DuplicateCodeException(code); } } if (!page.getStatus().equals(Post.Status.DRAFT)) { page.setCode(code); page.setDraftedCode(null); } else { page.setCode(null); page.setDraftedCode(code); } Page parent = (request.getParentId() != null) ? entityManager.getReference(Page.class, request.getParentId()) : null; if (!(page.getParent() == null && parent == null) && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) { pageRepository.shiftLftRgt(page.getLft(), page.getRgt()); pageRepository.shiftRgt(page.getRgt()); pageRepository.shiftLft(page.getRgt()); int rgt = 0; if (parent == null) { rgt = pageRepository.findMaxRgt(); rgt++; } else { rgt = parent.getRgt(); pageRepository.unshiftRgt(rgt); pageRepository.unshiftLft(rgt); } page.setLft(rgt); page.setRgt(rgt + 1); } page.setParent(parent); Media cover = null; if (request.getCoverId() != null) { cover = entityManager.getReference(Media.class, request.getCoverId()); } page.setCover(cover); page.setTitle(request.getTitle()); page.setBody(request.getBody()); // User author = null; // if (request.getAuthorId() != null) { // author = entityManager.getReference(User.class, request.getAuthorId()); // } // page.setAuthor(author); LocalDateTime date = request.getDate(); if (Post.Status.PUBLISHED.equals(page.getStatus())) { if (date == null) { date = now.truncatedTo(ChronoUnit.HOURS); } else if (date.isAfter(now)) { page.setStatus(Post.Status.SCHEDULED); } } page.setDate(date); page.setLanguage(request.getLanguage()); page.getCategories().clear(); SortedSet<Category> categories = new TreeSet<>(); for (long categoryId : request.getCategoryIds()) { categories.add(entityManager.getReference(Category.class, categoryId)); } page.setCategories(categories); page.getTags().clear(); Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags()); if (!CollectionUtils.isEmpty(tagNames)) { for (String tagName : tagNames) { Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage()); if (tag == null) { tag = new Tag(); tag.setName(tagName); tag.setLanguage(request.getLanguage()); page.setCreatedAt(now); page.setCreatedBy(authorizedUser.toString()); page.setUpdatedAt(now); page.setUpdatedBy(authorizedUser.toString()); tag = tagRepository.saveAndFlush(tag); } page.getTags().add(tag); } } page.getRelatedPosts().clear(); Set<Post> relatedPosts = new HashSet<>(); for (long relatedId : request.getRelatedPostIds()) { relatedPosts.add(entityManager.getReference(Post.class, relatedId)); } page.setRelatedToPosts(relatedPosts); Seo seo = new Seo(); seo.setTitle(request.getSeoTitle()); seo.setDescription(request.getSeoDescription()); seo.setKeywords(request.getSeoKeywords()); page.setSeo(seo); List<Media> medias = new ArrayList<>(); if (StringUtils.hasText(request.getBody())) { // Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix(); Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix)); Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody()); while (mediaUrlMatcher.find()) { Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1)); medias.add(media); } } page.setMedias(medias); page.setUpdatedAt(now); page.setUpdatedBy(authorizedUser.toString()); SortedSet<CustomFieldValue> fieldValues = new TreeSet<>(); Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>(); for (CustomFieldValue value : page.getCustomFieldValues()) { valueMap.put(value.getCustomField(), value); } page.getCustomFieldValues().clear(); if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) { for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) { CustomField customField = entityManager.getReference(CustomField.class, valueForm.getCustomFieldId()); CustomFieldValue value = valueMap.get(customField); if (value == null) { value = new CustomFieldValue(); } value.setCustomField(customField); value.setPost(page); if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) { if (!ArrayUtils.isEmpty(valueForm.getTextValues())) { value.setTextValue(String.join(",", valueForm.getTextValues())); } else { value.setTextValue(null); } } else { value.setTextValue(valueForm.getTextValue()); } value.setStringValue(valueForm.getStringValue()); value.setNumberValue(valueForm.getNumberValue()); value.setDateValue(valueForm.getDateValue()); value.setDatetimeValue(valueForm.getDatetimeValue()); if (!value.isEmpty()) { fieldValues.add(value); } } } page.setCustomFieldValues(fieldValues); return pageRepository.save(page); }
From source file:cz.muni.fi.mir.controllers.StatisticsController.java
private ModelMap prepareStatisticsModelMap(Statistics stat, Map<Long, DateTime> dropdownMap) { Map<Pair<Configuration, Revision>, SortedMap<String, Integer>> map = new HashMap<>(); Map<String, Integer> graph = new HashMap<>(); SortedSet<String> columns = new TreeSet<>(); for (StatisticsHolder sh : stat.getStatisticsHolders()) { Pair<Configuration, Revision> key = new Pair<>(sh.getConfiguration(), sh.getRevision()); SortedMap<String, Integer> keyValues = null; if (map.containsKey(key)) { keyValues = map.get(key);//from w w w . j ava 2 s. c om addOrIncrement(sh.getAnnotation(), sh.getCount(), keyValues); addOrIncrement(sh.getAnnotation(), sh.getCount(), graph); } else { keyValues = new TreeMap<>(); keyValues.put(sh.getAnnotation(), sh.getCount()); addOrIncrement(sh.getAnnotation(), sh.getCount(), graph); } map.put(key, keyValues); columns.add(sh.getAnnotation()); } //postprocessing to fill empty columns for (Pair<Configuration, Revision> pair : map.keySet()) { SortedMap<String, Integer> values = map.get(pair); for (String s : columns) { if (!values.containsKey(s)) { values.put(s, 0); } } map.put(pair, values); } ModelMap mm = new ModelMap(); mm.addAttribute("statisticsMap", map); mm.addAttribute("statisticsColumns", columns); mm.addAttribute("statisticsDate", stat.getCalculationDate()); mm.addAttribute("formulaCount", stat.getTotalFormulas()); mm.addAttribute("coCount", stat.getTotalCanonicOutputs()); mm.addAttribute("graph", graph); mm.addAttribute("statisticsDropdown", dropdownMap); return mm; }
From source file:net.sourceforge.fenixedu.domain.mobility.outbound.OutboundMobilityCandidacyContestGroup.java
private void collectGradesForGroup(final SortedSet<OutboundMobilityCandidacySubmissionGrade> grades, final OutboundMobilityCandidacyPeriod period) { for (final OutboundMobilityCandidacySubmissionGrade submissionGrade : getOutboundMobilityCandidacySubmissionGradeSet()) { final OutboundMobilityCandidacySubmission submission = submissionGrade .getOutboundMobilityCandidacySubmission(); if (submission.getOutboundMobilityCandidacyPeriod() == period) { grades.add(submissionGrade); }//w w w . j a v a2 s.c o m } }
From source file:net.sourceforge.fenixedu.presentationTier.backBeans.person.OrganizationalStructureBackingBean.java
public SortedSet<PersonFunction> getValidPersonFunction(ExecutionYear iExecutionYear, Function function) { SortedSet<PersonFunction> personFunctions = new TreeSet<PersonFunction>( PersonFunction.COMPARATOR_BY_PERSON_NAME); for (PersonFunction personFunction : function.getPersonFunctions()) { if (personFunction.belongsToPeriod(iExecutionYear.getBeginDateYearMonthDay(), iExecutionYear.getEndDateYearMonthDay())) { personFunctions.add(personFunction); }/* w w w . j a v a 2s .c om*/ } return personFunctions; }