target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void shouldCreateSearchResultItem() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getNewznabAttributes().add(new NewznabAttribute("password", "0")); rssItem.getNewznabAttributes().add(new NewznabAttribute("group", "group")); rssItem.getNewznabAttributes().add(new NewznabAttribute("poster", "poster")); rssItem.getNewznabAttributes().add(new NewznabAttribute("files", "10")); rssItem.getNewznabAttributes().add(new NewznabAttribute("grabs", "20")); rssItem.getNewznabAttributes().add(new NewznabAttribute("comments", "30")); rssItem.getNewznabAttributes().add(new NewznabAttribute("usenetdate", new JaxbPubdateAdapter().marshal(Instant.ofEpochSecond(6666666)))); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5000")); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5050")); SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getLink(), is("http: assertThat(item.getIndexerGuid(), is("123")); assertThat(item.getSize(), is(456L)); assertThat(item.getDescription(), is("description")); assertThat(item.getPubDate(), is(Instant.ofEpochSecond(5555555))); assertThat(item.getCommentsLink(), is("http: assertThat(item.getDetails(), is("http: assertThat(item.isAgePrecise(), is(true)); assertThat(item.getUsenetDate().get(), is(Instant.ofEpochSecond(6666666))); assertThat(item.getDownloadType(), is(DownloadType.NZB)); assertThat(item.isPassworded(), is(false)); assertThat(item.getGroup().get(), is("group")); assertThat(item.getPoster().get(), is("poster")); assertThat(item.getFiles(), is(10)); assertThat(item.getGrabs(), is(20)); assertThat(item.getCommentsCount(), is(30)); verify(categoryProviderMock, times(1)).fromResultNewznabCategories(Arrays.asList(5000, 5050)); rssItem.setRssGuid(new NewznabXmlGuid("123", false)); rssItem.getNewznabAttributes().clear(); rssItem.getNewznabAttributes().add(new NewznabAttribute("password", "1")); rssItem.getNewznabAttributes().add(new NewznabAttribute("nfo", "1")); item = testee.createSearchResultItem(rssItem); assertThat(item.getIndexerGuid(), is("123")); assertThat(item.isPassworded(), is(true)); assertThat(item.getHasNfo(), is(HasNfo.YES)); } | protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } @Override NfoResult getNfo(String guid); } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } @Override NfoResult getNfo(String guid); } |
@Test public void shouldUseIndexersCategoryMappingToBuildOriginalCategoryName() throws Exception { testee.config.getCategoryMapping().setCategories(Arrays.asList(new MainCategory(5000, "TV", Arrays.asList(new SubCategory(5040, "HD"))))); NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5040")); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5000")); SearchResultItem searchResultItem = new SearchResultItem(); Category category = new Category(); category.setSearchType(SearchType.TVSEARCH); searchResultItem.setCategory(category); testee.parseAttributes(rssItem, searchResultItem); assertThat(searchResultItem.getOriginalCategory(), is("TV HD")); rssItem.getNewznabAttributes().clear(); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "1234")); testee.parseAttributes(rssItem, searchResultItem); assertThat(searchResultItem.getOriginalCategory(), is("N/A")); } | protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } | Newznab extends Indexer<Xml> { protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } } | Newznab extends Indexer<Xml> { protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } } | Newznab extends Indexer<Xml> { protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } @Override NfoResult getNfo(String guid); } | Newznab extends Indexer<Xml> { protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } @Override NfoResult getNfo(String guid); } |
@Test public void shouldGetDetailsLinkFromRssGuidIfPermalink() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setRssGuid(new NewznabXmlGuid("detailsLink", true)); rssItem.setComments("http: SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getDetails(), is("detailsLink")); } | protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } @Override NfoResult getNfo(String guid); } | Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } @Override NfoResult getNfo(String guid); } |
@Test public void shouldIgnoreHitAndDownloadLimitIfNoneAreSet() { indexerConfigMock.setHitLimit(null); indexerConfigMock.setDownloadLimit(null); testee.checkIndexerHitLimit(indexer); verify(nzbDownloadRepository, never()).findBySearchResultIndexerOrderByTimeDesc(any(), any()); verify(indexerApiAccessRepository, never()).findByIndexerOrderByTimeDesc(any(), any()); } | protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } | IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } } | IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } } | IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); } | IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; } |
@Test(expected = MissingConfigException.class) public void missingUser() throws ParseException, MissingConfigException { String[] args = new String[] { "-pass", "password", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); } | public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } | PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } } | PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); } | PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); } | PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); static final String KEY_USER; static final String KEY_PASSWORD; static final String KEY_SFTP_SERVER; static final String KEY_LOCAL_DIRECTORY; static final String KEY_PORT; final static Options OPTIONS; } |
@Test public void testNonEmptyIncludeFieldConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setIncludeFieldString("name"); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getFieldsObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", 1, obj.get("body.name")); assertEquals("Should match", 1, obj.get("type")); assertEquals("Should match", 1, obj.get("metaData")); assertNull("Should be null", obj.get("body")); } | public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } | MongoQueryConverter { public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } } | MongoQueryConverter { public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } MongoQueryConverter(); } | MongoQueryConverter { public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } MongoQueryConverter(); Query convert(String entityName, NeutralQuery neutralQuery); Query convert(String entityName, NeutralQuery neutralQuery, boolean allFields); List<Criteria> convertToCriteria(String entityName, NeutralQuery neutralQuery, NeutralSchema entitySchema); } | MongoQueryConverter { public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } MongoQueryConverter(); Query convert(String entityName, NeutralQuery neutralQuery); Query convert(String entityName, NeutralQuery neutralQuery, boolean allFields); List<Criteria> convertToCriteria(String entityName, NeutralQuery neutralQuery, NeutralSchema entitySchema); } |
@Test(expected = EmptyStackException.class) public void testEmptyHolderPop() { CurrentTenantHolder.pop(); } | public static String pop() { return getCurrentStack().pop(); } | CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } } | CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } } | CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); } | CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); } |
@Test(expected = EmptyStackException.class) public void testEmptyHolderPeek() { CurrentTenantHolder.getCurrentTenant(); } | public static String getCurrentTenant() { return getCurrentStack().peek(); } | CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } } | CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } } | CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); } | CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); } |
@Test public void testIgnoredOnSystemCall() { TenantContext.setIsSystemCall(true); deltaJournal.journal("test", "userSession", false); verify(template, never()).upsert(any(Query.class), any(Update.class), anyString()); TenantContext.setIsSystemCall(false); } | public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } | DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } } | DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } } | DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); } | DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; } |
@Test public void testJournalCollapsedSubDocs() throws DecoderException { String assessment1id = "1234567890123456789012345678901234567890"; String assessment2id = "1234567890123456789012345678901234567892"; deltaJournal.journal( Arrays.asList(assessment1id + "_id1234567890123456789012345678901234567891_id", assessment1id + "_id1234567890123456789012345678901234567892_id", assessment2id + "_id1234567890123456789012345678901234567891_id"), "assessmentItem", false); Query q1 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment1id.toCharArray()))); Query q2 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment2id.toCharArray()))); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); return o.get("c").equals("assessment"); } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'assessment'"); } }; verify(template).upsert(eq(q1), argThat(updateMatcher), eq("deltas")); verify(template).upsert(eq(q2), argThat(updateMatcher), eq("deltas")); } | public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } | DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } } | DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } } | DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); } | DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; } |
@Test public void testJournalPurge() { final long time = new Date().getTime(); deltaJournal.journalPurge(time); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); if (o.get("c").equals("purge") && o.get("t").equals(time)) { return true; } return false; } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'purge' and 't' set to time of purge"); } }; verify(template, Mockito.times(1)).upsert(Mockito.any(Query.class), argThat(updateMatcher), Mockito.eq("deltas")); } | public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } | DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } } | DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } } | DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); } | DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; } |
@Test public void testGetByteId() throws DecoderException { String id = "1234567890123456789012345678901234567890"; String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(id + "_id").get(0))); assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(0))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(1))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(1))); assertEquals(extraid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(2))); } | public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } | DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } } | DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } } | DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); } | DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; } |
@Test public void testGetEntityId() throws DecoderException { String id = "1234567890123456789012345678901234567890"; String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; Map<String, Object> delta = new HashMap<String, Object>(); delta.put("_id", Hex.decodeHex(id.toCharArray())); assertEquals(id + "_id", DeltaJournal.getEntityId(delta)); delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()))); assertEquals(superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta)); delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()), Hex.decodeHex(extraid.toCharArray()))); assertEquals(extraid + "_id" + superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta)); } | public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } | DeltaJournal implements InitializingBean { public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } } | DeltaJournal implements InitializingBean { public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } } | DeltaJournal implements InitializingBean { public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); } | DeltaJournal implements InitializingBean { public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; } |
@Test public void testSingleInsert() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); assertTrue(underTest.subDoc("studentSectionAssociation").create(entity)); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION1) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((Map<String, Map<String, Object>>) studentSectionsToPush[0]).get("body").get("beginDate") .equals(BEGINDATE) && ssaIds.get(0).equals("studentSectionAssociation"); } }), eq(false), eq(false), eq(WriteConcern.SAFE)); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testMultipleInsert() { Entity ssa1 = new MongoEntity("studentSectionAssociation", studentSectionAssociation); Entity ssa2 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>( studentSectionAssociation)); ssa2.getBody().put("studentId", STUDENT2); Entity ssa3 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>( studentSectionAssociation)); ssa3.getBody().put("sectionId", SECTION2); assertTrue(underTest.subDoc("studentSectionAssociation").insert(Arrays.asList(ssa1, ssa2, ssa3))); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION2) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((Map<String, Map<String, Object>>) studentSectionsToPush[0]).get("body").get("beginDate") .equals(BEGINDATE) && ssaIds.get(0).equals("studentSectionAssociation"); } }), eq(false), eq(false), eq(WriteConcern.SAFE)); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION1) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid", "subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); return studentSectionsToPush.length == 2; } }), eq(false), eq(false), eq(WriteConcern.SAFE)); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testNewLineCharacter() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithNewLine.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/Student.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); } | public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } |
@Test public void testMakeSubDocQuery() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); DBObject parentQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, true); DBObject childQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, false); assertEquals("someValue", parentQuery.get("studentSectionAssociation.someProperty")); assertEquals("parent_id", parentQuery.get("_id")); assertEquals("parent_idchild", parentQuery.get("studentSectionAssociation._id")); assertEquals("someValue", childQuery.get("studentSectionAssociation.someProperty")); assertEquals("parent_idchild", childQuery.get("studentSectionAssociation._id")); assertNotNull(childQuery.get("_id")); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testSearchByParentId() { Query originalQuery = new Query(Criteria.where("body.sectionId").in("parentId1", "parentId2")); DBObject parentQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, true); assertEquals(new BasicDBObject("$in", Arrays.asList("parentId1", "parentId2")), parentQuery.get("_id")); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testdoUpdate() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); Update update = new Update(); update.set("someProperty", "someNewValue"); boolean result = underTest.subDoc("studentSectionAssociation").doUpdate(originalQuery, update); assertTrue(result); originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("nonExistProperty").is("someValue")); update = new Update(); update.set("nonExistProperty", "someNewValue"); result = underTest.subDoc("studentSectionAssociation").doUpdate(originalQuery, update); assertFalse(result); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testFindById() { Entity resultEntity = underTest.subDoc("studentSectionAssociation").findById("parent_idchild"); assertNotNull(resultEntity); assertEquals("parent_idchild", resultEntity.getEntityId()); assertEquals("someValue", resultEntity.getBody().get("someProperty")); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testFindAll() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")) .skip(0).limit(1); List<Entity> entityResults = underTest.subDoc("studentSectionAssociation").findAll(originalQuery); assertNotNull(entityResults); assertEquals(1, entityResults.size()); assertEquals("parent_idchild", entityResults.get(0).getEntityId()); assertEquals("someValue", entityResults.get(0).getBody().get("someProperty")); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testDelete() { Entity entity = underTest.subDoc("studentSectionAssociation").findById("parent_idchild"); boolean result = underTest.subDoc("studentSectionAssociation").delete(entity); assertTrue(result); entity = underTest.subDoc("studentSectionAssociation").findById("nonExistId"); result = underTest.subDoc("studentSectionAssociation").delete(entity); assertFalse(result); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testCount() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); long count = underTest.subDoc("studentSectionAssociation").count(originalQuery); assertEquals(1L, count); originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("nonExistProperty").is("someValue")); count = underTest.subDoc("studentSectionAssociation").count(originalQuery); assertEquals(0L, count); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testExists() { boolean exists = underTest.subDoc("studentSectionAssociation").exists("parent_idchild"); assertTrue(exists); boolean nonExists = underTest.subDoc("studentSectionAssociation").exists("nonExistId"); assertFalse(nonExists); } | public Location subDoc(String docType) { return locations.get(docType); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } | SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); } |
@Test public void testCreate() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); entity.getMetaData().put("tenantId", "TEST"); assertTrue(denormalizer.denormalization("studentSectionAssociation").create(entity)); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT1).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); } | public Denormalization denormalization(String docType) { return denormalizations.get(docType); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } |
@Test public void testInsert() { Entity entity1 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>(studentSectionAssociation)); entity1.getBody().put("sectionId", SECTION2); entity1.getBody().put("endDate", ENDDATE2); entity1.getMetaData().put("tenantId", "TEST"); Entity entity2 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>(studentSectionAssociation)); entity2.getBody().put("studentId", STUDENT2); entity2.getMetaData().put("tenantId", "TEST"); assertTrue(denormalizer.denormalization("studentSectionAssociation").insert(Arrays.asList(entity1, entity2))); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT2).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT1).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); } | public Denormalization denormalization(String docType) { return denormalizations.get(docType); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } |
@Test public void testUnicodeCharacter() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithUnicode.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/StudentWithUnicode.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); } | public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } |
@Test public void testDelete() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); boolean result = denormalizer.denormalization("studentSectionAssociation").delete(entity, entity.getEntityId()); assertTrue(result); result = denormalizer.denormalization("studentSectionAssociation").delete(null, SSAID); assertTrue(result); result = denormalizer.denormalization("studentSectionAssociation").delete(null, "invalidID"); assertFalse(result); } | public Denormalization denormalization(String docType) { return denormalizations.get(docType); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } | Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); } |
@Test public void upconvertNoAssessmentShouldRemoveInvalidReference() { List<Entity> old = Arrays.asList(createUpConvertEntity()); assertNotNull(old.get(0).getEmbeddedData().get("studentAssessmentItem")); Iterable<Entity> entity = saConverter.subdocToBodyField(old); assertNull(entity.iterator().next().getEmbeddedData().get("studentAssessmentItem")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testBodyFieldToSubdoc() { List<Entity> entities = Arrays.asList(createDownConvertEntity()); assertNotNull("studentAssessment body should have studentAssessmentItem", entities.get(0).getBody().get("studentAssessmentItems")); assertNull("studentAssessmentItem should not be outside the studentAssessment body", entities.get(0) .getEmbeddedData().get("studentAssessmentItem")); saConverter.bodyFieldToSubdoc(entities); assertNull("studentAssessment body should not have studentAssessmentItem", entities.get(0).getBody().get("studentAssessmentItems")); assertNotNull("studentAssessmentItem should be moved outside body", entities.get(0).getEmbeddedData().get("studentAssessmentItem")); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@SuppressWarnings("unchecked") @Test public void testSubdocDid() { List<Entity> entities = Arrays.asList(createDownConvertEntity()); assertNull( "studentAssessmentItem should not have id before transformation", ((List<Map<String, Object>>) (entities.get(0).getBody().get("studentAssessmentItems"))).get(0).get( "_id")); saConverter.bodyFieldToSubdoc(entities); assertFalse("subdoc id should be generated", entities.get(0).getEmbeddedData().get("studentAssessmentItem") .get(0).getEntityId().isEmpty()); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@SuppressWarnings("unchecked") @Test public void testUpConvertShouldCollapseAssessmentItem() { Entity saEntity = createUpConvertEntity(); saEntity.getBody().put("assessmentId", "assessmentId"); saEntity.getBody().put("studentId", "studentId"); List<Entity> old = Arrays.asList(saEntity); assertNull("studentAssessmentItem should not be in body", old.get(0).getBody() .get("studentAssessmentItem")); Entity assessment = createAssessment(); when(repo.getTemplate()).thenReturn(template); when(template.findById("assessmentId", Entity.class, EntityNames.ASSESSMENT)).thenReturn(assessment); Iterable<Entity> entities = saConverter.subdocToBodyField(old); assertNotNull("studentAssessmentItem should be moved into body", entities.iterator().next().getBody().get("studentAssessmentItems")); assertNotNull( "assessmentItem should be collapsed into the studentAssessmentItem", ((List<Map<String, Object>>) (entities.iterator().next().getBody().get("studentAssessmentItems"))).get(0).get( "assessmentItem")); Map<String, Object> assessmentItemBody = (Map<String, Object>) ((List<Map<String, Object>>) (entities.iterator().next() .getBody().get("studentAssessmentItems"))).get(0).get("assessmentItem"); assertEquals("collapsed assessmentItem should have assessmentId field is assessmentId", "assessmentId", assessmentItemBody.get("assessmentId")); assertEquals("collapsed assessmentItem should have identificationCode field is code1", "code1", assessmentItemBody.get("identificationCode")); assertEquals("collapsed assessmentItem should have itemCategory is Matching", "Matching", assessmentItemBody.get("itemCategory")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testIsContainerDocument() { when(mockHolder.isContainerDocument(ATTENDANCE)).thenReturn(true); boolean actual = testAccessor.isContainerDocument(ATTENDANCE); assertEquals(true, actual); } | public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } | ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } } | ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); } | ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } | ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } |
@Test public void isContainerSubDoc() { final ContainerDocument cDoc2 = createContainerDocGrade(); when(mockHolder.isContainerDocument(ATTENDANCE)).thenReturn(true); when(mockHolder.isContainerDocument(GRADE)).thenReturn(true); when(mockHolder.getContainerDocument(GRADE)).thenReturn(cDoc2); assertFalse(testAccessor.isContainerSubdoc(ATTENDANCE)); assertTrue(testAccessor.isContainerSubdoc(GRADE)); } | public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } | ContainerDocumentAccessor { public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } } | ContainerDocumentAccessor { public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); } | ContainerDocumentAccessor { public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } | ContainerDocumentAccessor { public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } |
@Test public void testInsert() { DBObject query = Mockito.mock(DBObject.class); DBObject docToPersist = ContainerDocumentHelper.buildDocumentToPersist(mockHolder, entity, generatorStrategy, naturalKeyExtractor); when(query.get("_id")).thenReturn(ID); when(mockHolder.getContainerDocument(ATTENDANCE)).thenReturn(createContainerDocAttendance()); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.update(Mockito.any(DBObject.class), Mockito.eq(docToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE))).thenReturn(writeResult); String result = testAccessor.insertContainerDoc(query, entity); assertTrue(result.equals(ID)); assertFalse("Wrong result returned by insert", result.equals("")); Mockito.verify(mockCollection, Mockito.times(1)).update(Mockito.any(DBObject.class), Mockito.eq(docToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE)); } | public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } | ContainerDocumentAccessor { public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } } | ContainerDocumentAccessor { public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); } | ContainerDocumentAccessor { public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } | ContainerDocumentAccessor { public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } |
@Test public void testDeleteEntity() { ContainerDocumentAccessor cda = Mockito.spy(testAccessor); Map<String, Object> updateDocCriteria = new HashMap<String, Object>(); updateDocCriteria.put("event", "Tardy"); DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get(); DBObject resultingAttendanceEvent = createResultAttendance("10-04-2013"); NeutralSchema attendanceSchema = createMockAttendanceSchema(); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject),Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent); when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema); boolean result = cda.deleteContainerNonSubDocs(entity); Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false)); assertTrue(result); } | @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } |
@Test public void testDeleteEntityAndContainerDoc() { ContainerDocumentAccessor cda = Mockito.spy(testAccessor); Map<String, Object> updateDocCriteria = new HashMap<String, Object>(); updateDocCriteria.put("event", "Tardy"); DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get(); DBObject resultingAttendanceEvent = createResultAttendance(null); NeutralSchema attendanceSchema = createMockAttendanceSchema(); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent); when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema); boolean result = cda.deleteContainerNonSubDocs(entity); Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false)); Mockito.verify(mongoTemplate, Mockito.times(1)).findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE)); assertTrue(result); } | @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } | ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); } |
@Test public void testCDATA() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithCDATA.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/StudentWithCDATA.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); } | public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } | EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); } |
@Test public void upconvertShouldRemoveAPD_references() { Entity oldEntity = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void upconvertNoEmbeddedSubdocShouldRemainUnchanged() { List<Entity> old = Arrays.asList(createDownConvertEntity()); Entity clone = createDownConvertEntity(); Iterable<Entity> entity = assessmentConverter.subdocToBodyField(old); assertEquals(clone.getBody(), entity.iterator().next().getBody()); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void upconvertShouldConstructAssessmentFamilyHierarchy() { Entity oldEntity = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNull(entity.getBody().get(ASSESSMENT_FAMILY_REFERENCE)); assertEquals("A.B.C", entity.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void downconvertShouldDeleteAssessmentFamilyHierarchy() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNull(entity.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void downconvertShouldDeleteAssessmentFamilyHierarchyExistingAssessment() { Entity existingAssessment = createDownConvertEntity(); existingAssessment.getBody().put(ASSESSMENT_FAMILY_REFERENCE, assessmentFamilyA.getEntityId()); when(template.findById(existingAssessment.getEntityId(), Entity.class, EntityNames.ASSESSMENT)).thenReturn(existingAssessment); Entity updatedAssessment = createDownConvertEntity(); updatedAssessment.getBody().put("assessmentTitle", "A_new_title"); assessmentConverter.bodyFieldToSubdoc(updatedAssessment); assertNull(updatedAssessment.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); assertEquals(existingAssessment.getBody().get(ASSESSMENT_FAMILY_REFERENCE), updatedAssessment.getBody().get(ASSESSMENT_FAMILY_REFERENCE)); assertEquals("A_new_title", updatedAssessment.getBody().get("assessmentTitle")); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@SuppressWarnings("unchecked") @Test public void upconvertEmbeddedSubdocShouldMoveInsideBody() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldEntity = createUpConvertEntity(); Entity clone = createUpConvertEntity(); assertNull(oldEntity.getBody().get("assessmentItem")); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNotNull(entity.getBody().get("assessmentItem")); assertEquals(clone.getEmbeddedData().get("assessmentItem").get(0).getBody().get("abc"), ((List<Map<String, Object>>) (entity.getBody().get("assessmentItem"))).get(0).get("abc")); assertEquals("somevalue1", PropertyUtils.getProperty(entity, "body.assessmentItem.[0].abc")); assertEquals("somevalue2", PropertyUtils.getProperty(entity, "body.assessmentItem.[1].abc")); assertNull(entity.getEmbeddedData().get("assessmentItem")); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); assertNotNull(entity.getBody().get("assessmentPeriodDescriptor")); assertEquals(((Map<String, Object>)(entity.getBody().get("assessmentPeriodDescriptor"))).get("codeValue"), assessmentPeriodDescriptor.getBody().get("codeValue")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void downconvertBodyHasNoSubdocShouldNotChange() throws NoNaturalKeysDefinedException { List<Entity> entity = Arrays.asList(createUpConvertEntity()); Entity clone = createUpConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertEquals(clone.getBody(), entity.get(0).getBody()); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void downconvertBodyToSubdoc() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNull(entity.getBody().get("assessmentItem")); assertNotNull(entity.getEmbeddedData().get("assessmentItem")); assertNull(entity.getBody().get("assessmentPeriodDescriptor")); assertNotNull(entity.getBody().get("assessmentPeriodDescriptorId")); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void bodyToSubdocGenerateId() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNotNull("should move assessmentItem from in body to out body", entity.getEmbeddedData().get("assessmentItem")); assertEquals("should have one assessmentItem in subdoc field", 1, entity.getEmbeddedData() .get("assessmentItem").size()); String id = entity.getEmbeddedData().get("assessmentItem").get(0).getEntityId(); assertNotNull("should generate id for subdoc entity", id); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void invalidApdIdShouldBeFilteredOutInUp() { when(template.findById("mydescriptorid", Entity.class, EntityNames.ASSESSMENT_PERIOD_DESCRIPTOR)).thenReturn(null); Entity old = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(Arrays.asList(old)).iterator().next(); assertNull(entity.getBody().get("assessmentPeriodDescriptor")); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testCreateSimpleWorkNote() { FileEntryWorkNote workNote = new FileEntryWorkNote("batchJobId", null, false); Assert.assertEquals("batchJobId", workNote.getBatchJobId()); Assert.assertEquals(null, workNote.getFileEntry()); } | public IngestionFileEntry getFileEntry() { return fileEntry; } | FileEntryWorkNote extends WorkNote implements Serializable { public IngestionFileEntry getFileEntry() { return fileEntry; } } | FileEntryWorkNote extends WorkNote implements Serializable { public IngestionFileEntry getFileEntry() { return fileEntry; } FileEntryWorkNote(String batchJobId, IngestionFileEntry fileEntry, boolean hasErrors); } | FileEntryWorkNote extends WorkNote implements Serializable { public IngestionFileEntry getFileEntry() { return fileEntry; } FileEntryWorkNote(String batchJobId, IngestionFileEntry fileEntry, boolean hasErrors); IngestionFileEntry getFileEntry(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } | FileEntryWorkNote extends WorkNote implements Serializable { public IngestionFileEntry getFileEntry() { return fileEntry; } FileEntryWorkNote(String batchJobId, IngestionFileEntry fileEntry, boolean hasErrors); IngestionFileEntry getFileEntry(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test @SuppressWarnings("unchecked") public void testHierachyInObjectiveAssessmentsToAPI() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldAssessment = createHierarchicalUpConvertEntity(); Entity assessment = assessmentConverter.subdocToBodyField(oldAssessment); List<Map<String, Object>> oas = (List<Map<String, Object>>) PropertyUtils.getProperty(assessment, "body.objectiveAssessment"); assertEquals(1, oas.size()); assertEquals("ParentOA", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].title")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].title")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[1].title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].objectiveAssessments.[0].title")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testHierachyInObjectiveAssessmentsToDAL() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity assessment = createHierarchicalDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(assessment); assertEquals("ParentOA", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.title")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.subObjectiveAssessment.[0]")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.subObjectiveAssessment.[1]")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[1].body.title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[1].body.subObjectiveAssessment.[0]")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[2].body.title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[0].body.title")); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testAssessmentsWithAIsInOAsToAPI() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldAssessment = createHierarchicalUpConvertEntity(); Entity assessment = assessmentConverter.subdocToBodyField(oldAssessment); assertEquals("somevalue1", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0].abc")); assertEquals("somevalue2", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[1].assessmentItem.[0].abc")); assertEquals("somevalue3", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[1].abc")); assertEquals("somevalue4", PropertyUtils.getProperty(assessment, "body.assessmentItem.[0].abc")); assertNull(PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0]._id")); assertNull(PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0].assessmentId")); } | @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testAssessmentsWithAIsInOAsToDAL() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity assessment = createHierarchicalDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(assessment); assertEquals("1", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[0].body.a")); assertEquals("somevalue1", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[1].body.abc")); assertEquals("somevalue2", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[2].body.abc")); assertEquals("somevalue3", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[3].body.abc")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[0].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[1].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[2].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[3].entityId")); } | @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } | AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); } |
@Test public void testEntityConvert() throws NoNaturalKeysDefinedException { Entity e = Mockito.mock(Entity.class); HashMap<String, Object> body = new HashMap<String, Object>(); body.put("field1", "field1"); body.put("field2", "field2"); HashMap<String, Object> meta = new HashMap<String, Object>(); meta.put("meta1", "field1"); meta.put("meta2", "field2"); NaturalKeyDescriptor desc = new NaturalKeyDescriptor(); Mockito.when(e.getType()).thenReturn("collection"); Mockito.when(e.getBody()).thenReturn(body); Mockito.when(e.getMetaData()).thenReturn(meta); Mockito.when(naturalKeyExtractor.getNaturalKeyDescriptor(Mockito.any(Entity.class))).thenReturn(desc); Mockito.when(uuidGeneratorStrategy.generateId(desc)).thenReturn("uid"); DBObject d = converter.convert(e); Assert.assertNotNull("DBObject should not be null", d); assertSame(body, (Map<?, ?>) d.get("body")); assertSame(meta, (Map<?, ?>) d.get("metaData")); Assert.assertEquals(1, encryptCalls.size()); Assert.assertEquals(2, encryptCalls.get(0).length); Assert.assertEquals(e.getType(), encryptCalls.get(0)[0]); Assert.assertEquals(e.getBody(), encryptCalls.get(0)[1]); } | @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } |
@Test public void testMockMongoEntityConvert() { MongoEntity e = Mockito.mock(MongoEntity.class); DBObject result = Mockito.mock(DBObject.class); Mockito.when(e.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor)).thenReturn(result); DBObject d = converter.convert(e); Assert.assertNotNull(d); Assert.assertEquals(result, d); Mockito.verify(e, Mockito.times(1)).encrypt(encryptor); Mockito.verify(e, Mockito.times(1)).toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } | @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } |
@Test public void testMongoEntityConvert() { HashMap<String, Object> body = new HashMap<String, Object>(); body.put("field1", "field1"); body.put("field2", "field2"); HashMap<String, Object> meta = new HashMap<String, Object>(); meta.put("meta1", "field1"); meta.put("meta2", "field2"); MongoEntity e = new MongoEntity("collection", UUID.randomUUID().toString(), body, meta); DBObject d = converter.convert(e); Assert.assertNotNull(d); assertSame(body, (Map<?, ?>) d.get("body")); assertSame(meta, (Map<?, ?>) d.get("metaData")); Assert.assertEquals(1, encryptCalls.size()); Assert.assertEquals(2, encryptCalls.get(0).length); Assert.assertEquals(e.getType(), encryptCalls.get(0)[0]); Assert.assertEquals(e.getBody(), encryptCalls.get(0)[1]); } | @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } | EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); } |
@Test public void testReadPreference() { template.setReadPreference(ReadPreference.secondary()); Query query = new Query(); template.findEach(query, Entity.class, "student"); Assert.assertEquals(ReadPreference.secondary(), template.getCollection("student").getReadPreference()); } | public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } | MongoEntityTemplate extends MongoTemplate { public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } } | MongoEntityTemplate extends MongoTemplate { public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } MongoEntityTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter); } | MongoEntityTemplate extends MongoTemplate { public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } MongoEntityTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter); Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName); } | MongoEntityTemplate extends MongoTemplate { public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } MongoEntityTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter); Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName); } |
@Test(expected = RuntimeException.class) public void testUnhandled() { aes.encrypt(1.1F); } | @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } @Override String encrypt(Object data); @Override Object decrypt(String data); } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } @Override String encrypt(Object data); @Override Object decrypt(String data); } |
@Test() public void testUnencryptedString() { Object decrypted = aes.decrypt("Some text"); assertEquals(null, decrypted); Object d2 = aes.decrypt("SOME DATA WITH : IN IT"); assertEquals(null, d2); } | @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } @Override String encrypt(Object data); @Override Object decrypt(String data); } | AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } @Override String encrypt(Object data); @Override Object decrypt(String data); } |
@Test public void shouldGetTenantIdFromLzPath() { Entity tenantRecord = createTenantEntity(); when(mockRepository.findOne(Mockito.eq("tenant"), Mockito.any(NeutralQuery.class))).thenReturn(tenantRecord); String tenantIdResult = tenantDA.getTenantId(lzPath1); assertNotNull("tenantIdResult was null", tenantIdResult); assertEquals("tenantIdResult did not match expected value", tenantId, tenantIdResult); Mockito.verify(mockRepository, Mockito.times(1)).findOne(Mockito.eq("tenant"), Mockito.any(NeutralQuery.class)); } | @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } | TenantMongoDA implements TenantDA { @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } } | TenantMongoDA implements TenantDA { @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } } | TenantMongoDA implements TenantDA { @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); } | TenantMongoDA implements TenantDA { @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; } |
@Test public void testGetAllConfigByType() { configManager = new ConfigManagerImpl(); configManager.setApiClient(apiClient); configManager.setDriverConfigLocation("config"); configManager.setUserConfigLocation("custom"); Map<String, String> params = new HashMap<String, String>(); params.put("type", "PANEL"); String edOrgId = "2012de-df94acd2-e7cd-11e1-a937-68a86d3c2f82"; Map<String, Collection<Config>> mapConfigs = configManager.getAllConfigByType("token", new EdOrgKey(edOrgId), params); Assert.assertEquals(3, mapConfigs.size()); Collection<Config> defaultConfig = mapConfigs.get("default"); Assert.assertNotNull(defaultConfig); Assert.assertEquals(10, defaultConfig.size()); Collection<Config> sea = mapConfigs.get("State Education Agency"); Assert.assertNotNull(sea); Assert.assertEquals(1, sea.size()); Collection<Config> lea = mapConfigs.get("Local Education Agency"); Assert.assertNotNull(lea); Assert.assertEquals(1, lea.size()); } | @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } | ConfigManagerImpl extends ApiClientManager implements ConfigManager { @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } } | ConfigManagerImpl extends ApiClientManager implements ConfigManager { @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } ConfigManagerImpl(); } | ConfigManagerImpl extends ApiClientManager implements ConfigManager { @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } ConfigManagerImpl(); void setDriverConfigLocation(String configLocation); void setUserConfigLocation(String configLocation); String getComponentConfigLocation(String path, String componentId); String getDriverConfigLocation(String componentId); @Override @CacheableConfig Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId); @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs,
boolean overwriteCustomConfig); @Override ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, Config config); @Override Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey,
Map<String, String> params); } | ConfigManagerImpl extends ApiClientManager implements ConfigManager { @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } ConfigManagerImpl(); void setDriverConfigLocation(String configLocation); void setUserConfigLocation(String configLocation); String getComponentConfigLocation(String path, String componentId); String getDriverConfigLocation(String componentId); @Override @CacheableConfig Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId); @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs,
boolean overwriteCustomConfig); @Override ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, Config config); @Override Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey,
Map<String, String> params); } |
@Test public void testGetUserEdOrg() { this.testInstitutionalHierarchyManagerImpl = new UserEdOrgManagerImpl() { @Override public String getToken() { return ""; } @Override protected boolean isEducator() { return false; } }; this.testInstitutionalHierarchyManagerImpl.setApiClient(apiClient); EdOrgKey edOrgKey1 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg(Constants.STATE_EDUCATION_AGENCY); Assert.assertEquals("2012ny-09327920-e000-11e1-9f3b-3c07546832b4", edOrgKey1.getSliId()); EdOrgKey edOrgKey2 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg(Constants.LOCAL_EDUCATION_AGENCY); Assert.assertEquals("2012zj-0b0711a4-e000-11e1-9f3b-3c07546832b4", edOrgKey2.getSliId()); this.testInstitutionalHierarchyManagerImpl = new UserEdOrgManagerImpl() { @Override public String getToken() { return ""; } @Override protected boolean isEducator() { return true; } }; this.testInstitutionalHierarchyManagerImpl.setApiClient(apiClient); EdOrgKey edOrgKey3 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg("Teacher"); Assert.assertEquals("2012zj-0b0711a4-e000-11e1-9f3b-3c07546832b4", edOrgKey3.getSliId()); } | @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } | UserEdOrgManagerImpl extends ApiClientManager implements UserEdOrgManager { @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } } | UserEdOrgManagerImpl extends ApiClientManager implements UserEdOrgManager { @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } } | UserEdOrgManagerImpl extends ApiClientManager implements UserEdOrgManager { @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } @Override @CacheableUserData EdOrgKey getUserEdOrg(String token); @Override @CacheableUserData GenericEntity getUserInstHierarchy(String token, Object key, Data config); @Override GenericEntity getUserCoursesAndSections(String token, Object schoolIdObj, Data config); @Override @SuppressWarnings("unchecked") GenericEntity getUserSectionList(String token, Object schoolIdObj, Data config); @Override GenericEntity getStaffInfo(String token); @Override @SuppressWarnings("unchecked") GenericEntity getSchoolInfo(String token, Object schoolIdObj, Data config); } | UserEdOrgManagerImpl extends ApiClientManager implements UserEdOrgManager { @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } @Override @CacheableUserData EdOrgKey getUserEdOrg(String token); @Override @CacheableUserData GenericEntity getUserInstHierarchy(String token, Object key, Data config); @Override GenericEntity getUserCoursesAndSections(String token, Object schoolIdObj, Data config); @Override @SuppressWarnings("unchecked") GenericEntity getUserSectionList(String token, Object schoolIdObj, Data config); @Override GenericEntity getStaffInfo(String token); @Override @SuppressWarnings("unchecked") GenericEntity getSchoolInfo(String token, Object schoolIdObj, Data config); } |
@Test public void test() { GenericEntity entity = new GenericEntity(); GenericEntity element = new GenericEntity(); element.put("tire", "Yokohama"); entity.put("car", element); assertEquals("{\"car\":{\"tire\":\"Yokohama\"}}", JsonConverter.toJson(entity)); } | public static String toJson(Object o) { return GSON.toJson(o); } | JsonConverter { public static String toJson(Object o) { return GSON.toJson(o); } } | JsonConverter { public static String toJson(Object o) { return GSON.toJson(o); } } | JsonConverter { public static String toJson(Object o) { return GSON.toJson(o); } static String toJson(Object o); static T fromJson(String json, Class<T> clazz); static T fromJson(Reader reader, Class<T> clazz); } | JsonConverter { public static String toJson(Object o) { return GSON.toJson(o); } static String toJson(Object o); static T fromJson(String json, Class<T> clazz); static T fromJson(Reader reader, Class<T> clazz); } |
@Test public void testSort() { List<GenericEntity> entities = new LinkedList<GenericEntity>(); List<LinkedHashMap<String, Object>> studentParentsAssocistion = new LinkedList<LinkedHashMap<String, Object>>(); LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>(); obj.put(Constants.ATTR_RELATION, "Father"); studentParentsAssocistion.add(obj); GenericEntity entity = new GenericEntity(); entity.put(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS, studentParentsAssocistion); entities.add(entity); obj = new LinkedHashMap<String, Object>(); obj.put(Constants.ATTR_RELATION, "Mother"); studentParentsAssocistion = new LinkedList<LinkedHashMap<String, Object>>(); studentParentsAssocistion.add(obj); entity = new GenericEntity(); entity.put(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS, studentParentsAssocistion); entities.add(entity); ParentsSorter.sort(entities); List<LinkedHashMap<String, Object>> objTest = (List<LinkedHashMap<String, Object>>) entities.get(0).get( Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); Assert.assertEquals("Mother", objTest.get(0).get(Constants.ATTR_RELATION)); } | public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } | ParentsSorter { public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } } | ParentsSorter { public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } private ParentsSorter(); } | ParentsSorter { public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } private ParentsSorter(); static List<GenericEntity> sort(List<GenericEntity> genericEntities); } | ParentsSorter { public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } private ParentsSorter(); static List<GenericEntity> sort(List<GenericEntity> genericEntities); } |
@Test public void testEnhanceStudent() { GenericEntity entity = new GenericEntity(); entity.put("gradeLevel", "Adult Education"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "AE"); entity = new GenericEntity(); entity.put("gradeLevel", "Early Education"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "EE"); entity = new GenericEntity(); entity.put("gradeLevel", "Eighth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "8"); entity = new GenericEntity(); entity.put("gradeLevel", "Eleventh grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "11"); entity = new GenericEntity(); entity.put("gradeLevel", "Fifth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "5"); entity = new GenericEntity(); entity.put("gradeLevel", "First grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "1"); entity = new GenericEntity(); entity.put("gradeLevel", "Fourth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "4"); entity = new GenericEntity(); entity.put("gradeLevel", "Grade 13"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "13"); entity = new GenericEntity(); entity.put("gradeLevel", "Infant/toddler"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "IN"); entity = new GenericEntity(); entity.put("gradeLevel", "Kindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "K"); entity = new GenericEntity(); entity.put("gradeLevel", "Ninth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "9"); entity = new GenericEntity(); entity.put("gradeLevel", "Other"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "O"); entity = new GenericEntity(); entity.put("gradeLevel", "Postsecondary"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "+S"); entity = new GenericEntity(); entity.put("gradeLevel", "Preschool/Prekindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "PK"); entity = new GenericEntity(); entity.put("gradeLevel", "Second grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "2"); entity = new GenericEntity(); entity.put("gradeLevel", "Seventh grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "7"); entity = new GenericEntity(); entity.put("gradeLevel", "Sixth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "6"); entity = new GenericEntity(); entity.put("gradeLevel", "Tenth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "10"); entity = new GenericEntity(); entity.put("gradeLevel", "Third grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "3"); entity = new GenericEntity(); entity.put("gradeLevel", "Transitional Kindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "TK"); entity = new GenericEntity(); entity.put("gradeLevel", "Twelfth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "12"); entity = new GenericEntity(); entity.put("gradeLevel", "Ungraded"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "UG"); entity = new GenericEntity(); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertNull(entity.get("gradeLevelCode")); } | public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } | GenericEntityEnhancer { public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } } | GenericEntityEnhancer { public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } } | GenericEntityEnhancer { public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); } | GenericEntityEnhancer { public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); } |
@Test public void testEnhanceStudentSchoolAssociation() { GenericEntity entity = new GenericEntity(); entity.put("entryGradeLevel", "Adult Education"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "AE"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Early Education"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "EE"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Eighth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "8"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Eleventh grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "11"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Fifth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "5"); entity = new GenericEntity(); entity.put("entryGradeLevel", "First grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "1"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Fourth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "4"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Grade 13"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "13"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Infant/toddler"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "IN"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Kindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "K"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Ninth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "9"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Other"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "O"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Postsecondary"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "+S"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Preschool/Prekindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "PK"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Second grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "2"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Seventh grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "7"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Sixth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "6"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Tenth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "10"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Third grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "3"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Transitional Kindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "TK"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Twelfth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "12"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Ungraded"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "UG"); entity = new GenericEntity(); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertNull(entity.get("entryGradeLevelCode")); } | public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } | GenericEntityEnhancer { public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } } | GenericEntityEnhancer { public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } } | GenericEntityEnhancer { public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); } | GenericEntityEnhancer { public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); } |
@Test public void testIsSecuredRequest() throws Exception { LOG.debug("[SLCAuthenticationEntryPointTest]Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(true); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with non-local environment, return FALSE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with non-local environment, return FALSE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Secure Protocol with non-local environment, return TRUE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(true); assertTrue(SLIAuthenticationEntryPoint.isSecureRequest(request)); } | static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); static final String OAUTH_TOKEN; static final String DASHBOARD_COOKIE; } |
@Test public void testCommence() throws Exception { HttpSession mockSession = mock(HttpSession.class); AuthenticationException mockAuthenticationException = mock(AuthenticationException.class); PropertiesDecryptor mockPropertiesDecryptor = mock(PropertiesDecryptor.class); APIClient mockAPIClient = mock(APIClient.class); RESTClient mockRESTClient = mock(RESTClient.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = (JsonObject)parser.parse("{\"authenticated\":true,\"edOrg\":null,\"edOrgId\":null,\"email\":\"[email protected]\",\"external_id\":\"cgray\",\"full_name\":\"Mr Charles Gray\",\"granted_authorities\":[\"Destroyme\"],\"isAdminUser\":false,\"realm\":\"2013uz-d5ae70c9-55ef-11e2-b6be-68a86d3c2fde\",\"rights\":[\"READ_PUBLIC\",\"READ_GENERAL\",\"AGGREGATE_READ\"],\"sliRoles\":[\"Destroyme\"],\"tenantId\":\"[email protected]\",\"userType\":\"teacher\",\"user_id\":\"[email protected]@gmail.com\"}"); when(request.getSession()).thenReturn(mockSession); when(request.getRemoteAddr()).thenReturn("http: when(request.getServerName()).thenReturn("mock.slidev.org"); when(request.isSecure()).thenReturn(true); when(mockPropertiesDecryptor.getDecryptedClientId()).thenReturn("mock-client-id"); when(mockPropertiesDecryptor.getDecryptedClientSecret()).thenReturn("mock-client-secret"); when(mockPropertiesDecryptor.encrypt(anyString())).thenReturn("MOCK-ENCRYPTED-TOKEN"); when(mockSession.getAttribute(anyString())).thenReturn("Mock-OAUTH-TOKEN"); when(mockRESTClient.sessionCheck(anyString())).thenReturn(jsonObject); SLIAuthenticationEntryPoint sliAuthenticationEntryPoint = new SLIAuthenticationEntryPoint(); sliAuthenticationEntryPoint.setPropDecryptor(mockPropertiesDecryptor); sliAuthenticationEntryPoint.setApiClient(mockAPIClient); sliAuthenticationEntryPoint.setRestClient(mockRESTClient); sliAuthenticationEntryPoint.setApiUrl("/api/mock/uri"); sliAuthenticationEntryPoint.setCallbackUrl("http: sliAuthenticationEntryPoint.commence(request,response,mockAuthenticationException); } | @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); } | SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); static final String OAUTH_TOKEN; static final String DASHBOARD_COOKIE; } |
@Test public void shouldGetCourseSectionMappings() throws SLIClientException, IOException, URISyntaxException { List<GenericEntity> sections = new ArrayList<GenericEntity>(); sections.add(createSection("S1", "CO1", "Section 1")); sections.add(createSection("S2", "CO2", "Section 2")); List<Entity> courseOfferings = new ArrayList<Entity>(); courseOfferings.add(createCourseOffering("CO1", "C1")); courseOfferings.add(createCourseOffering("CO2", "C2")); when(mockSliClient.read("/schools/SCHOOL_ID/courseOfferings/?limit=0")).thenReturn(courseOfferings); when(mockSliClient.read("/educationOrganizations/SCHOOL_ID")) .thenReturn(asList(createEdOrg(SCHOOL_ID, LEA_ID))); when(mockSliClient.read("/educationOrganizations/LEA_ID")).thenReturn(asList(createEdOrg(LEA_ID, SEA_ID))); when(mockSliClient.read("/educationOrganizations/SEA_ID")).thenReturn(asList(createEdOrg(SEA_ID, null))); when(mockSliClient.read("/educationOrganizations/SCHOOL_ID/courses?limit=0")).thenReturn( asList(createCourse("C1", "C1"))); when(mockSliClient.read("/educationOrganizations/LEA_ID/courses?limit=0")).thenReturn( asList(createCourse("C2", "C1"))); List<GenericEntity> result = sdkapiClient.getCourseSectionMappings(sections, SCHOOL_ID, TOKEN); Assert.assertEquals(2, result.size()); } | @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } | SDKAPIClient implements APIClient { @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } } | SDKAPIClient implements APIClient { @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } } | SDKAPIClient implements APIClient { @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } SLIClientFactory getClientFactory(); void setClientFactory(SLIClientFactory clientFactory); void setGracePeriod(String gracePeriod); String getGracePeriod(); @Override GenericEntity getEntity(String token, String type, String id, Map<String, String> params); @Override List<GenericEntity> getEntities(String token, String type, String ids, Map<String, String> params); @Override GenericEntity getHome(String token); @Override String getId(String token); @Override ConfigMap getEdOrgCustomData(String token, String id); @Override void putEdOrgCustomData(String token, String id, ConfigMap configMap); @Override List<GenericEntity> getEducationalOrganizations(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getEducationOrganizationsForStaff(String token, String staffId); @Override GenericEntity getEducationalOrganization(String token, String id); @Override GenericEntity getEducationOrganizationForStaff(String token, String staffId, String organizationCategory); @Override List<GenericEntity> getParentEducationalOrganizations(String token,
List<GenericEntity> educationalOrganizations); @Override GenericEntity getParentEducationalOrganization(String token, GenericEntity educationalOrganization); @Override List<GenericEntity> getSchools(String token, List<String> ids); @Override List<GenericEntity> getMySchools(String token); @Override List<GenericEntity> getSchools(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getSchool(String token, String id); @Override List<GenericEntity> getSessions(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getSessions(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSessionsForYear(String token, String schoolYear); @Override GenericEntity getSession(String token, String id); @Override List<GenericEntity> getSections(String token, Map<String, String> params); @Override List<GenericEntity> getSections(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSectionsForNonEducator(String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForTeacher(String teacherId, String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForStudent(final String token, final String studentId,
Map<String, String> params); @Override @CacheableUserData GenericEntity getSection(String token, String id); @Override GenericEntity getSectionHomeForStudent(String token, String studentId); @Override List<GenericEntity> getCourses(String token, List<String> ids, Map<String, String> params); List<GenericEntity> getCourses(String token, List<String> ids); @Override List<GenericEntity> getCoursesForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getCoursesSectionsForSchool(String token, String schoolId); @Override List<GenericEntity> getTranscriptsForStudent(String token, String studentId, Map<String, String> params); @Override GenericEntity getCourse(String token, String id); @Override List<GenericEntity> getStaff(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getStaff(String token, String id); @Override GenericEntity getStaffWithEducationOrganization(String token, String id, String organizationCategory); @Override List<GenericEntity> getTeachers(String token, List<String> ids, Map<String, String> params); @Override @CacheableUserData GenericEntity getTeacher(String token, String id); @Override GenericEntity getTeacherWithSections(String token, String id); @Override GenericEntity getTeacherForSection(String token, String sectionId); @Override String getTeacherIdForSection(String token, String sectionId); @Override void getTeacherIdForSections(String token, List<String> sectionIds, Map<String, String> teacherIdCache); @Override List<GenericEntity> getTeachersForSchool(String token, String schoolId); @Override List<GenericEntity> getParentsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getStudentsForSchool(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getStudentsForSection(String token, String sectionId); @Override List<GenericEntity> getStudentsWithSearch(String token, String firstName, String lastName, String schoolId); @Override List<GenericEntity> searchStudents(String token, String query, Map<String, String> params); @Override List<GenericEntity> getStudentsForSectionWithGradebookEntries(String token, String sectionId); @Override @CacheableUserData GenericEntity getStudent(String token, String id); @Override GenericEntity getStudentWithOptionalFields(String token, String id, List<String> optionalFields); @Override List<GenericEntity> getEnrollmentForStudent(String token, String studentId); @Override List<GenericEntity> getAttendanceForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAcademicRecordsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAssessments(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getAssessmentsForStudent(String token, String studentId); @Override GenericEntity getAssessment(String token, String id); @Override @ExecutionTimeLogger.LogExecutionTime GenericEntity readEntity(String token, String url); @ExecutionTimeLogger.LogExecutionTime @Override @CacheableUserData List<GenericEntity> readEntityList(String token, String url); @Override List<GenericEntity> readEntityList(String token, List<String> ids, Map<String, String> params, String type); @Override List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token); SLIClient getClient(String sessionToken); } | SDKAPIClient implements APIClient { @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } SLIClientFactory getClientFactory(); void setClientFactory(SLIClientFactory clientFactory); void setGracePeriod(String gracePeriod); String getGracePeriod(); @Override GenericEntity getEntity(String token, String type, String id, Map<String, String> params); @Override List<GenericEntity> getEntities(String token, String type, String ids, Map<String, String> params); @Override GenericEntity getHome(String token); @Override String getId(String token); @Override ConfigMap getEdOrgCustomData(String token, String id); @Override void putEdOrgCustomData(String token, String id, ConfigMap configMap); @Override List<GenericEntity> getEducationalOrganizations(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getEducationOrganizationsForStaff(String token, String staffId); @Override GenericEntity getEducationalOrganization(String token, String id); @Override GenericEntity getEducationOrganizationForStaff(String token, String staffId, String organizationCategory); @Override List<GenericEntity> getParentEducationalOrganizations(String token,
List<GenericEntity> educationalOrganizations); @Override GenericEntity getParentEducationalOrganization(String token, GenericEntity educationalOrganization); @Override List<GenericEntity> getSchools(String token, List<String> ids); @Override List<GenericEntity> getMySchools(String token); @Override List<GenericEntity> getSchools(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getSchool(String token, String id); @Override List<GenericEntity> getSessions(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getSessions(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSessionsForYear(String token, String schoolYear); @Override GenericEntity getSession(String token, String id); @Override List<GenericEntity> getSections(String token, Map<String, String> params); @Override List<GenericEntity> getSections(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSectionsForNonEducator(String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForTeacher(String teacherId, String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForStudent(final String token, final String studentId,
Map<String, String> params); @Override @CacheableUserData GenericEntity getSection(String token, String id); @Override GenericEntity getSectionHomeForStudent(String token, String studentId); @Override List<GenericEntity> getCourses(String token, List<String> ids, Map<String, String> params); List<GenericEntity> getCourses(String token, List<String> ids); @Override List<GenericEntity> getCoursesForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getCoursesSectionsForSchool(String token, String schoolId); @Override List<GenericEntity> getTranscriptsForStudent(String token, String studentId, Map<String, String> params); @Override GenericEntity getCourse(String token, String id); @Override List<GenericEntity> getStaff(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getStaff(String token, String id); @Override GenericEntity getStaffWithEducationOrganization(String token, String id, String organizationCategory); @Override List<GenericEntity> getTeachers(String token, List<String> ids, Map<String, String> params); @Override @CacheableUserData GenericEntity getTeacher(String token, String id); @Override GenericEntity getTeacherWithSections(String token, String id); @Override GenericEntity getTeacherForSection(String token, String sectionId); @Override String getTeacherIdForSection(String token, String sectionId); @Override void getTeacherIdForSections(String token, List<String> sectionIds, Map<String, String> teacherIdCache); @Override List<GenericEntity> getTeachersForSchool(String token, String schoolId); @Override List<GenericEntity> getParentsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getStudentsForSchool(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getStudentsForSection(String token, String sectionId); @Override List<GenericEntity> getStudentsWithSearch(String token, String firstName, String lastName, String schoolId); @Override List<GenericEntity> searchStudents(String token, String query, Map<String, String> params); @Override List<GenericEntity> getStudentsForSectionWithGradebookEntries(String token, String sectionId); @Override @CacheableUserData GenericEntity getStudent(String token, String id); @Override GenericEntity getStudentWithOptionalFields(String token, String id, List<String> optionalFields); @Override List<GenericEntity> getEnrollmentForStudent(String token, String studentId); @Override List<GenericEntity> getAttendanceForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAcademicRecordsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAssessments(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getAssessmentsForStudent(String token, String studentId); @Override GenericEntity getAssessment(String token, String id); @Override @ExecutionTimeLogger.LogExecutionTime GenericEntity readEntity(String token, String url); @ExecutionTimeLogger.LogExecutionTime @Override @CacheableUserData List<GenericEntity> readEntityList(String token, String url); @Override List<GenericEntity> readEntityList(String token, List<String> ids, Map<String, String> params, String type); @Override List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token); SLIClient getClient(String sessionToken); } |
@Test public void testGetStatusCodes() { assertEquals(STATUS_CODES, response.getStatusCodes()); } | public List<String> getStatusCodes() { return statusCodes; } | Response extends WadlElement { public List<String> getStatusCodes() { return statusCodes; } } | Response extends WadlElement { public List<String> getStatusCodes() { return statusCodes; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); } | Response extends WadlElement { public List<String> getStatusCodes() { return statusCodes; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Response extends WadlElement { public List<String> getStatusCodes() { return statusCodes; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void shouldInsertTenant() { TenantRecord tenantRecord = createTestTenantRecord(); tenantDA.insertTenant(tenantRecord); Mockito.verify(mockRepository).create(Mockito.eq("tenant"), Mockito.argThat(new IsCorrectBody(tenantRecord))); } | @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } | TenantMongoDA implements TenantDA { @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } } | TenantMongoDA implements TenantDA { @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } } | TenantMongoDA implements TenantDA { @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); } | TenantMongoDA implements TenantDA { @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; } |
@Test public void testGetParams() { assertEquals(PARAMS, response.getParams()); } | public List<Param> getParams() { return params; } | Response extends WadlElement { public List<Param> getParams() { return params; } } | Response extends WadlElement { public List<Param> getParams() { return params; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); } | Response extends WadlElement { public List<Param> getParams() { return params; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Response extends WadlElement { public List<Param> getParams() { return params; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testGetRepresentations() { assertEquals(REPRESENTATIONS, response.getRepresentations()); } | public List<Representation> getRepresentations() { return representations; } | Response extends WadlElement { public List<Representation> getRepresentations() { return representations; } } | Response extends WadlElement { public List<Representation> getRepresentations() { return representations; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); } | Response extends WadlElement { public List<Representation> getRepresentations() { return representations; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Response extends WadlElement { public List<Representation> getRepresentations() { return representations; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testToString() { assertTrue(!"".equals(response.toString())); } | @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } | Response extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } } | Response extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); } | Response extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Response extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testGetParams() { assertEquals(PARAMS, request.getParams()); } | public List<Param> getParams() { return params; } | Request extends WadlElement { public List<Param> getParams() { return params; } } | Request extends WadlElement { public List<Param> getParams() { return params; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); } | Request extends WadlElement { public List<Param> getParams() { return params; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Request extends WadlElement { public List<Param> getParams() { return params; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testGetRepresentations() { assertEquals(REPRESENTATIONS, request.getRepresentations()); } | public List<Representation> getRepresentations() { return representations; } | Request extends WadlElement { public List<Representation> getRepresentations() { return representations; } } | Request extends WadlElement { public List<Representation> getRepresentations() { return representations; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); } | Request extends WadlElement { public List<Representation> getRepresentations() { return representations; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Request extends WadlElement { public List<Representation> getRepresentations() { return representations; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testToString() { assertTrue(!"".equals(request.toString())); } | @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } | Request extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } } | Request extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); } | Request extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } | Request extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); } |
@Test public void testGetId() { assertEquals(ID, representation.getId()); } | public String getId() { return id; } | Representation extends WadlElement { public String getId() { return id; } } | Representation extends WadlElement { public String getId() { return id; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { public String getId() { return id; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { public String getId() { return id; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@Test public void testGetMediaType() { assertEquals(MEDIA_TYPE, representation.getMediaType()); } | public String getMediaType() { return mediaType; } | Representation extends WadlElement { public String getMediaType() { return mediaType; } } | Representation extends WadlElement { public String getMediaType() { return mediaType; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { public String getMediaType() { return mediaType; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { public String getMediaType() { return mediaType; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@Test public void testGetParams() { assertEquals(PARAMS, representation.getParams()); } | public List<Param> getParams() { return params; } | Representation extends WadlElement { public List<Param> getParams() { return params; } } | Representation extends WadlElement { public List<Param> getParams() { return params; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { public List<Param> getParams() { return params; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { public List<Param> getParams() { return params; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@Test public void testGetProfiles() { assertEquals(PROFILES, representation.getProfiles()); } | public List<String> getProfiles() { return profiles; } | Representation extends WadlElement { public List<String> getProfiles() { return profiles; } } | Representation extends WadlElement { public List<String> getProfiles() { return profiles; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { public List<String> getProfiles() { return profiles; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { public List<String> getProfiles() { return profiles; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@SuppressWarnings("unchecked") @Test public void testGetAutoLoadFiles() throws UnknownHostException { Map<String, Object> tenantsForPreloading = new HashMap<String, Object>(); tenantsForPreloading.put(lzPath1, Arrays.asList("smallDataSet.xml", "mediumDataSet.xml")); Entity tenant = createTenantEntity(); List<Map<String, Object>> landingZone = (List<Map<String, Object>>) tenant.getBody().get( TenantMongoDA.LANDING_ZONE); Map<String, Object> preloadDef = new HashMap<String, Object>(); preloadDef.put(TenantMongoDA.PRELOAD_STATUS, "ready"); preloadDef.put(TenantMongoDA.PRELOAD_FILES, Arrays.asList("smallDataSet.xml", "mediumDataSet.xml")); landingZone.get(0).put(TenantMongoDA.PRELOAD_DATA, preloadDef); when(mockRepository.findAll(eq("tenant"), any(NeutralQuery.class))).thenReturn(Arrays.asList(tenant)); when(mockRepository.doUpdate(eq("tenant"), any(NeutralQuery.class), any(Update.class))).thenReturn(true); assertEquals(tenantsForPreloading, tenantDA.getPreloadFiles("ingestion_server_host")); verify(mockRepository).doUpdate(eq("tenant"), any(NeutralQuery.class), argThat(new ArgumentMatcher<Update>() { @Override public boolean matches(Object argument) { Update expectedUpdate = Update.update("body." + TenantMongoDA.LANDING_ZONE + ".$." + TenantMongoDA.PRELOAD_DATA + "." + TenantMongoDA.PRELOAD_STATUS, "started"); return ((Update) argument).getUpdateObject().equals(expectedUpdate.getUpdateObject()); } })); } | @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } | TenantMongoDA implements TenantDA { @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } } | TenantMongoDA implements TenantDA { @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } } | TenantMongoDA implements TenantDA { @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); } | TenantMongoDA implements TenantDA { @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; } |
@Test public void testGetElementName() { assertEquals(ELEMENT_NAME, representation.getElementName()); } | public QName getElementName() { return elementName; } | Representation extends WadlElement { public QName getElementName() { return elementName; } } | Representation extends WadlElement { public QName getElementName() { return elementName; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { public QName getElementName() { return elementName; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { public QName getElementName() { return elementName; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@Test public void testToString() { assertTrue(!"".equals(representation.toString())); } | @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } | Representation extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } } | Representation extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); } | Representation extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } | Representation extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); } |
@Test public void testGetIncludes() { assertEquals(INCLUDES, grammars.getIncludes()); } | public List<Include> getIncludes() { return includes; } | Grammars extends WadlElement { public List<Include> getIncludes() { return includes; } } | Grammars extends WadlElement { public List<Include> getIncludes() { return includes; } Grammars(final List<Documentation> doc, final List<Include> includes); } | Grammars extends WadlElement { public List<Include> getIncludes() { return includes; } Grammars(final List<Documentation> doc, final List<Include> includes); List<Include> getIncludes(); @Override String toString(); } | Grammars extends WadlElement { public List<Include> getIncludes() { return includes; } Grammars(final List<Documentation> doc, final List<Include> includes); List<Include> getIncludes(); @Override String toString(); } |
@Test public void testToString() { assertTrue(!"".equals(grammars.toString())); } | @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("includes").append(" : ").append(includes); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } | Grammars extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("includes").append(" : ").append(includes); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } } | Grammars extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("includes").append(" : ").append(includes); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Grammars(final List<Documentation> doc, final List<Include> includes); } | Grammars extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("includes").append(" : ").append(includes); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Grammars(final List<Documentation> doc, final List<Include> includes); List<Include> getIncludes(); @Override String toString(); } | Grammars extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("includes").append(" : ").append(includes); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Grammars(final List<Documentation> doc, final List<Include> includes); List<Include> getIncludes(); @Override String toString(); } |
@Test public void testGetTitle() { assertEquals(TITLE, documentation.getTitle()); } | public String getTitle() { return title; } | Documentation { public String getTitle() { return title; } } | Documentation { public String getTitle() { return title; } Documentation(final String title, final String language, final List<DmNode> contents); } | Documentation { public String getTitle() { return title; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } | Documentation { public String getTitle() { return title; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } |
@Test public void testGetLanguage() { assertEquals(LANGUAGE, documentation.getLanguage()); } | public String getLanguage() { return language; } | Documentation { public String getLanguage() { return language; } } | Documentation { public String getLanguage() { return language; } Documentation(final String title, final String language, final List<DmNode> contents); } | Documentation { public String getLanguage() { return language; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } | Documentation { public String getLanguage() { return language; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } |
@Test public void testGetContents() { assertEquals(CONTENTS, documentation.getContents()); } | public List<DmNode> getContents() { return contents; } | Documentation { public List<DmNode> getContents() { return contents; } } | Documentation { public List<DmNode> getContents() { return contents; } Documentation(final String title, final String language, final List<DmNode> contents); } | Documentation { public List<DmNode> getContents() { return contents; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } | Documentation { public List<DmNode> getContents() { return contents; } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } |
@Test public void testToString() { assertTrue(!"".equals(documentation.toString())); } | @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("language").append(" : ").append(language); sb.append(", "); sb.append("title").append(" : ").append(title); sb.append(", "); sb.append("contents").append(" : ").append(contents); sb.append("}"); return sb.toString(); } | Documentation { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("language").append(" : ").append(language); sb.append(", "); sb.append("title").append(" : ").append(title); sb.append(", "); sb.append("contents").append(" : ").append(contents); sb.append("}"); return sb.toString(); } } | Documentation { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("language").append(" : ").append(language); sb.append(", "); sb.append("title").append(" : ").append(title); sb.append(", "); sb.append("contents").append(" : ").append(contents); sb.append("}"); return sb.toString(); } Documentation(final String title, final String language, final List<DmNode> contents); } | Documentation { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("language").append(" : ").append(language); sb.append(", "); sb.append("title").append(" : ").append(title); sb.append(", "); sb.append("contents").append(" : ").append(contents); sb.append("}"); return sb.toString(); } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } | Documentation { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("language").append(" : ").append(language); sb.append(", "); sb.append("title").append(" : ").append(title); sb.append(", "); sb.append("contents").append(" : ").append(contents); sb.append("}"); return sb.toString(); } Documentation(final String title, final String language, final List<DmNode> contents); String getTitle(); String getLanguage(); List<DmNode> getContents(); @Override String toString(); } |
@Test public void testGetValue() { assertEquals(VALUE, option.getValue()); } | public String getValue() { return value; } | Option extends WadlElement { public String getValue() { return value; } } | Option extends WadlElement { public String getValue() { return value; } Option(final String value, final List<Documentation> doc); } | Option extends WadlElement { public String getValue() { return value; } Option(final String value, final List<Documentation> doc); String getValue(); } | Option extends WadlElement { public String getValue() { return value; } Option(final String value, final List<Documentation> doc); String getValue(); } |
@Test public void testGetId() { assertEquals(ID, resourceType.getId()); } | public String getId() { return id; } | ResourceType extends WadlElement { public String getId() { return id; } } | ResourceType extends WadlElement { public String getId() { return id; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); } | ResourceType extends WadlElement { public String getId() { return id; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } | ResourceType extends WadlElement { public String getId() { return id; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } |
@Test public void testReceive() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext()); IngestionFileEntry entry = new IngestionFileEntry("/", FileFormat.EDFI_XML, FileType.XML_STUDENT_PROGRAM, "fileName", "111"); FileEntryWorkNote workNote = new FileEntryWorkNote("batchJobId", entry, false); boolean fileEntryLatchOpened; exchange.getIn().setBody(workNote, FileEntryWorkNote.class); fileEntryLatchOpened = fileEntryLatch.lastFileProcessed(exchange); Assert.assertFalse(fileEntryLatchOpened); fileEntryLatchOpened = fileEntryLatch.lastFileProcessed(exchange); Assert.assertTrue(fileEntryLatchOpened); } | @Handler public boolean lastFileProcessed(Exchange exchange) throws Exception { FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class); String batchJobId = workNote.getBatchJobId(); TenantContext.setJobId(batchJobId); if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) { RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId); exchange.getIn().setBody(wn, RangedWorkNote.class); return true; } return false; } | FileEntryLatch { @Handler public boolean lastFileProcessed(Exchange exchange) throws Exception { FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class); String batchJobId = workNote.getBatchJobId(); TenantContext.setJobId(batchJobId); if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) { RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId); exchange.getIn().setBody(wn, RangedWorkNote.class); return true; } return false; } } | FileEntryLatch { @Handler public boolean lastFileProcessed(Exchange exchange) throws Exception { FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class); String batchJobId = workNote.getBatchJobId(); TenantContext.setJobId(batchJobId); if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) { RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId); exchange.getIn().setBody(wn, RangedWorkNote.class); return true; } return false; } } | FileEntryLatch { @Handler public boolean lastFileProcessed(Exchange exchange) throws Exception { FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class); String batchJobId = workNote.getBatchJobId(); TenantContext.setJobId(batchJobId); if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) { RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId); exchange.getIn().setBody(wn, RangedWorkNote.class); return true; } return false; } @Handler boolean lastFileProcessed(Exchange exchange); BatchJobDAO getBatchJobDAO(); void setBatchJobDAO(BatchJobDAO batchJobDAO); } | FileEntryLatch { @Handler public boolean lastFileProcessed(Exchange exchange) throws Exception { FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class); String batchJobId = workNote.getBatchJobId(); TenantContext.setJobId(batchJobId); if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) { RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId); exchange.getIn().setBody(wn, RangedWorkNote.class); return true; } return false; } @Handler boolean lastFileProcessed(Exchange exchange); BatchJobDAO getBatchJobDAO(); void setBatchJobDAO(BatchJobDAO batchJobDAO); } |
@Test public void testGetMethod() { assertEquals(METHOD, resourceType.getMethod()); } | public Method getMethod() { return method; } | ResourceType extends WadlElement { public Method getMethod() { return method; } } | ResourceType extends WadlElement { public Method getMethod() { return method; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); } | ResourceType extends WadlElement { public Method getMethod() { return method; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } | ResourceType extends WadlElement { public Method getMethod() { return method; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } |
@Test public void testGetParams() { assertEquals(PARAMS, resourceType.getParams()); } | public List<Param> getParams() { return params; } | ResourceType extends WadlElement { public List<Param> getParams() { return params; } } | ResourceType extends WadlElement { public List<Param> getParams() { return params; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); } | ResourceType extends WadlElement { public List<Param> getParams() { return params; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } | ResourceType extends WadlElement { public List<Param> getParams() { return params; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } |
@Test public void testGetResource() { assertEquals(RESOURCE, resourceType.getResource()); } | public Resource getResource() { return resource; } | ResourceType extends WadlElement { public Resource getResource() { return resource; } } | ResourceType extends WadlElement { public Resource getResource() { return resource; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); } | ResourceType extends WadlElement { public Resource getResource() { return resource; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } | ResourceType extends WadlElement { public Resource getResource() { return resource; } ResourceType(final String id, final List<Documentation> doc, final List<Param> params,
final Method method, final Resource resource); String getId(); List<Param> getParams(); Method getMethod(); Resource getResource(); } |
@Test public void testComputeRequestTemplateParamsEmptyAncestors() { Stack<Resource> resources = new Stack<Resource>(); Param r1p1 = mock(Param.class); when(r1p1.getStyle()).thenReturn(ParamStyle.TEMPLATE); when(r1p1.getId()).thenReturn(R1P1_ID); List<Param> r1Params = new ArrayList<Param>(1); r1Params.add(r1p1); Resource r1 = mock(Resource.class); when(r1.getParams()).thenReturn(r1Params); List<Param> templateParams = RestHelper.computeRequestTemplateParams(r1, resources); assertEquals(1, templateParams.size()); assertEquals(R1P1_ID, templateParams.get(0).getId()); } | public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } |
@Test public void testComputeRequestTemplateParams() { Stack<Resource> resources = new Stack<Resource>(); Param r1p1 = mock(Param.class); when(r1p1.getStyle()).thenReturn(ParamStyle.TEMPLATE); when(r1p1.getId()).thenReturn(R1P1_ID); List<Param> r1Params = new ArrayList<Param>(1); r1Params.add(r1p1); Resource r1 = mock(Resource.class); when(r1.getParams()).thenReturn(r1Params); Param r2p1 = mock(Param.class); when(r2p1.getStyle()).thenReturn(ParamStyle.TEMPLATE); when(r2p1.getId()).thenReturn(R2P1_ID); Param r2p2 = mock(Param.class); when(r2p2.getStyle()).thenReturn(ParamStyle.QUERY); when(r2p2.getId()).thenReturn(R2P2_ID); List<Param> r2Params = new ArrayList<Param>(2); r2Params.add(r2p1); r2Params.add(r2p2); Resource r2 = mock(Resource.class); when(r2.getParams()).thenReturn(r2Params); Param r3p1 = mock(Param.class); when(r3p1.getStyle()).thenReturn(ParamStyle.TEMPLATE); when(r3p1.getId()).thenReturn(R3P1_ID); Param r3p2 = mock(Param.class); when(r3p2.getStyle()).thenReturn(ParamStyle.TEMPLATE); when(r3p2.getId()).thenReturn(R3P2_ID); List<Param> r3Params = new ArrayList<Param>(2); r3Params.add(r3p1); r3Params.add(r3p2); Resource r3 = mock(Resource.class); when(r3.getParams()).thenReturn(r3Params); resources.push(r2); resources.push(r3); List<Param> templateParams = RestHelper.computeRequestTemplateParams(r1, resources); assertEquals(4, templateParams.size()); assertEquals(R3P1_ID, templateParams.get(0).getId()); assertEquals(R3P2_ID, templateParams.get(1).getId()); assertEquals(R2P1_ID, templateParams.get(2).getId()); assertEquals(R1P1_ID, templateParams.get(3).getId()); } | public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } | RestHelper { public static final List<Param> computeRequestTemplateParams(final Resource resource, final Stack<Resource> ancestors) { final List<Param> params = new LinkedList<Param>(); final List<Resource> rightToLeftResources = new LinkedList<Resource>(); rightToLeftResources.addAll(reverse(ancestors)); rightToLeftResources.add(resource); for (final Resource rightToLeftResource : rightToLeftResources) { for (final Param param : rightToLeftResource.getParams()) { if (param.getStyle() == ParamStyle.TEMPLATE) { params.add(param); } } } return Collections.unmodifiableList(params); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } |
@Test public void testReverse() { List<Integer> numbers = new ArrayList<Integer>(3); numbers.add(1); numbers.add(2); numbers.add(3); List<Integer> reversedNumbers = RestHelper.reverse(numbers); Integer crntNumber = 3; assertEquals(3, reversedNumbers.size()); for (Integer i : reversedNumbers) { assertEquals(crntNumber--, i); } } | public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } |
@Test public void testReverseEmpty() { List<Integer> numbers = new ArrayList<Integer>(0); List<Integer> reversedNumbers = RestHelper.reverse(numbers); assertEquals(0, reversedNumbers.size()); } | public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } | RestHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } static final List<Param> computeRequestTemplateParams(final Resource resource,
final Stack<Resource> ancestors); static final List<T> reverse(final List<T> strings); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.