src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
DinnerPermsResolver implements PermissionsResolver { @Override @SuppressWarnings("deprecation") public boolean inGroup(String name, String group) { return inGroup(server.getOfflinePlayer(name), group); } DinnerPermsResolver(Server server); static PermissionsResolver factory(Server server, YAMLProcessor config); @Overri...
@Test public void testInGroup() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("group.a", true); permissible.setPermission("group.b", true); assertTrue(resolver.inGroup(permissible, "a")); assertTrue(resolver.inGroup(permissible, "b")); assertFalse(resolver.inGroup(...
BukkitWorld extends AbstractWorld { public static TreeType toBukkitTreeType(TreeGenerator.TreeType type) { return treeTypeMapping.get(type); } BukkitWorld(World world); @Override List<com.sk89q.worldedit.entity.Entity> getEntities(Region region); @Override List<com.sk89q.worldedit.entity.Entity> getEntities(); @Nullabl...
@Test public void testTreeTypeMapping() { for (TreeGenerator.TreeType type : TreeGenerator.TreeType.values()) { assertNotNull(BukkitWorld.toBukkitTreeType(type), "No mapping for: " + type); } }
CommandContext { public int argsLength() { return parsedArgs.size(); } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); CommandContext(String[] args, Set<Character> va...
@Test public void testEmptyQuote() { try { CommandContext context = new CommandContext("region flag xmas blocked-cmds \"\""); assertEquals(context.argsLength(), 3); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } }
Location { public Extent getExtent() { return extent; } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw...
@Test public void testGetWorld() throws Exception { World world = mock(World.class); Location location = new Location(world); assertEquals(world, location.getExtent()); }
Location { public Vector3 toVector() { return position; } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float y...
@Test public void testToVector() throws Exception { World world = mock(World.class); Vector3 position = Vector3.at(1, 1, 1); Location location = new Location(world, position); assertEquals(position, location.toVector()); }
Location { public double getX() { return position.getX(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float...
@Test public void testGetX() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getX(), EPSILON); }
Location { public int getBlockX() { return (int) Math.floor(position.getX()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, doubl...
@Test public void testGetBlockX() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getBlockX()); }
Location { public Location setX(double x) { return new Location(extent, position.withX(x), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Exte...
@Test public void testSetX() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setX(TEST_VALUE); assertEquals(0, location1.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getX(), EPSILON); assertEquals(0, location2.getY(), EPS...
Location { public double getY() { return position.getY(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float...
@Test public void testGetY() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getY(), EPSILON); }
Location { public int getBlockY() { return (int) Math.floor(position.getY()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, doubl...
@Test public void testGetBlockY() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getBlockY()); }
ViewerResourceBundle extends ResourceBundle { static String replaceParameters(final String msg, String... params) { String ret = msg; if (ret != null && params != null) { for (int i = 0; i < params.length; ++i) { ret = ret.replace(new StringBuilder("{").append(i).append("}").toString(), params[i]); } } return ret; } Vi...
@Test public void replaceParameters_shouldReturnNullIfMsgIsNull() throws Exception { Assert.assertNull(ViewerResourceBundle.replaceParameters(null, "one", "two", "three")); } @Test public void replaceParameters_shouldReplaceParametersCorrectly() throws Exception { Assert.assertEquals("one two three", ViewerResourceBund...
StructElement extends StructElementStub implements Comparable<StructElementStub>, Serializable { @Override public String getPi() { if (pi != null && !pi.equals("null")) { return pi; } else if (getMetadataValue(SolrConstants.PI_TOPSTRUCT) != null) { pi = getMetadataValue(SolrConstants.PI_TOPSTRUCT); return pi; } else if...
@Test public void getPi_shouldRetrivevePiFromTopstructIfNotTopstruct() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getIddocByLogid(PI_KLEIUNIV, "LOG_0002"); Assert.assertNotEquals(-1, iddoc); StructElement element = new StructElement(iddoc); Assert.assertEquals(PI_KLEIUNIV, element.getPi(...
LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public int getNumPages() throws IndexUnreachableException { if (numPages < 0) { numPages = topElement.getNumPages(); } return numPages; } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPages(); @Override int getFi...
@Test public void getNumPages_shouldReturnSizeCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, 5); Assert.assertEquals(5, pageLoader.getNumPages()); pageLoader = new LeanPageLoader(se, -1); Assert.assertEqual...
LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPage(int pageOrder) throws IndexUnreachableException, DAOException { if (pageOrder != currentPageNumber && pageOrder >= firstPageOrder && pageOrder <= lastPageOrder) { try { currentPage = loadPage(pageOrder, null); c...
@Test public void getPage_shouldReturnCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPage(3); Assert.assertNotNull(pe); Assert.assertEquals(3, pe.getOrder()); } @Te...
LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPageForFileName(String fileName) throws PresentationException, IndexUnreachableException, DAOException { return loadPage(-1, fileName); } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPa...
@Test public void getPageForFileName_shouldReturnTheCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPageForFileName("00000004.tif"); Assert.assertNotNull(pe); Assert...
LeanPageLoader extends AbstractPageLoader implements Serializable { protected PhysicalElement loadPage(int pageNumber, String fileName) throws PresentationException, IndexUnreachableException, DAOException { String pi = topElement.getPi(); if (pageNumber >= 0) { logger.trace("Loading page {} for '{}'...", pageNumber, p...
@Test public void loadPage_shouldLoadPageCorrectlyViaPageNumber() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.loadPage(3, null); Assert.assertNotNull(pe); Assert.assertEquals(3, ...
IpRange implements ILicensee, Serializable { public boolean canSatisfyAllAccessConditions(Set<String> conditionList, List<LicenseType> licenseTypes, String privilegeName, String pi) throws PresentationException, IndexUnreachableException, DAOException { if (AccessConditionUtils.isFreeOpenAccess(conditionList, licenseTy...
@Test public void canSatisfyAllAccessConditions_shouldReturnFalseIfIpRangeHasNoLicense() throws Exception { IpRange ipRange = DataManager.getInstance().getDao().getIpRange(1); Assert.assertNotNull(ipRange); Assert.assertFalse(ipRange.canSatisfyAllAccessConditions(new HashSet<>(Collections.singletonList("license type 2 ...
EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getNumPages() { return pages.size(); } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); ...
@Test public void getNumPages_shouldReturnSizeCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(16, pageLoader.getNumPages()); }
EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPage(int pageOrder) { return pages.get(pageOrder); } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalEle...
@Test public void getPage_shouldReturnCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); PhysicalElement pe = pageLoader.getPage(3); Assert.assertNotNull(pe); Assert.assertEquals(3, pe.getOrder()); }
EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPageForFileName(String fileName) { for (int key : pages.keySet()) { PhysicalElement page = pages.get(key); if (fileName.equals(page.getFileName())) { return page; } } return null; } EagerPageLoader(StructElement top...
@Test public void getPageForFileName_shouldReturnTheCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); PhysicalElement pe = pageLoader.getPageForFileName("00000004.tif"); Assert.assertNotNull(pe); Assert.a...
EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getFirstPageOrder() { return firstPageOrder; } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int page...
@Test public void setFirstAndLastPageOrder_shouldSetFirstPageOrderCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(1, pageLoader.getFirstPageOrder()); }
EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getLastPageOrder() { return lastPageOrder; } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOr...
@Test public void setFirstAndLastPageOrder_shouldSetLastPageOrderCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(16, pageLoader.getLastPageOrder()); }
AbstractPageLoader implements IPageLoader { protected String buildPageLabelTemplate(String format, Locale locale) throws IndexUnreachableException { if (format == null) { throw new IllegalArgumentException("format may not be null"); } String labelTemplate = format.replace("{numpages}", String.valueOf(getNumPages())); P...
@Test public void buildPageLabelTemplate_shouldReplaceNumpagesCurrectly() throws Exception { StructElement se = new StructElement(); EagerPageLoader loader = new EagerPageLoader(se); Assert.assertEquals("foo 0 bar", loader.buildPageLabelTemplate("foo {numpages} bar", null)); } @Test public void buildPageLabelTemplate_s...
ViewManager implements Serializable { public Optional<PhysicalElement> getPage(int order) throws IndexUnreachableException, DAOException { if (pageLoader != null && pageLoader.getPage(order) != null) { return Optional.ofNullable(pageLoader.getPage(order)); } return Optional.empty(); } ViewManager(StructElement topDocum...
@Test public void getPage_shouldReturnCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); ViewManager viewManager = new ViewManager(se, new EagerPageLoader(se), se.getLuceneId(), null, null, null); PhysicalElement pe = viewManager.getPage(3).orElse(null); Asse...
ViewManager implements Serializable { public String getPersistentUrl() throws IndexUnreachableException, DAOException { PhysicalElement currentPage = getCurrentPage(); if (topDocument != null) { String customPURL = topDocument.getMetadataValue("MD_PURL"); if (StringUtils.isNotEmpty(customPURL)) { return customPURL; } }...
@Test public void getPersistentUrl_shouldGeneratePurlViaUrnCorrectly() throws Exception { StructElement se = new StructElement(); ViewManager viewManager = new ViewManager(se, new EagerPageLoader(se), se.getLuceneId(), null, null, new ImageDeliveryBean()); String purl = viewManager.getPersistentUrl("urn:nbn:foo:bar-123...
ViewManager implements Serializable { public boolean isBelowFulltextThreshold() throws PresentationException, IndexUnreachableException { int threshold = DataManager.getInstance().getConfiguration().getFulltextPercentageWarningThreshold(); return isBelowFulltextThreshold(threshold); } ViewManager(StructElement topDocum...
@Test public void isBelowFulltextThreshold_shouldReturnTrueIfThereAreNoPages() throws Exception { String pi = "PPN123"; String docstructType = "Catalogue"; StructElement se = new StructElement(123L); se.setDocStructType(docstructType); se.getMetadataFields().put(SolrConstants.PI_TOPSTRUCT, Collections.singletonList(pi)...
PhysicalElement implements Comparable<PhysicalElement>, Serializable { protected static String determineFileName(String filePath) { String ret = filePath; if (StringUtils.isNotBlank(ret) && !(ret.startsWith("http: File file = new File(ret); ret = file.getName(); } return ret; } PhysicalElement(String physId, String fil...
@Test public void determineFileName_shouldCutOffEverythingButTheFileNameForNormalFilePaths() throws Exception { Assert.assertEquals("image.jpg", PhysicalElement.determineFileName("image.jpg")); Assert.assertEquals("image.jpg", PhysicalElement.determineFileName("/opt/digiverso/viewer/media/123/image.jpg")); } @Test publ...
EventElement implements Comparable<EventElement>, Serializable { public Date getDateStart() { return dateStart; } EventElement(SolrDocument doc, Locale locale); @Override int compareTo(EventElement o); String getDisplayDate(); String getLabel(); String getType(); void setType(String type); Date getDateStart(); void set...
@Test public void EventElement_shouldFillInMissingDateStartFromDisplayDate() throws Exception { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.EVENTDATE, "2018-11-23"); EventElement ee = new EventElement(doc, null); Assert.assertNotNull(ee.getDateStart()); Assert.assertEquals("2018-11-23", DateTools....
EventElement implements Comparable<EventElement>, Serializable { public Date getDateEnd() { return dateEnd; } EventElement(SolrDocument doc, Locale locale); @Override int compareTo(EventElement o); String getDisplayDate(); String getLabel(); String getType(); void setType(String type); Date getDateStart(); void setDate...
@Test public void EventElement_shouldFillInMissingDateEndFromDateStart() throws Exception { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.EVENTDATESTART, "2018-11-23"); EventElement ee = new EventElement(doc, null); Assert.assertNotNull(ee.getDateEnd()); Assert.assertEquals("2018-11-23", DateTools.f...
TocMaker { protected static List<String> getSolrFieldsToFetch(String template) { logger.trace("getSolrFieldsToFetch: {}", template); Set<String> ret = new HashSet<>(Arrays.asList(REQUIRED_FIELDS)); List<Metadata> metadataList = DataManager.getInstance().getConfiguration().getTocLabelConfiguration(template); if (metadat...
@Test public void getSolrFieldsToFetch_shouldReturnBothStaticAndConfiguredFields() throws Exception { List<?> fields = TocMaker.getSolrFieldsToFetch("_DEFAULT"); Assert.assertNotNull(fields); Assert.assertEquals(33, fields.size()); }
TocMaker { public static LinkedHashMap<String, List<TOCElement>> generateToc(TOC toc, StructElement structElement, boolean addAllSiblings, String mimeType, int tocCurrentPage, int hitsPerPage) throws PresentationException, IndexUnreachableException, DAOException, ViewerConfigurationException { logger.trace("generateToc...
@Test public void generateToc_shouldGenerateVolumeTOCWithSiblingsCorrectly() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getIddocFromIdentifier("306653648_1891"); Assert.assertTrue(iddoc > 0); StructElement structElement = new StructElement(iddoc); Map<String, List<TOCElement>> tocElement...
User implements ILicensee, HttpSessionBindingListener, Serializable { public boolean canSatisfyAllAccessConditions(Set<String> conditionList, String privilegeName, String pi) throws PresentationException, IndexUnreachableException, DAOException { if (isSuperuser()) { return true; } if (conditionList.size() == 1 && cond...
@Test public void canSatisfyAllAccessConditions_shouldReturnTrueIfUserHasLicense() throws Exception { User user = DataManager.getInstance().getDao().getUser(2); Assert.assertNotNull(user); List<String> licenceTypes = Arrays.asList(new String[] { "license type 1 name", "license type 3 name" }); Assert.assertTrue(user.ca...
TocMaker { static IMetadataValue buildLabel(SolrDocument doc, String template) { List<Metadata> labelConfigList = DataManager.getInstance().getConfiguration().getTocLabelConfiguration(template); IMetadataValue label = new MultiLanguageMetadataValue(); if (labelConfigList == null || labelConfigList.isEmpty()) { label.se...
@Test public void buildLabel_shouldBuildConfiguredLabelCorrectly() throws Exception { { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.LABEL, "label"); doc.setField("MD_CREATOR", "creator"); String label = TocMaker.buildLabel(doc, null).getValue().orElse(""); Assert.assertEquals("label/creator", labe...
TOCElement implements Serializable { public String getUrl() { return urlPrefix + urlSuffix; } TOCElement(IMetadataValue label, String pageNo, String pageNoLabel, String iddoc, String logId, int level, String topStructPi, String thumbnailUrl, boolean accessPermissionPdf, boolean anchorOrGroup, boolean hasIma...
@Test public void getUrl_shouldConstructFullScreenUrlCorrectly() throws Exception { TOCElement tef = new TOCElement(new SimpleMetadataValue("Label"), "1", "first", "123", "LOG_0001", 0, "PPN123", null, false, false, true, "image", null, null); Assert.assertEquals('/' + PageType.viewFullscreen.getName() + "/PPN123/1/LOG...
CalendarView { public List<String> getVolumeYears() throws PresentationException, IndexUnreachableException { if (anchorPi == null) { return Collections.emptyList(); } return SearchHelper.getFacetValues("+" + SolrConstants.PI_ANCHOR + ":" + anchorPi + " +" + SolrConstants._CALENDAR_DAY + ":*", SolrConstants._CALENDAR_Y...
@Test public void getVolumeYears_shouldOnlyReturnVolumeYearsThatHaveYEARMONTHDAYField() throws Exception { CalendarView cv = new CalendarView("168714434_1805", "168714434", null); List<String> years = cv.getVolumeYears(); Assert.assertEquals(9, years.size()); }
Sitemap { private Element createUrlElement(String pi, int order, String dateModified, String type, String changefreq, String priority) { return createUrlElement(viewerRootUrl + '/' + type + '/' + pi + '/' + order + '/', dateModified, changefreq, priority); } List<File> generate(String viewerRootUrl, String outputPath)...
@Test public void createUrlElement_shouldCreateLocElementCorrectly() throws Exception { Sitemap sitemap = new Sitemap(); Element eleUrl = sitemap.createUrlElement("https: Assert.assertNotNull(eleUrl); Assert.assertEquals("https: } @Test public void createUrlElement_shouldCreateLastmodElementCorrectly() throws Exception...
Sitemap { public List<File> generate(String viewerRootUrl, String outputPath) throws IOException, PresentationException, IndexUnreachableException, DAOException { this.viewerRootUrl = viewerRootUrl; docIndex.setRootElement(new Element("sitemapindex", nsSitemap)); index = -1; long timestampModified = 0; if (index == -1)...
@Test public void testSitemap() throws IOException, InterruptedException { int timeout = 20; Sitemap sitemap = new Sitemap(); Path path = Paths.get("sitemap_temp"); try { if (!Files.isDirectory(path)) { Files.createDirectory(path); } long start = System.nanoTime(); Thread thread = new Thread(() -> { try { sitemap.gener...
ViewerPathBuilder { public static boolean startsWith(URI uri, String string) { if (uri != null) { if (uri.toString().endsWith("/") && !string.endsWith("/")) { string = string + "/"; } String[] uriParts = uri.toString().split("/"); String[] stringParts = string.toString().split("/"); if (uriParts.length < stringParts.le...
@Test public void testStartsWith() { String url1 = "a"; String url2 = "a/b"; String url3 = "a/b/c"; String url4 = "f"; String url5 = "b/a"; String url6 = "a/bc"; URI uri = URI.create("a/b/cdef"); Assert.assertTrue(ViewerPathBuilder.startsWith(uri, url1)); Assert.assertTrue(ViewerPathBuilder.startsWith(uri, url2)); Asse...
AdvancedSearchFieldConfiguration { public String getLabel() { if (label == null) { return field; } return label; } AdvancedSearchFieldConfiguration(String field); String getField(); String getLabel(); AdvancedSearchFieldConfiguration setLabel(String label); boolean isHierarchical(); AdvancedSearchFieldConfiguration set...
@Test public void getLabel_shouldReturnFieldIfLabelNull() throws Exception { Assert.assertEquals("field", new AdvancedSearchFieldConfiguration("field").getLabel()); }
SearchFacets implements Serializable { static String generateFacetPrefix(List<FacetItem> facetItems, boolean escapeSlashes) { if (facetItems == null) { throw new IllegalArgumentException("facetItems may not be null"); } StringBuilder sb = new StringBuilder(); for (FacetItem facetItem : facetItems) { if (escapeSlashes) ...
@Test public void generateFacetPrefix_shouldEncodeSlashedAndBackslashes() throws Exception { List<FacetItem> list = new ArrayList<>(); list.add(new FacetItem("FIELD:a/b\\c", false)); Assert.assertEquals("FIELD:a/b\\c;;", SearchFacets.generateFacetPrefix(list, false)); Assert.assertEquals("FIELD:aU002FbU005Cc;;", Search...
SearchFacets implements Serializable { static void parseFacetString(String facetString, List<FacetItem> facetItems, Map<String, String> labelMap) { if (facetItems == null) { facetItems = new ArrayList<>(); } else { facetItems.clear(); } if (StringUtils.isEmpty(facetString) || "-".equals(facetString)) { return; } if (la...
@Test public void parseFacetString_shouldFillListCorrectly() throws Exception { List<FacetItem> facetItems = new ArrayList<>(); SearchFacets.parseFacetString("DC:a;;DC:b;;MD_TITLE:word;;", facetItems, null); Assert.assertEquals(3, facetItems.size()); Assert.assertEquals("DC", facetItems.get(0).getField()); Assert.asser...
UserTools { public static int deleteBookmarkListsForUser(User owner) throws DAOException { List<BookmarkList> bookmarkLists = DataManager.getInstance().getDao().getBookmarkLists(owner); if (bookmarkLists.isEmpty()) { return 0; } int count = 0; for (BookmarkList bookmarkList : bookmarkLists) { if (DataManager.getInstanc...
@Test public void deleteBookmarkListsForUser_shouldDeleteAllBookmarkListsOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertFalse(DataManager.getInstance().getDao().getBookmarkLists(user).isEmpty()); UserTools.deleteBookmarkListsForUser(u...
SearchFacets implements Serializable { public String getCurrentFacetString() { String ret = generateFacetPrefix(currentFacets, true); if (StringUtils.isEmpty(ret)) { ret = "-"; } try { return URLEncoder.encode(ret, SearchBean.URL_ENCODING); } catch (UnsupportedEncodingException e) { return ret; } } void resetAvailable...
@Test public void getCurrentFacetString_shouldReturnHyphenIfCurrentFacetsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); String facetString = facets.getCurrentFacetString(); Assert.assertEquals("-", facetString); }
SearchFacets implements Serializable { String generateFacetFilterQuery(boolean includeRangeFacets) { if (currentFacets.isEmpty()) { return null; } StringBuilder sbQuery = new StringBuilder(); for (FacetItem facetItem : currentFacets) { if (facetItem.isHierarchial()) { continue; } if (facetItem.getField().equals(SolrCon...
@Test public void generateFacetFilterQuery_shouldReturnNullIfFacetListIsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertNull(facets.generateFacetFilterQuery(true)); }
SearchFacets implements Serializable { String generateHierarchicalFacetFilterQuery(int advancedSearchGroupOperator) { if (currentFacets.isEmpty()) { return null; } StringBuilder sbQuery = new StringBuilder(); int count = 0; for (FacetItem facetItem : currentFacets) { if (!facetItem.isHierarchial()) { continue; } if (co...
@Test public void generateHierarchicalFacetFilterQuery_shouldReturnNullIfFacetListIsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertNull(facets.generateHierarchicalFacetFilterQuery(1)); }
SearchFacets implements Serializable { public boolean isHasWrongLanguageCode(String field, String language) { if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (language == null) { throw new IllegalArgumentException("language may not be null"); } if (field.contains(SolrConstants._LA...
@Test public void isHasWrongLanguageCode_shouldReturnTrueIfLanguageCodeDifferent() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertTrue(facets.isHasWrongLanguageCode("MD_TITLE_LANG_DE", "en")); } @Test public void isHasWrongLanguageCode_shouldReturnFalseIfLanguageCodeSame() throws Exception { ...
SearchFacets implements Serializable { public String updateFacetItem(String field, boolean hierarchical) { updateFacetItem(field, tempValue, currentFacets, hierarchical); return "pretty:search6"; } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(...
@Test public void updateFacetItem_shouldUpdateFacetItemCorrectly() throws Exception { List<FacetItem> items = new ArrayList<>(2); items.add(new FacetItem("FIELD1:foo", false)); items.add(new FacetItem("FIELD2:bar", false)); SearchFacets.updateFacetItem("FIELD2", "[foo TO bar]", items, false); Assert.assertEquals(2, ite...
FacetItem implements Comparable<FacetItem>, Serializable { public String getQueryEscapedLink() { String field = SearchHelper.facetifyField(this.field); String escapedValue = getEscapedValue(value); if (hierarchial) { return new StringBuilder("(").append(field) .append(':') .append(escapedValue) .append(" OR ") .append(...
@Test public void getQueryEscapedLink_shouldConstructLinkCorrectly() throws Exception { FacetItem item = new FacetItem("FIELD:value", false); Assert.assertEquals("FIELD:value", item.getQueryEscapedLink()); } @Test public void getQueryEscapedLink_shouldEscapeValuesContainingWhitespaces() throws Exception { FacetItem ite...
UserTools { public static int deleteSearchesForUser(User owner) throws DAOException { List<Search> searches = DataManager.getInstance().getDao().getSearches(owner); if (searches.isEmpty()) { return 0; } int count = 0; for (Search search : searches) { if (DataManager.getInstance().getDao().deleteSearch(search)) { count+...
@Test public void deleteSearchesForUser_shouldDeleteAllSearchesOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertFalse(DataManager.getInstance().getDao().getSearches(user).isEmpty()); UserTools.deleteSearchesForUser(user); Assert.assertT...
FacetItem implements Comparable<FacetItem>, Serializable { static String getEscapedValue(String value) { if (StringUtils.isEmpty(value)) { return value; } String escapedValue = null; if (value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"' && value.length() > 2) { escapedValue = '"' + ClientUtils.escapeQue...
@Test public void getEscapedValue_shouldEscapeValueCorrectly() throws Exception { Assert.assertEquals("\\(foo\\)", FacetItem.getEscapedValue("(foo)")); } @Test public void getEscapedValue_shouldAddQuotationMarksIfValueContainsSpace() throws Exception { Assert.assertEquals("\"foo\\ bar\"", FacetItem.getEscapedValue("foo...
BrowseElement implements Serializable { static String generateDefaultLabel(StructElement se, Locale locale) { String ret = null; if (locale != null) { String englishTitle = null; String germanTitle = null; String anyTitle = null; for (String key : se.getMetadataFields().keySet()) { if (key.equals(SolrConstants.TITLE + ...
@Test public void generateDefaultLabel_shouldTranslateDocstructLabel() throws Exception { BrowseElement be = new BrowseElement("PPN123", 1, null, null, Locale.GERMAN, null, null); StructElement se = new StructElement(); se.setDocStructType("Monograph"); String label = BrowseElement.generateDefaultLabel(se, Locale.GERMA...
BrowseElement implements Serializable { public String getFulltextForHtml() { if (fulltextForHtml == null) { if (fulltext != null) { fulltextForHtml = StringTools.stripJS(fulltext).replaceAll("\n", " "); } else { fulltextForHtml = ""; } } return fulltextForHtml; } BrowseElement(String pi, int imageNo, String label, Stri...
@Test public void getFulltextForHtml_shouldRemoveAnyLineBreaks() throws Exception { BrowseElement be = new BrowseElement(null, 1, "FROM FOO TO BAR", "foo\nbar", Locale.ENGLISH, null, null); Assert.assertEquals("foo bar", be.getFulltextForHtml()); } @Test public void getFulltextForHtml_shouldRemoveAnyJS() throws Excepti...
SearchHelper { public static List<String> searchAutosuggestion(String suggest, List<FacetItem> currentFacets) throws IndexUnreachableException { if (suggest.contains(" ")) { return Collections.emptyList(); } List<String> ret = new ArrayList<>(); try { suggest = suggest.toLowerCase(); StringBuilder sbQuery = new StringB...
@Test public void searchAutosuggestion_shouldReturnAutosuggestionsCorrectly() throws Exception { List<String> values = SearchHelper.searchAutosuggestion("klein", null); Assert.assertFalse(values.isEmpty()); } @Test public void searchAutosuggestion_shouldFilterByCollectionCorrectly() throws Exception { FacetItem item = ...
UserTools { public static int deleteUserGroupOwnedByUser(User owner) throws DAOException { List<UserGroup> userGroups = owner.getUserGroupOwnerships(); if (userGroups.isEmpty()) { return 0; } int count = 0; for (UserGroup userGroup : userGroups) { if (!userGroup.getMemberships().isEmpty()) { for (UserRole userRole : us...
@Test public void deleteUserGroupOwnedByUser_shouldDeleteAllUserGroupsOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertNotNull(DataManager.getInstance().getDao().getUserGroup(1)); UserTools.deleteUserGroupOwnedByUser(user); Assert.asser...
SearchHelper { public static Map<String, CollectionResult> findAllCollectionsFromField(String luceneField, String facetField, String filterQuery, boolean filterForWhitelist, boolean filterForBlacklist, String splittingChar) throws IndexUnreachableException { logger.trace("findAllCollectionsFromField: {}", luceneField);...
@Test public void findAllCollectionsFromField_shouldFindAllCollections() throws Exception { Map<String, CollectionResult> collections = SearchHelper.findAllCollectionsFromField(SolrConstants.DC, SolrConstants.DC, null, true, true, "."); Assert.assertTrue(collections.size() > 40); List<String> keys = new ArrayList<>(col...
SearchHelper { public static String getPersonalFilterQuerySuffix(User user, String ipAddress) throws IndexUnreachableException, PresentationException, DAOException { if (user != null && user.isSuperuser()) { return ""; } if (NetTools.isIpAddressLocalhost(ipAddress) && DataManager.getInstance().getConfiguration().isFull...
@Test public void getPersonalFilterQuerySuffix_shouldConstructSuffixCorrectly() throws Exception { String suffix = SearchHelper.getPersonalFilterQuerySuffix(null, null); Assert.assertEquals( " +(ACCESSCONDITION:\"OPENACCESS\"" + " ACCESSCONDITION:\"license type 2 name\"" + " (+ACCESSCONDITION:\"restriction on access\" ...
SearchHelper { public static List<String> truncateFulltext(Set<String> searchTerms, String fulltext, int targetFragmentLength, boolean firstMatchOnly, boolean addFragmentIfNoMatches) { if (fulltext == null) { throw new IllegalArgumentException("fulltext may not be null"); } fulltext = Jsoup.parse(fulltext).text(); List...
@Test public void truncateFulltext_shouldMakeTermsBoldIfFoundInText() throws Exception { String original = LOREM_IPSUM; String[] terms = { "ipsum", "tempor", "labore" }; List<String> truncated = SearchHelper.truncateFulltext(new HashSet<>(Arrays.asList(terms)), original, 200, true, true); Assert.assertFalse(truncated.i...
UserTools { public static void deleteUserPublicContributions(User user) throws DAOException { if (user == null) { return; } int comments = DataManager.getInstance().getDao().deleteComments(null, user); logger.debug("{} comment(s) of user {} deleted.", comments, user.getId()); int statistics = DataManager.getInstance()....
@Test public void deleteUserPublicContributions_shouldDeleteAllUserPublicContentCorrectly() throws Exception { User user = DataManager.getInstance().getDao().getUser(2); Assert.assertNotNull(user); UserTools.deleteUserPublicContributions(user); Assert.assertNull(DataManager.getInstance().getDao().getComment(2)); List<C...
SearchHelper { public static Map<String, Set<String>> extractSearchTermsFromQuery(String query, String discriminatorValue) { if (query == null) { throw new IllegalArgumentException("query may not be null"); } Map<String, Set<String>> ret = new HashMap<>(); Set<String> stopwords = DataManager.getInstance().getConfigurat...
@Test public void extractSearchTermsFromQuery_shouldExtractAllValuesFromQueryExceptFromNOTBlocks() throws Exception { Map<String, Set<String>> result = SearchHelper.extractSearchTermsFromQuery( "(MD_X:value1 OR MD_X:value2 OR (SUPERDEFAULT:value3 AND :value4:)) AND SUPERFULLTEXT:\"hello-world\" AND SUPERUGCTERMS:\"comm...
UserTools { public static boolean anonymizeUserPublicContributions(User user) throws DAOException { User anon = UserTools.checkAndCreateAnonymousUser(); if (anon == null) { logger.error("Anonymous user could not be found"); return false; } int comments = DataManager.getInstance().getDao().changeCommentsOwner(user, anon...
@Test public void anonymizeUserPublicContributions_shouldAnonymizeAllUserPublicContentCorrectly() throws Exception { User user = DataManager.getInstance().getDao().getUser(2); Assert.assertNotNull(user); Assert.assertTrue(UserTools.anonymizeUserPublicContributions(user)); Comment comment = DataManager.getInstance().get...
SearchHelper { protected static String generateCollectionBlacklistFilterSuffix(String field) { logger.debug("Generating blacklist suffix for field '{}'...", field); StringBuilder sbQuery = new StringBuilder(); List<String> list = DataManager.getInstance().getConfiguration().getCollectionBlacklist(field); if (list != nu...
@Test public void generateCollectionBlacklistFilterSuffix_shouldConstructSuffixCorrectly() throws Exception { String suffix = SearchHelper.generateCollectionBlacklistFilterSuffix(SolrConstants.DC); Assert.assertEquals(" -" + SolrConstants.DC + ":collection1 -" + SolrConstants.DC + ":collection2", suffix); }
SearchHelper { protected static boolean checkCollectionInBlacklist(String dc, Set<String> blacklist, String splittingChar) { if (dc == null) { throw new IllegalArgumentException("dc may not be null"); } if (blacklist == null) { throw new IllegalArgumentException("blacklist may not be null"); } if (splittingChar == null...
@Test public void checkCollectionInBlacklist_shouldMatchSimpleCollectionsCorrectly() throws Exception { { Set<String> blacklist = new HashSet<>(Collections.singletonList("a")); Assert.assertTrue(SearchHelper.checkCollectionInBlacklist("a", blacklist, ".")); Assert.assertFalse(SearchHelper.checkCollectionInBlacklist("z"...
SearchHelper { public static String getDiscriminatorFieldFilterSuffix(NavigationHelper nh, String discriminatorField) throws IndexUnreachableException { logger.trace("discriminatorField: {}", discriminatorField); if (StringUtils.isNotEmpty(discriminatorField) && nh != null) { String discriminatorValue = nh.getSubThemeD...
@Test public void getDiscriminatorFieldFilterSuffix_shouldConstructSubqueryCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.setSubThemeDiscriminatorValue("val"); Assert.assertEquals(" +fie:val", SearchHelper.getDiscriminatorFieldFilterSuffix(nh, "fie")); } @Test public void getDiscriminat...
SearchHelper { public static String defacetifyField(String fieldName) { if (fieldName == null) { return null; } switch (fieldName) { case SolrConstants.FACET_DC: case "FACET_" + SolrConstants.DOCSTRCT: case "FACET_" + SolrConstants.DOCSTRCT_SUB: case "FACET_" + SolrConstants.DOCSTRCT_TOP: return fieldName.substring(6);...
@Test public void defacetifyField_shouldDefacetifyCorrectly() throws Exception { Assert.assertEquals(SolrConstants.DC, SearchHelper.defacetifyField(SolrConstants.FACET_DC)); Assert.assertEquals(SolrConstants.DOCSTRCT, SearchHelper.defacetifyField("FACET_DOCSTRCT")); Assert.assertEquals("MD_TITLE", SearchHelper.defaceti...
SearchHelper { public static String facetifyField(String fieldName) { return adaptField(fieldName, "FACET_"); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultFields, List<String> filterQueries, Map<String, String> params, Map<St...
@Test public void facetifyField_shouldFacetifyCorrectly() throws Exception { Assert.assertEquals(SolrConstants.FACET_DC, SearchHelper.facetifyField(SolrConstants.DC)); Assert.assertEquals("FACET_DOCSTRCT", SearchHelper.facetifyField(SolrConstants.DOCSTRCT)); Assert.assertEquals("FACET_TITLE", SearchHelper.facetifyField...
UserGroup implements ILicensee, Serializable { public long getMemberCount() throws DAOException { return DataManager.getInstance().getDao().getUserRoleCount(this, null, null); } @Override int hashCode(); @Override boolean equals(Object obj); boolean addMember(User user, Role role); boolean changeMemberRole(User user, ...
@Test public void getMemberCount_shouldCountCorrectly() throws Exception { UserGroup ug = DataManager.getInstance().getDao().getUserGroup(1); Assert.assertNotNull(ug); Assert.assertEquals(1, ug.getMemberCount()); }
SearchHelper { public static List<String> facetifyList(List<String> sourceList) { if (sourceList == null) { return null; } List<String> ret = new ArrayList<>(sourceList.size()); for (String s : sourceList) { String fieldName = facetifyField(s); if (fieldName != null) { ret.add(fieldName); } } return ret; } static List...
@Test public void facetifyList_shouldFacetifyCorrectly() throws Exception { List<String> result = SearchHelper.facetifyList(Arrays.asList(new String[] { SolrConstants.DC, "MD_TITLE_UNTOKENIZED" })); Assert.assertEquals(2, result.size()); Assert.assertEquals(SolrConstants.FACET_DC, result.get(0)); Assert.assertEquals("F...
SearchHelper { public static String sortifyField(String fieldName) { return adaptField(fieldName, "SORT_"); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultFields, List<String> filterQueries, Map<String, String> params, Map<Stri...
@Test public void sortifyField_shouldSortifyCorrectly() throws Exception { Assert.assertEquals("SORT_DC", SearchHelper.sortifyField(SolrConstants.DC)); Assert.assertEquals("SORT_DOCSTRCT", SearchHelper.sortifyField(SolrConstants.DOCSTRCT)); Assert.assertEquals("SORT_TITLE", SearchHelper.sortifyField("MD_TITLE_UNTOKENIZ...
SearchHelper { public static String normalizeField(String fieldName) { return adaptField(fieldName, null); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultFields, List<String> filterQueries, Map<String, String> params, Map<Strin...
@Test public void normalizeField_shouldNormalizeCorrectly() throws Exception { Assert.assertEquals("MD_FOO", SearchHelper.normalizeField("MD_FOO_UNTOKENIZED")); }
SearchHelper { static String adaptField(String fieldName, String prefix) { if (fieldName == null) { return null; } if (prefix == null) { prefix = ""; } switch (fieldName) { case SolrConstants.DC: case SolrConstants.DOCSTRCT: case SolrConstants.DOCSTRCT_SUB: case SolrConstants.DOCSTRCT_TOP: return prefix + fieldName; de...
@Test public void adaptField_shouldApplyPrefixCorrectly() throws Exception { Assert.assertEquals("SORT_DC", SearchHelper.adaptField(SolrConstants.DC, "SORT_")); Assert.assertEquals("SORT_FOO", SearchHelper.adaptField("MD_FOO", "SORT_")); } @Test public void adaptField_shouldNotApplyPrefixToRegularFieldsIfEmpty() throws...
SearchHelper { public static String getAllSuffixes(HttpServletRequest request, boolean addStaticQuerySuffix, boolean addCollectionBlacklistSuffix) throws IndexUnreachableException { StringBuilder sbSuffix = new StringBuilder(""); if (addStaticQuerySuffix && StringUtils.isNotBlank(DataManager.getInstance().getConfigurat...
@Test public void getAllSuffixes_shouldAddStaticSuffix() throws Exception { String suffix = SearchHelper.getAllSuffixes(null, true, false); Assert.assertNotNull(suffix); Assert.assertTrue(suffix.contains(DataManager.getInstance().getConfiguration().getStaticQuerySuffix())); } @Test public void getAllSuffixes_shouldNotA...
SearchHelper { public static String generateExpandQuery(List<String> fields, Map<String, Set<String>> searchTerms, boolean phraseSearch) { logger.trace("generateExpandQuery"); StringBuilder sbOuter = new StringBuilder(); if (!searchTerms.isEmpty()) { logger.trace("fields: {}", fields.toString()); logger.trace("searchTe...
@Test public void generateExpandQuery_shouldGenerateQueryCorrectly() throws Exception { List<String> fields = Arrays.asList(new String[] { SolrConstants.DEFAULT, SolrConstants.FULLTEXT, SolrConstants.NORMDATATERMS, SolrConstants.UGCTERMS, SolrConstants.CMS_TEXT_ALL }); Map<String, Set<String>> searchTerms = new HashMap...
UserGroup implements ILicensee, Serializable { public Set<User> getMembersAndOwner() throws DAOException { Set<User> ret = new HashSet<>(getMembers()); ret.add(getOwner()); return ret; } @Override int hashCode(); @Override boolean equals(Object obj); boolean addMember(User user, Role role); boolean changeMemberRole(Us...
@Test public void getMembersAndOwner_shouldReturnAllMembersAndOwner() throws Exception { UserGroup ug = DataManager.getInstance().getDao().getUserGroup(1); Assert.assertNotNull(ug); Assert.assertEquals(2, ug.getMembersAndOwner().size()); }
SearchHelper { public static String generateAdvancedExpandQuery(List<SearchQueryGroup> groups, int advancedSearchGroupOperator) { logger.trace("generateAdvancedExpandQuery"); if (groups == null || groups.isEmpty()) { return ""; } StringBuilder sbOuter = new StringBuilder(); for (SearchQueryGroup group : groups) { Strin...
@Test public void generateAdvancedExpandQuery_shouldGenerateQueryCorrectly() throws Exception { List<SearchQueryGroup> groups = new ArrayList<>(2); { SearchQueryGroup group = new SearchQueryGroup(null, 2); group.setOperator(SearchQueryGroupOperator.AND); group.getQueryItems().get(0).setOperator(SearchItemOperator.AND);...
SearchHelper { public static SXSSFWorkbook exportSearchAsExcel(String finalQuery, String exportQuery, List<StringPair> sortFields, List<String> filterQueries, Map<String, String> params, Map<String, Set<String>> searchTerms, Locale locale, boolean aggregateHits, HttpServletRequest request) throws IndexUnreachableExcept...
@Test public void exportSearchAsExcel_shouldCreateExcelWorkbookCorrectly() throws Exception { String query = "DOCSTRCT:monograph AND MD_YEARPUBLISH:18*"; SXSSFWorkbook wb = SearchHelper.exportSearchAsExcel(query, query, Collections.singletonList(new StringPair("SORT_YEARPUBLISH", "asc")), null, null, new HashMap<String...
SearchHelper { public static String applyHighlightingToPhrase(String phrase, Set<String> terms) { if (phrase == null) { throw new IllegalArgumentException("phrase may not be null"); } if (terms == null) { throw new IllegalArgumentException("terms may not be null"); } String highlightedValue = phrase; for (String term :...
@Test public void applyHighlightingToPhrase_shouldApplyHighlightingForAllTerms() throws Exception { { String phrase = "FOO BAR Foo Bar foo bar"; Set<String> terms = new HashSet<>(); terms.add("foo"); terms.add("bar"); String highlightedPhrase = SearchHelper.applyHighlightingToPhrase(phrase, terms); Assert.assertEquals(...
LicenseType implements IPrivilegeHolder { public String getProcessedConditions() { String conditions = this.conditions; conditions = getQueryConditions(conditions); conditions = SolrSearchIndex.getProcessedConditions(conditions); return conditions.trim(); } LicenseType(); LicenseType(String name); @Override int hashCo...
@Test public void testGetProcessedConditions() { LicenseType type = new LicenseType(); type.setConditions("FILENAME:{" + CONDITION_FILENAME_1 + "}"); Assert.assertTrue("processed conditions are " + type.getProcessedConditions(), StringUtils.isBlank(type.getProcessedConditions())); type.setConditions("FILENAME:{" + COND...
SearchHelper { static String applyHighlightingToTerm(String term) { return new StringBuilder(PLACEHOLDER_HIGHLIGHTING_START).append(term).append(PLACEHOLDER_HIGHLIGHTING_END).toString(); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultField...
@Test public void applyHighlightingToTerm_shouldAddSpanCorrectly() throws Exception { Assert.assertEquals(SearchHelper.PLACEHOLDER_HIGHLIGHTING_START + "foo" + SearchHelper.PLACEHOLDER_HIGHLIGHTING_END, SearchHelper.applyHighlightingToTerm("foo")); }
SearchHelper { public static String replaceHighlightingPlaceholders(String phrase) { return phrase.replace(PLACEHOLDER_HIGHLIGHTING_START, "<span class=\"search-list--highlight\">") .replace(PLACEHOLDER_HIGHLIGHTING_END, "</span>"); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<St...
@Test public void replaceHighlightingPlaceholders_shouldReplacePlaceholdersWithHtmlTags() throws Exception { Assert.assertEquals("<span class=\"search-list--highlight\">foo</span>", SearchHelper .replaceHighlightingPlaceholders(SearchHelper.PLACEHOLDER_HIGHLIGHTING_START + "foo" + SearchHelper.PLACEHOLDER_HIGHLIGHTING_...
SearchHelper { public static String prepareQuery(String query) { StringBuilder sbQuery = new StringBuilder(); if (StringUtils.isNotEmpty(query)) { sbQuery.append('(').append(query).append(')'); } else { String docstructWhitelistFilterQuery = getDocstrctWhitelistFilterQuery(); if (StringUtils.isNotEmpty(docstructWhiteli...
@Test public void prepareQuery_shouldPrepareNonemptyQueriesCorrectly() throws Exception { Assert.assertEquals("(FOO:bar)", SearchHelper.prepareQuery("FOO:bar", null)); } @Test public void prepareQuery_shouldPrepareEmptyQueriesCorrectly() throws Exception { Assert.assertEquals("(ISWORK:true OR ISANCHOR:true) AND BLA:blu...
SearchHelper { public static List<StringPair> parseSortString(String sortString, NavigationHelper navigationHelper) { List<StringPair> ret = new ArrayList<>(); if (StringUtils.isNotEmpty(sortString)) { String[] sortStringSplit = sortString.split(";"); if (sortStringSplit.length > 0) { for (String field : sortStringSpli...
@Test public void parseSortString_shouldParseStringCorrectly() throws Exception { String sortString = "!SORT_1;SORT_2;SORT_3"; Assert.assertEquals(3, SearchHelper.parseSortString(sortString, null).size()); }
SearchHelper { public static String removeHighlightingTags(String phrase) { return phrase.replace("<span class=\"search-list--highlight\">", "").replace("</span>", ""); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultFields, Lis...
@Test public void removeHighlightingTags_shouldRemoveHtmlTags() throws Exception { Assert.assertEquals("foo bar", SearchHelper .removeHighlightingTags("f<span class=\"search-list--highlight\">oo</span> <span class=\"search-list--highlight\">bar</span>")); }
LicenseType implements IPrivilegeHolder { public String getFilenameConditions() { return getFilenameConditions(this.conditions); } LicenseType(); LicenseType(String name); @Override int hashCode(); @Override boolean equals(Object obj); Long getId(); void setId(Long id); String getName(); void setName(String name); Str...
@Test public void testGetFilenameConditions() { LicenseType type = new LicenseType(); type.setConditions("FILENAME:{" + CONDITION_FILENAME_1 + "}"); Assert.assertTrue("filename conditions are " + type.getFilenameConditions(), type.getFilenameConditions().equals(CONDITION_FILENAME_1)); type.setConditions("FILENAME:{" + ...
SearchHelper { public static String cleanUpSearchTerm(String s) { if (StringUtils.isNotEmpty(s)) { boolean addNegation = false; boolean addLeftTruncation = false; boolean addRightTruncation = false; if (s.charAt(0) == '-') { addNegation = true; s = s.substring(1); } else if (s.charAt(0) == '*') { addLeftTruncation = tr...
@Test public void cleanUpSearchTerm_shouldRemoveIllegalCharsCorrectly() throws Exception { Assert.assertEquals("a", SearchHelper.cleanUpSearchTerm("(a)")); } @Test public void cleanUpSearchTerm_shouldPreserveTruncation() throws Exception { Assert.assertEquals("*a*", SearchHelper.cleanUpSearchTerm("*a*")); } @Test publi...
SearchHelper { static String normalizeString(String string) { if (string == null) { return null; } string = Normalizer.normalize(string, Normalizer.Form.NFD); string = string.toLowerCase().replaceAll("\\p{M}", "").replaceAll("[^\\p{L}0-9#]", " "); string = Normalizer.normalize(string, Normalizer.Form.NFC); return strin...
@Test public void normalizeString_shouldPreserveDigits() throws Exception { Assert.assertEquals("1 2 3", SearchHelper.normalizeString("1*2*3")); } @Test public void normalizeString_shouldPreserveLatinChars() throws Exception { Assert.assertEquals("f o obar", SearchHelper.normalizeString("F*O*Obar")); }
SearchHelper { public static String buildFinalQuery(String rawQuery, boolean aggregateHits) throws IndexUnreachableException { return buildFinalQuery(rawQuery, aggregateHits, null); } static List<SearchHit> searchWithFulltext(String query, int first, int rows, List<StringPair> sortFields, List<String> resultFields, ...
@Test public void testBuildFinalQuery() throws IndexUnreachableException, PresentationException { String query = "DC:dctei"; String finalQuery = SearchHelper.buildFinalQuery(query, false, null); SolrDocumentList docs = DataManager.getInstance().getSearchIndex().search(finalQuery); Assert.assertEquals(65, docs.size()); ...
SearchHelper { public static List<BrowseTerm> getFilteredTerms(BrowsingMenuFieldConfig bmfc, String startsWith, String filterQuery, int start, int rows, Comparator<BrowseTerm> comparator, boolean aggregateHits) throws PresentationException, IndexUnreachableException { if (bmfc == null) { throw new IllegalArgumentExcept...
@Test public void getFilteredTerms_shouldBeThreadSafeWhenCountingTerms() throws Exception { int previousSize = -1; Map<String, Long> previousCounts = new HashMap<>(); BrowsingMenuFieldConfig bmfc = new BrowsingMenuFieldConfig("MD_LANGUAGE_UNTOKENIZED", null, null, false, false, false); for (int i = 0; i < 100; ++i) { L...
SearchHelper { public static Map<String, String> generateQueryParams() { Map<String, String> params = new HashMap<>(); if (DataManager.getInstance().getConfiguration().isAggregateHits()) { return params; } if (DataManager.getInstance().getConfiguration().isGroupDuplicateHits()) { params.put(GroupParams.GROUP, "true"); ...
@Test public void generateQueryParams_shouldReturnEmptyMapIfSearchHitAggregationOn() throws Exception { DataManager.getInstance().getConfiguration().overrideValue("search.aggregateHits", true); Map<String, String> params = SearchHelper.generateQueryParams(); }
BrowseTermComparator implements Comparator<BrowseTerm>, Serializable { @Override public int compare(BrowseTerm o1, BrowseTerm o2) { BrowseTerm o1a = o1; BrowseTerm o2a = o2; String relevantString1 = o1a.getTerm(); if (StringUtils.isNotEmpty(relevantString1)) { if (o1a.getSortTerm() != null) { relevantString1 = o1a.getS...
@Test public void compare_shouldCompareCorrectly() throws Exception { BrowseTermComparator comparator = new BrowseTermComparator(null); Assert.assertEquals(1, comparator.compare(new BrowseTerm("foo", null, null), new BrowseTerm("bar", null, null))); Assert.assertEquals(-1, comparator.compare(new BrowseTerm("A", null, n...
BibliothecaAuthenticationRequest extends UserPasswordAuthenticationRequest { static String normalizeUsername(String username) { if (username == null || username.length() == 11) { return username; } if (username.length() < 11) { StringBuilder sb = new StringBuilder(11); for (int i = username.length(); i < 11; ++i) { sb....
@Test public void normalizeUsername_shouldNormalizeValueCorrectly() throws Exception { Assert.assertEquals("00001234567", BibliothecaAuthenticationRequest.normalizeUsername("1234567")); }
BrowseTermComparator implements Comparator<BrowseTerm>, Serializable { public static String normalizeString(String s, String ignoreChars) { if (s == null) { return null; } if (StringUtils.isNotEmpty(ignoreChars)) { while (s.length() > 1 && ignoreChars.contains(s.substring(0, 1))) { s = s.substring(1); } } else { if (s....
@Test public void normalizeString_shouldUseIgnoreCharsIfProvided() throws Exception { Assert.assertEquals("#.foo", BrowseTermComparator.normalizeString("[.]#.foo", ".[]")); } @Test public void normalizeString_shouldRemoveFirstCharIfNonAlphanumIfIgnoreCharsNotProvided() throws Exception { Assert.assertEquals(".]#.foo", ...
DownloadJob implements Serializable { public static String generateDownloadJobId(String... criteria) { StringBuilder sbCriteria = new StringBuilder(criteria.length * 10); for (String criterion : criteria) { if (criterion != null) { sbCriteria.append(criterion); } } return StringTools.generateMD5(sbCriteria.toString());...
@Test public void generateDownloadJobId_shouldGenerateSameIdFromSameCriteria() throws Exception { String hash = "78acb5991aaf0fee0329b673e985ce82"; String crit1 = "PPN123456789"; String crit2 = "LOG_0000"; Assert.assertEquals(hash, DownloadJob.generateDownloadJobId(crit1, crit2)); Assert.assertEquals(hash, DownloadJob....
NavigationHelper implements Serializable { public String getCurrentPartnerPage() { return statusMap.get(KEY_CURRENT_PARTNER_PAGE); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage()...
@Test public void getCurrentPartnerPage_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put(NavigationHelper.KEY_CURRENT_PARTNER_PAGE, NavigationHelper.KEY_CURRENT_PARTNER_PAGE + "_value"); Assert.assertEquals(NavigationHelper.KEY_CURRENT_PARTNER_PAGE + "_value...
NavigationHelper implements Serializable { public String getCurrentView() { return statusMap.get(KEY_CURRENT_VIEW); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage(); boolean isCms...
@Test public void getCurrentView_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put(NavigationHelper.KEY_CURRENT_VIEW, NavigationHelper.KEY_CURRENT_VIEW + "_value"); Assert.assertEquals(NavigationHelper.KEY_CURRENT_VIEW + "_value", nh.getCurrentView()); }
NavigationHelper implements Serializable { public String getMenuPage() { return statusMap.get(KEY_MENU_PAGE); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage(); boolean isCmsPage()...
@Test public void getMenuPage_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put(NavigationHelper.KEY_MENU_PAGE, NavigationHelper.KEY_MENU_PAGE + "_value"); Assert.assertEquals(NavigationHelper.KEY_MENU_PAGE + "_value", nh.getMenuPage()); }
NavigationHelper implements Serializable { public String getPreferredView() { return statusMap.get(KEY_PREFERRED_VIEW); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage(); boolean i...
@Test public void getPreferredView_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put(NavigationHelper.KEY_PREFERRED_VIEW, NavigationHelper.KEY_PREFERRED_VIEW + "_value"); Assert.assertEquals(NavigationHelper.KEY_PREFERRED_VIEW + "_value", nh.getPreferredView(...
NavigationHelper implements Serializable { public String getSelectedNewsArticle() { return statusMap.get(KEY_SELECTED_NEWS_ARTICLE); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage...
@Test public void getSelectedNewsArticle_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put(NavigationHelper.KEY_SELECTED_NEWS_ARTICLE, NavigationHelper.KEY_SELECTED_NEWS_ARTICLE + "_value"); Assert.assertEquals(NavigationHelper.KEY_SELECTED_NEWS_ARTICLE + "_v...
LitteraProvider extends HttpAuthenticationProvider { @Override public CompletableFuture<LoginResult> login(String loginName, String password) throws AuthenticationProviderException { try { LitteraAuthenticationResponse response = get(new URI(getUrl()), loginName, password); Optional<User> user = getUser(loginName, resp...
@Test public void testLogin() throws AuthenticationProviderException, InterruptedException, ExecutionException { Assert.assertFalse(provider.login(user_id, user_pw).get().isRefused()); Assert.assertTrue(provider.login(user_id_invalid, user_pw).get().isRefused()); Assert.assertTrue(provider.login(user_id, user_pw_invali...
NavigationHelper implements Serializable { public String getStatusMapValue(String key) { return statusMap.get(key); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); String searchPage(); String homePage(); String browsePage(); String getCurrentPage(); boolean isCms...
@Test public void getStatusMapValue_shouldReturnValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.statusMap.put("new_key", "new_value"); Assert.assertEquals("new_value", nh.getStatusMapValue("new_key")); }
NavigationHelper implements Serializable { public void setCurrentPartnerPage(String currentPartnerPage) { statusMap.put(KEY_CURRENT_PARTNER_PAGE, currentPartnerPage); logger.trace("current Partner Page: {}", currentPartnerPage); } NavigationHelper(); @PostConstruct void init(); void setBreadcrumbBean(BreadcrumbBean bre...
@Test public void setCurrentPartnerPage_shouldSetValueCorrectly() throws Exception { NavigationHelper nh = new NavigationHelper(); nh.setCurrentPartnerPage(NavigationHelper.KEY_CURRENT_PARTNER_PAGE + "_value"); Assert.assertEquals(NavigationHelper.KEY_CURRENT_PARTNER_PAGE + "_value", nh.statusMap.get(NavigationHelper.K...