src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Configuration extends AbstractConfiguration { public int getTocIndentation() { return getLocalInt("toc.tocIndentation", 20); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnailsPerPage(... | @Test public void getTocIndentation_shouldReturnCorrectValue() throws Exception { Assert.assertEquals(15, DataManager.getInstance().getConfiguration().getTocIndentation()); } |
Configuration extends AbstractConfiguration { public String getTranskribusUserName() { return getLocalString("transkribus.userName"); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnail... | @Test public void getTranskribusUserName_shouldReturnCorrectValue() throws Exception { Assert.assertEquals("transkribus_user", DataManager.getInstance().getConfiguration().getTranskribusUserName()); } |
MetadataTools { public static String convertLanguageToIso2(String language) { if (language == null) { return null; } if (language.length() == 3) { Language lang = null; try { lang = DataManager.getInstance().getLanguageHelper().getLanguage(language); } catch (IllegalArgumentException e) { logger.warn("No language found... | @Test public void convertLanguageToIso2_shouldReturnOriginalValueIfLanguageNotFound() throws Exception { Assert.assertEquals("###", MetadataTools.convertLanguageToIso2("###")); } |
Configuration extends AbstractConfiguration { public String getTranskribusPassword() { return getLocalString("transkribus.password"); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnail... | @Test public void getTranskribusPassword_shouldReturnCorrectValue() throws Exception { Assert.assertEquals("transkribus_pwd", DataManager.getInstance().getConfiguration().getTranskribusPassword()); } |
Configuration extends AbstractConfiguration { public String getDfgViewerUrl() { return getLocalString("urls.dfg-viewer", "https: } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnailsPerP... | @Test public void getDfgViewerUrl_shouldReturnCorrectValue() throws Exception { Assert.assertEquals("dfg-viewer_value", DataManager.getInstance().getConfiguration().getDfgViewerUrl()); } |
Configuration extends AbstractConfiguration { public boolean isDisplayCrowdsourcingModuleLinks() { return this.getLocalBoolean("webGuiDisplay.displayCrowdsourcingModuleLinks", false); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String get... | @Test public void isDisplayCrowdsourcingModuleLinks_shouldReturnCorrectValue() throws Exception { Assert.assertTrue(DataManager.getInstance().getConfiguration().isDisplayCrowdsourcingModuleLinks()); } |
Configuration extends AbstractConfiguration { public boolean isSearchInItemEnabled() { return getLocalBoolean("sidebar.searchInItem.visible", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int get... | @Test public void isSearchInItemEnabled_shouldReturnTrueIfTheSearchFieldToSearchTheCurrentItemworkIsConfiguredToBeVisible() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isSearchInItemEnabled()); } |
Configuration extends AbstractConfiguration { public boolean isUseReCaptcha() { return getLocalBoolean("reCaptcha[@show]", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnailsPer... | @Test public void isUseReCaptcha_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isUseReCaptcha()); } |
Configuration extends AbstractConfiguration { public String getWebApiToken() { String token = getLocalString("webapi.authorization.token", ""); return token; } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile()... | @Test public void getWebApiToken_shouldReturnCorrectValue() throws Exception { Assert.assertEquals("test", DataManager.getInstance().getConfiguration().getWebApiToken()); } |
Configuration extends AbstractConfiguration { public boolean isAddCORSHeader() { return getLocalBoolean("webapi.cors[@use]", false); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnails... | @Test public void isAddCORSHeader_shouldReturnCorrectValue() throws Exception { Assert.assertTrue(DataManager.getInstance().getConfiguration().isAddCORSHeader()); } |
Configuration extends AbstractConfiguration { public boolean isAllowRedirectCollectionToWork() { boolean redirect = getLocalBoolean("collections.redirectToWork", true); return redirect; } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String g... | @Test public void isAllowRedirectCollectionToWork_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isAllowRedirectCollectionToWork()); } |
Configuration extends AbstractConfiguration { public boolean isLimitImageHeight() { return getLocalBoolean("viewer.limitImageHeight", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerTh... | @Test public void isLimitImageHeight_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isLimitImageHeight()); } |
Metadata implements Serializable { static String buildHierarchicalValue(String field, String value, Locale locale, String applicationUrl) { String[] valueSplit = value.split("[.]"); StringBuilder sbFullValue = new StringBuilder(); StringBuilder sbHierarchy = new StringBuilder(); for (String s : valueSplit) { if (sbFull... | @Test public void buildHierarchicalValue_shouldBuildValueCorrectly() throws Exception { { String value = Metadata.buildHierarchicalValue("DC", "a.b", null, "http: Assert.assertEquals( "<a href=\"http: value); } { String value = Metadata.buildHierarchicalValue("DC", "a.b.c.d", null, null); Assert.assertEquals("a > a.b >... |
Comment implements Comparable<Comment> { public boolean mayEdit(User user) { return owner.getId() != null && user != null && owner.getId() == user.getId(); } Comment(); Comment(String pi, int page, User owner, String text, Comment parent); @Override int compareTo(Comment o); static boolean sendEmailNotifications(Comme... | @Test public void mayEdit_shouldReturnFalseIfOwnerIdIsNull() throws Exception { User owner = new User(); Comment comment = new Comment("PPN123", 1, owner, "comment text", null); Assert.assertFalse(comment.mayEdit(owner)); }
@Test public void mayEdit_shouldReturnFalseIfUserIsNull() throws Exception { User owner = new Us... |
Configuration extends AbstractConfiguration { public float getLimitImageHeightLowerRatioThreshold() { return getLocalFloat("viewer.limitImageHeight[@lowerRatioThreshold]", 3f); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRe... | @Test public void getLimitImageHeightUpperRatioThreshold_shouldReturnCorrectValue() throws Exception { Assert.assertTrue(0.2f == DataManager.getInstance().getConfiguration().getLimitImageHeightLowerRatioThreshold()); } |
Configuration extends AbstractConfiguration { public float getLimitImageHeightUpperRatioThreshold() { return getLocalFloat("viewer.limitImageHeight[@upperRatioThreshold]", 0.3f); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocal... | @Test public void getLimitImageHeightLowerRatioThreshold_shouldReturnCorrectValue() throws Exception { Assert.assertTrue(2.0f == DataManager.getInstance().getConfiguration().getLimitImageHeightUpperRatioThreshold()); } |
Configuration extends AbstractConfiguration { public String getMapBoxToken() { return getLocalString("maps.mapbox.token", ""); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerThumbnailsPerPag... | @Test public void testReadMapBoxToken() { Assert.assertEquals("some.token", DataManager.getInstance().getConfiguration().getMapBoxToken()); } |
Configuration extends AbstractConfiguration { public List<LicenseDescription> getLicenseDescriptions() { List<LicenseDescription> licenses = new ArrayList<>(); List<HierarchicalConfiguration> licenseNodes = getLocalConfigurationsAt("metadata.licenses.license"); for (HierarchicalConfiguration node : licenseNodes) { Stri... | @Test public void testGetLicenseDescriptions() { List<LicenseDescription> licenses = DataManager.getInstance().getConfiguration().getLicenseDescriptions(); Assert.assertEquals(2, licenses.size()); Assert.assertEquals("CC0 1.0", licenses.get(0).getLabel()); Assert.assertEquals("http: Assert.assertEquals("", licenses.get... |
Configuration extends AbstractConfiguration { public List<String> getGeoMapMarkerFields() { return getLocalList("maps.coordinateFields.field", Arrays.asList("MD_GEOJSON_POINT", "NORM_COORDS_GEOJSON")); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocal... | @Test public void testGetGeoMapMarkerFields() { List<String> fields = DataManager.getInstance().getConfiguration().getGeoMapMarkerFields(); Assert.assertEquals(3, fields.size()); Assert.assertTrue(fields.contains("MD_GEOJSON_POINT")); Assert.assertTrue(fields.contains("NORM_COORDS_GEOJSON")); Assert.assertTrue(fields.c... |
Configuration extends AbstractConfiguration { public List<GeoMapMarker> getGeoMapMarkers() { List<GeoMapMarker> markers = new ArrayList<>(); List<HierarchicalConfiguration> configs = getLocalConfigurationsAt("maps.markers.marker"); for (HierarchicalConfiguration config : configs) { GeoMapMarker marker = readGeoMapMarke... | @Test public void testGetGeoMapMarkers() { List<GeoMapMarker> markers = DataManager.getInstance().getConfiguration().getGeoMapMarkers(); Assert.assertEquals(5, markers.size()); Assert.assertEquals("maps__marker_1", markers.get(0).getName()); Assert.assertEquals("fa-circle", markers.get(0).getIcon()); Assert.assertEqual... |
Configuration extends AbstractConfiguration { public GeoMapMarker getGeoMapMarker(String name) { return getGeoMapMarkers().stream().filter(m -> name.equalsIgnoreCase(m.getName())).findAny().orElse(null); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLoc... | @Test public void testGetGeoMapMarker() { GeoMapMarker marker = DataManager.getInstance().getConfiguration().getGeoMapMarker("maps__marker_2"); Assert.assertNotNull(marker); Assert.assertEquals("maps__marker_2", marker.getName()); Assert.assertEquals("fa-search", marker.getIcon()); } |
Configuration extends AbstractConfiguration { public String getConnectorVersionUrl() { return getLocalString("urls.connectorVersion", "http: } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); int getViewerTh... | @Test public void getConnectorVersionUrl_shouldReturnCorrectValue() throws Exception { Assert.assertEquals("http: DataManager.getInstance().getConfiguration().getConnectorVersionUrl()); } |
Configuration extends AbstractConfiguration { public boolean isDisplaySidebarBrowsingTerms() { return getLocalBoolean("sidebar.sidebarBrowsingTerms[@display]", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBun... | @Test public void isDisplaySidebarBrowsingTerms_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isDisplaySidebarBrowsingTerms()); } |
Configuration extends AbstractConfiguration { public boolean isDisplaySidebarRssFeed() { return getLocalBoolean("sidebar.sidebarRssFeed[@display]", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); i... | @Test public void isDisplaySidebarRssFeed_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isDisplaySidebarRssFeed()); } |
Campaign implements CMSMediaHolder { public long getDaysLeft() { if (dateEnd == null) { return -1; } LocalDateTime now = LocalDate.now().atStartOfDay(); LocalDateTime end = DateTools.convertDateToLocalDateTimeViaInstant(dateEnd); return Math.max(0L, Duration.between(now, end).toDays()); } Campaign(); Campaign(Locale s... | @Test public void getDaysLeft_shouldReturn1IfNoDateEnd() throws Exception { Campaign campaign = new Campaign(); Assert.assertEquals(-1, campaign.getDaysLeft()); } |
Configuration extends AbstractConfiguration { public boolean isDisplayWidgetUsage() { return getLocalBoolean("sidebar.sidebarWidgetUsage[@display]", true); } Configuration(String configFilePath); Set<String> getStopwords(); boolean reloadingRequired(); String getConfigLocalPath(); String getLocalRessourceBundleFile(); ... | @Test public void isDisplayWidgetUsage_shouldReturnCorrectValue() throws Exception { Assert.assertFalse(DataManager.getInstance().getConfiguration().isDisplayWidgetUsage()); } |
TEITools { public static String getTeiFulltext(String tei) throws JDOMException, IOException { if (tei == null) { return null; } Document doc = XmlTools.getDocumentFromString(tei, StringTools.DEFAULT_ENCODING); if (doc == null) { return null; } if (doc.getRootElement() != null) { Element eleText = doc.getRootElement().... | @Test public void getTeiFulltext_shouldExtractFulltextCorrectly() throws Exception { Path path = Paths.get("src/test/resources/data/viewer/tei/DE_2013_Riedel_PolitikUndCo_241__248/DE_2013_Riedel_PolitikUndCo_241__248_eng.xml"); Assert.assertTrue(Files.isRegularFile(path)); String tei = FileTools.getStringFromFile(path.... |
SolrSearchIndex { public QueryResponse search(String query, int first, int rows, List<StringPair> sortFields, List<String> facetFields, String facetSort, List<String> fieldList, List<String> filterQueries, Map<String, String> params) throws PresentationException, IndexUnreachableException { SolrQuery solrQuery = new So... | @Test public void search_shouldReturnCorrectResults() throws Exception { QueryResponse response = DataManager.getInstance() .getSearchIndex() .search(SolrConstants.PI + ":PPN517154005 " + SolrConstants.PI + ":34115495_1940", 0, Integer.MAX_VALUE, null, null, null); Assert.assertEquals(2, response.getResults().size()); ... |
SolrSearchIndex { public QueryResponse searchFacetsAndStatistics(String query, List<String> filterQueries, List<String> facetFields, int facetMinCount, boolean getFieldStatistics) throws PresentationException, IndexUnreachableException { return searchFacetsAndStatistics(query, filterQueries, facetFields, facetMinCount,... | @Test public void searchFacetsAndStatistics_shouldGenerateFacetsCorrectly() throws Exception { String[] facetFields = { SolrConstants._CALENDAR_YEAR, SolrConstants._CALENDAR_MONTH }; QueryResponse resp = DataManager.getInstance() .getSearchIndex() .searchFacetsAndStatistics(SolrConstants._CALENDAR_YEAR + ":*", null, Ar... |
Campaign implements CMSMediaHolder { public long getDaysBeforeStart() { if (dateStart == null) { return -1; } LocalDateTime now = LocalDate.now().atStartOfDay(); LocalDateTime start = DateTools.convertDateToLocalDateTimeViaInstant(dateStart); return Math.max(0L, Duration.between(now, start).toDays()); } Campaign(); Ca... | @Test public void getDaysBeforeStart_shouldReturn1IfNoDateStart() throws Exception { Campaign campaign = new Campaign(); Assert.assertEquals(-1, campaign.getDaysBeforeStart()); } |
SolrSearchIndex { public long getImageOwnerIddoc(String pi, int pageNo) throws IndexUnreachableException, PresentationException { logger.trace("getImageOwnerIddoc: {}:{}", pi, pageNo); String query = new StringBuilder(SolrConstants.PI_TOPSTRUCT).append(":") .append(pi) .append(" AND ") .append(SolrConstants.ORDER) .app... | @Test public void getImageOwnerIddoc_shouldRetrieveCorrectIDDOC() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getImageOwnerIddoc(PI_KLEIUNIV, 1); Assert.assertNotEquals(-1, iddoc); } |
SolrSearchIndex { public static List<StringPair> getSolrSortFieldsAsList(String solrSortFields, String splitFieldsBy, String splitNameOrderBy) { if (solrSortFields == null) { throw new IllegalArgumentException("solrSortFields may not be null"); } if (splitFieldsBy == null) { throw new IllegalArgumentException("splitFie... | @Test public void getSolrSortFieldsAsList_shouldSplitFieldsCorrectly() throws Exception { List<StringPair> result = SolrSearchIndex.getSolrSortFieldsAsList("SORT_A; SORT_B, desc;SORT_C,asc", ";", ","); Assert.assertNotNull(result); Assert.assertEquals(3, result.size()); Assert.assertEquals("SORT_A", result.get(0).getOn... |
SolrSearchIndex { public SolrDocument getFirstDoc(String query, List<String> fieldList) throws PresentationException, IndexUnreachableException { return getFirstDoc(query, fieldList, null); } SolrSearchIndex(SolrClient client); void checkReloadNeeded(); static HttpSolrClient getNewHttpSolrClient(); QueryResponse testQu... | @Test public void getFirstDoc_shouldReturnCorrectDoc() throws Exception { SolrDocument doc = DataManager.getInstance() .getSearchIndex() .getFirstDoc(new StringBuilder(SolrConstants.PI_TOPSTRUCT).append(":") .append(PI_KLEIUNIV) .append(" AND ") .append(SolrConstants.DOCTYPE) .append(":PAGE") .toString(), Collections.s... |
SolrSearchIndex { public SolrDocument getDocumentByIddoc(String iddoc) throws IndexUnreachableException, PresentationException { SolrDocument ret = null; SolrDocumentList hits = search(new StringBuilder(SolrConstants.IDDOC).append(':').append(iddoc).toString(), 0, 1, null, null, null).getResults(); if (hits != null && ... | @Test public void getDocumentByIddoc_shouldReturnCorrectDoc() throws Exception { SolrDocument doc = DataManager.getInstance().getSearchIndex().getDocumentByIddoc(String.valueOf(iddocKleiuniv)); Assert.assertNotNull(doc); Assert.assertEquals(String.valueOf(iddocKleiuniv), doc.getFieldValue(SolrConstants.IDDOC)); } |
SolrSearchIndex { public long getIddocFromIdentifier(String identifier) throws PresentationException, IndexUnreachableException { SolrDocumentList docs = search(new StringBuilder(SolrConstants.PI).append(':').append(identifier).toString(), 1, null, Collections.singletonList(SolrConstants.IDDOC)); if (!docs.isEmpty()) {... | @Test public void getIddocFromIdentifier_shouldRetrieveCorrectIDDOC() throws Exception { Assert.assertEquals(iddocKleiuniv, DataManager.getInstance().getSearchIndex().getIddocFromIdentifier(PI_KLEIUNIV)); } |
SolrSearchIndex { public String getIdentifierFromIddoc(long iddoc) throws PresentationException, IndexUnreachableException { logger.trace("getIdentifierFromIddoc: {}", iddoc); SolrQuery solrQuery = new SolrQuery(new StringBuilder(SolrConstants.IDDOC).append(":").append(iddoc).toString()); solrQuery.setRows(1); try { Qu... | @Test public void getIdentifierFromIddoc_shouldRetrieveCorrectIdentifier() throws Exception { Assert.assertEquals(PI_KLEIUNIV, DataManager.getInstance().getSearchIndex().getIdentifierFromIddoc(iddocKleiuniv)); } |
Campaign implements CMSMediaHolder { public boolean isHasEnded() { if (dateEnd == null) { return false; } LocalDateTime now = LocalDateTime.now(); LocalDateTime end = DateTools.convertDateToLocalDateTimeViaInstant(dateEnd); return now.isAfter(end); } Campaign(); Campaign(Locale selectedLocale); @Override int hashCode(... | @Test public void isHasEnded_shouldReturnFalseIfDateEndNull() throws Exception { Campaign campaign = new Campaign(); Assert.assertFalse(campaign.isHasEnded()); } |
SolrSearchIndex { public long getIddocByLogid(String pi, String logId) throws IndexUnreachableException, PresentationException { logger.trace("getIddocByLogid: {}:{}", pi, logId); String query = new StringBuilder(SolrConstants.PI_TOPSTRUCT).append(":") .append(pi) .append(" AND ") .append(SolrConstants.LOGID) .append("... | @Test public void getIddocByLogid_shouldRetrieveCorrectIDDOC() throws Exception { Assert.assertNotEquals(-1, DataManager.getInstance().getSearchIndex().getIddocByLogid(PI_KLEIUNIV, "LOG_0001")); } |
SolrSearchIndex { public static Map<String, List<String>> getMetadataValuesForLanguage(SolrDocument doc, String key) { if (doc == null) { throw new IllegalArgumentException("doc may not be null"); } if (key == null) { throw new IllegalArgumentException("key may not be null"); } List<String> fieldNames = doc.getFieldNam... | @Test public void testGetMetadataValuesForLanguage() { SolrDocument doc = new SolrDocument(); doc.addField("field_A", "value_A"); doc.addField("field_B_LANG_EN", "field_B_en"); doc.addField("field_B_LANG_DE", "field_B_de"); doc.addField("field_B_LANG_EN", "field_B_en_2"); Map<String, List<String>> mapA = SolrSearchInde... |
SolrSearchIndex { public static Map<String, List<IMetadataValue>> getMultiLanguageFieldValueMap(SolrDocument doc) { Map<String, List<IMetadataValue>> ret = new HashMap<>(); for (String fieldName : doc.getFieldNames()) { switch (fieldName) { case SolrConstants.IMAGEURN_OAI: case "PAGEURNS": break; default: if (isLanguag... | @Test public void testGetMultiLanguageFieldValueMap() { SolrDocument doc = new SolrDocument(); doc.addField("field_A", "value_A"); doc.addField("field_B", "value_B"); doc.addField("field_B_LANG_EN", "field_B_en"); doc.addField("field_B_LANG_DE", "field_B_de"); doc.addField("field_B_LANG_EN", "field_B_en_2"); Map<String... |
SolrSearchIndex { public static String getSingleFieldStringValue(SolrDocument doc, String field) { Object val = getSingleFieldValue(doc, field); return val != null ? String.valueOf(val) : null; } SolrSearchIndex(SolrClient client); void checkReloadNeeded(); static HttpSolrClient getNewHttpSolrClient(); QueryResponse te... | @Test public void getSingleFieldStringValue_shouldReturnValueAsStringCorrectly() throws Exception { SolrDocument doc = new SolrDocument(); doc.addField("NUM", 1337); Assert.assertEquals("1337", SolrSearchIndex.getSingleFieldStringValue(doc, "NUM")); }
@Test public void getSingleFieldStringValue_shouldNotReturnNullAsStr... |
SolrSearchIndex { String findDataRepositoryName(String pi) throws PresentationException, IndexUnreachableException { if (!dataRepositoryNames.containsKey(pi)) { String dataRepositoryName = findDataRepository(pi); updateDataRepositoryNames(pi, dataRepositoryName); } return dataRepositoryNames.get(pi); } SolrSearchIndex(... | @Test public void findDataRepositoryName_shouldReturnValueFromMapIfAvailable() throws Exception { DataManager.getInstance().getSearchIndex().dataRepositoryNames.put("PPN123", "superrepo"); Assert.assertEquals("superrepo", DataManager.getInstance().getSearchIndex().findDataRepositoryName("PPN123")); } |
SolrSearchIndex { public static boolean isHasImages(SolrDocument doc) throws IndexUnreachableException { StructElement structElement = new StructElement(0, doc); String fileExtension = ""; String filename = structElement.getMetadataValue(SolrConstants.FILENAME); if (StringUtils.isEmpty(filename)) { filename = structEle... | @Test public void isHasImages_shouldReturnCorrectValueForPageDocs() throws Exception { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.FILENAME, "foo.jpg"); Assert.assertTrue(SolrSearchIndex.isHasImages(doc)); doc.setField(SolrConstants.FILENAME, "foo.txt"); Assert.assertFalse(SolrSearchIndex.isHasIma... |
SolrSearchIndex { public void updateDataRepositoryNames(String pi, String dataRepositoryName) { dataRepositoryNames.put(pi, dataRepositoryName); } SolrSearchIndex(SolrClient client); void checkReloadNeeded(); static HttpSolrClient getNewHttpSolrClient(); QueryResponse testQuery(String query); QueryResponse search(Strin... | @Test public void updateDataRepositoryNames_shouldUpdateValueCorrectly() throws Exception { Assert.assertNull(DataManager.getInstance().getSearchIndex().dataRepositoryNames.get("PPN123")); DataManager.getInstance().getSearchIndex().updateDataRepositoryNames("PPN123", "repo/a"); Assert.assertEquals("repo/a", DataManager... |
SolrSearchIndex { public static String getQueryForAccessCondition(String accessCondition, boolean escape) { if (escape) { accessCondition = BeanUtils.escapeCriticalUrlChracters(accessCondition); } return SearchHelper.ALL_RECORDS_QUERY + " AND " + SolrConstants.ACCESSCONDITION + ":\"" + accessCondition + "\""; } SolrSea... | @Test public void getQueryForAccessCondition_shouldBuildEscapedQueryCorrectly() throws Exception { Assert.assertEquals( SearchHelper.ALL_RECORDS_QUERY + " AND " + SolrConstants.ACCESSCONDITION + ":\"foo" + BeanUtils.SLASH_REPLACEMENT + "bar\"", SolrSearchIndex.getQueryForAccessCondition("foo/bar", true)); }
@Test publi... |
Campaign implements CMSMediaHolder { public boolean isHasStarted() { if (dateStart == null) { return true; } LocalDateTime now = LocalDateTime.now(); LocalDateTime start = DateTools.convertDateToLocalDateTimeViaInstant(dateStart); return now.isEqual(start) || now.isAfter(start); } Campaign(); Campaign(Locale selectedL... | @Test public void isHasStarted_shouldReturnTrueIfDateStartNull() throws Exception { Campaign campaign = new Campaign(); Assert.assertTrue(campaign.isHasStarted()); } |
SolrSearchIndex { public Map<String, String> getLabelValuesForDrillDownField(String field, String labelField, Set<String> values) throws PresentationException, IndexUnreachableException { if (field == null || labelField == null || values == null || values.isEmpty()) { return Collections.emptyMap(); } Map<String, String... | @Test public void getLabelValuesForDrillDownField_shouldReturnCorrectValues() throws Exception { String[] values = new String[] { "Groos, Karl", "Schubert, Otto", "Heinse, Gottlob Heinrich" }; Map<String, String> result = DataManager.getInstance() .getSearchIndex() .getLabelValuesForDrillDownField("MD_AUTHOR", "MD_FIRS... |
ALTOTools { protected static Rectangle rotate(Rectangle rect, int rotation, Dimension imageSize) { double x1 = rect.getMinX(); double y1 = rect.getMinY(); double x2 = rect.getMaxX(); double y2 = rect.getMaxY(); double w = imageSize.getWidth(); double h = imageSize.getHeight(); double x1r = x1; double y1r = y1; double x... | @Test public void testRotate() { Rectangle rect = new Rectangle(589, 502, 948 - 589, 654 - 502); Dimension canvasSize = new Dimension(1792, 2747); Rectangle expectedRotatedRect_270 = new Rectangle(502, 844, 654 - 502, 1203 - 844); rect = ALTOTools.rotate(rect, 270, canvasSize); assertEquals(expectedRotatedRect_270, rec... |
ALTOTools { public static List<String> getWordCoords(String altoString, Set<String> searchTerms) { return getWordCoords(altoString, searchTerms, 0); } static String getFulltext(Path path, String encoding); static String getFullText(String alto, boolean mergeLineBreakWords, HttpServletRequest request); static List<TagC... | @Test public void testGetWordCoords() throws IOException { File testFile = new File("src/test/resources/data/sample_alto.xml"); int rotation = 0; String altoString = FileUtils.readFileToString(testFile, "UTF-8"); List<String> coords = ALTOTools.getWordCoords(altoString, Collections.singleton("hinauf"), rotation); Asser... |
ALTOTools { protected static String alto2Txt(String alto, boolean mergeLineBreakWords, HttpServletRequest request) throws IOException, XMLStreamException, JDOMException { if (alto == null) { throw new IllegalArgumentException("alto may not be null"); } String useAlto = alto; if (mergeLineBreakWords) { AltoDocument alto... | @Test public void alto2Txt_shouldUseExtractFulltextCorrectly() throws Exception { File file = new File("src/test/resources/data/viewer/alto/LIWZ_1877_01_05_001.xml"); Assert.assertTrue(file.isFile()); String alto = FileTools.getStringFromFile(file, "utf-8"); Assert.assertNotNull(alto); String text = ALTOTools.alto2Txt(... |
ALTOTools { public static String getFulltext(Path path, String encoding) throws IOException { String altoString = FileTools.getStringFromFile(path.toFile(), encoding); return getFullText(altoString, false, null); } static String getFulltext(Path path, String encoding); static String getFullText(String alto, boolean me... | @Test public void getFullText_shouldExtractFulltextCorrectly() throws Exception { File file = new File("src/test/resources/data/viewer/data/1/alto/00000010.xml"); Assert.assertTrue(file.isFile()); String text = ALTOTools.getFulltext(file.toPath(), "utf-8"); Assert.assertNotNull(text); Assert.assertTrue(text.length() > ... |
CMSSidebarElement { protected static String cleanupHtmlTag(String tag) { Matcher m2 = patternHtmlAttribute.matcher(tag); while (m2.find()) { String attribute = m2.group(); tag = tag.replace(attribute, ""); } tag = tag.replace("</", "<").replace("/>", ">").replace(" ", ""); return tag; } CMSSidebarElement(); CMSSidebar... | @Test public void cleanupHtmlTag_shouldRemoveAttributesCorrectly() throws Exception { Assert.assertEquals("<tag>", CMSSidebarElement.cleanupHtmlTag("<tag attribute=\"value\" attribute=\"value\" >")); }
@Test public void cleanupHtmlTag_shouldRemoveClosingTagCorrectly() throws Exception { Assert.assertEquals("<tag>", CMS... |
FileTools { public static String getStringFromFile(File file, String encoding) throws FileNotFoundException, IOException { return getStringFromFile(file, encoding, null); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile... | @Test public void getStringFromFile_shouldReadTextFileCorrectly() throws Exception { File file = new File("src/test/resources/stopwords.txt"); Assert.assertTrue(file.isFile()); String contents = FileTools.getStringFromFile(file, null); Assert.assertTrue(StringUtils.isNotBlank(contents)); }
@Test(expected = FileNotFound... |
FileTools { public static String getStringFromFilePath(String filePath) throws FileNotFoundException, IOException { return getStringFromFile(new File(filePath), null); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(Fi... | @Test public void getStringFromFilePath_shouldReadTextFileCorrectly() throws Exception { String contents = FileTools.getStringFromFilePath("src/test/resources/stopwords.txt"); Assert.assertTrue(StringUtils.isNotBlank(contents)); }
@Test(expected = FileNotFoundException.class) public void getStringFromFilePath_shouldThr... |
FileTools { public static void compressGzipFile(File file, File gzipFile) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(gzipFile); GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) { byte[] buffer = new byte[1024]; int le... | @Test(expected = FileNotFoundException.class) public void compressGzipFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.compressGzipFile(file, new File("target/test.tar.gz")); } |
FileTools { public static void decompressGzipFile(File gzipFile, File newFile) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(gzipFile); GZIPInputStream gis = new GZIPInputStream(fis); FileOutputStream fos = new FileOutputStream(newFile)) { byte[] buffer = new byte[1024]; int... | @Test(expected = FileNotFoundException.class) public void decompressGzipFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File gzipFile = new File("notfound.tar.gz"); Assert.assertFalse(gzipFile.exists()); FileTools.decompressGzipFile(gzipFile, new File("target/target.bla")); } |
FileTools { public static File getFileFromString(String string, String filePath, String encoding, boolean append) throws IOException { if (string == null) { throw new IllegalArgumentException("string may not be null"); } if (encoding == null) { encoding = StringTools.DEFAULT_ENCODING; } File file = new File(filePath); ... | @Test public void getFileFromString_shouldWriteFileCorrectly() throws Exception { Assert.assertTrue(tempDir.mkdirs()); File file = new File(tempDir, "temp.txt"); String text = "Lorem ipsum dolor sit amet"; FileTools.getFileFromString(text, file.getAbsolutePath(), null, false); Assert.assertTrue(file.isFile()); } |
FileTools { public static String getCharset(InputStream input) throws IOException { CharsetDetector cd = new CharsetDetector(); try (BufferedInputStream bis = new BufferedInputStream(input)) { cd.setText(bis); CharsetMatch cm = cd.detect(); if (cm != null) { return cm.getName(); } } return null; } static String getStr... | @Test public void getCharset_shouldDetectCharsetCorrectly() throws Exception { File file = new File("src/test/resources/stopwords.txt"); try (FileInputStream fis = new FileInputStream(file)) { Assert.assertEquals("UTF-8", FileTools.getCharset(fis)); } } |
FileTools { public static String probeContentType(URI uri) throws IOException { String type = URLConnection.guessContentTypeFromName(uri.toString()); if ("text/plain".equals(type)) { if (!uri.isAbsolute() || uri.getScheme().equals("file")) { Path path = PathConverter.getPath(uri); try (InputStream in = Files.newInputSt... | @Test public void testProbeContentType() throws FileNotFoundException, IOException { Path resourceFolder = Paths.get("src/test/resources/data/viewer/fulltext"); Assert.assertEquals("text/plain", FileTools.probeContentType(FileTools.getStringFromFilePath(resourceFolder.resolve("ascii.txt").toString()))); Assert.assertEq... |
FileTools { public static String getBottomFolderFromPathString(String pathString) { if (StringUtils.isBlank(pathString)) { return ""; } Path path = Paths.get(pathString); return path.getParent() != null ? path.getParent().getFileName().toString() : ""; } static String getStringFromFilePath(String filePath); static Str... | @Test public void getBottomFolderFromPathString_shouldReturnFolderNameCorrectly() throws Exception { Assert.assertEquals("PPN123", FileTools.getBottomFolderFromPathString("data/1/alto/PPN123/00000001.xml")); }
@Test public void getBottomFolderFromPathString_shouldReturnEmptyStringIfNoFolderInPath() throws Exception { A... |
FileTools { public static String getFilenameFromPathString(String pathString) { if (StringUtils.isBlank(pathString)) { return ""; } Path path = getPathFromUrlString(pathString); return path.getFileName().toString(); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, Stri... | @Test public void getFilenameFromPathString_shouldReturnFileNameCorrectly() throws Exception { Assert.assertEquals("00000001.xml", FileTools.getFilenameFromPathString("data/1/alto/PPN123/00000001.xml")); } |
LanguageHelper { public Language getLanguage(String isoCode) { SubnodeConfiguration languageConfig = null; try { if (isoCode.length() == 3) { List<HierarchicalConfiguration> nodes = config.configurationsAt("language[iso_639-2=\"" + isoCode + "\"]"); if (nodes.isEmpty()) { nodes = config.configurationsAt("language[iso_6... | @Test public void test() { LanguageHelper helper = new LanguageHelper("languages.xml"); Assert.assertNotNull(helper.getLanguage("fra")); Assert.assertNotNull(helper.getLanguage("fre")); Assert.assertNotNull(helper.getLanguage("fr")); } |
DataFileTools { public static String getSourceFilePath(String fileName, String format) throws PresentationException, IndexUnreachableException { String pi = FilenameUtils.getBaseName(fileName); String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getSourceFilePath(fileNa... | @Test public void getSourceFilePath_shouldConstructMETSFilePathCorrectly() throws Exception { Assert.assertEquals("src/test/resources/data/viewer/data/1/indexed_mets/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", "1", SolrConstants._METS)); Assert.assertEquals("src/test/resources/data/viewer/indexed_mets/PP... |
DataFileTools { public static Path getDataFolder(String pi, String dataFolderName) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return... | @Test public void getDataFolder_shouldReturnCorrectFolderIfNoDataRepositoryUsed() throws Exception { Path folder = DataFileTools.getDataFolder("PPN123", "media", null); Assert.assertEquals(Paths.get("src/test/resources/data/viewer/media/PPN123"), folder); }
@Test public void getDataFolder_shouldReturnCorrectFolderIfDat... |
CMSSidebarElement { public boolean isValid() { if (hasHtml()) { Matcher m = patternHtmlTag.matcher(html); Set<String> disallowedTags = CMSSidebarManager.getInstance().getDisallowedHtmlTags(); while (m.find()) { String tag = m.group(); if (tag.startsWith("<!--")) { continue; } tag = cleanupHtmlTag(tag); logger.trace("Ch... | @Test public void isValidTest() { String html = "<dl>dsdf <br /> sadasdsdf</dl>"; CMSSidebarElement element = new CMSSidebarElement(); element.setHtml(html); assertTrue(element.isValid()); } |
DataFileTools { static String getDataRepositoryPath(String dataRepositoryPath) { if (StringUtils.isBlank(dataRepositoryPath)) { return DataManager.getInstance().getConfiguration().getViewerHome(); } if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryPath)).isAbsolute()) { return dataRepositoryPath + '/'; } retur... | @Test public void getDataRepositoryPath_shouldReturnCorrectPathForEmptyDataRepository() throws Exception { Assert.assertEquals(DataManager.getInstance().getConfiguration().getViewerHome(), DataFileTools.getDataRepositoryPath(null)); }
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForDataRepositoryName(... |
DataFileTools { static String sanitizeFileName(String fileName) { if (StringUtils.isBlank(fileName)) { return fileName; } return Paths.get(fileName).getFileName().toString(); } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String... | @Test public void sanitizeFileName_shouldRemoveEverythingButTheFileNameFromGivenPath() throws Exception { Assert.assertEquals("foo.bar", DataFileTools.sanitizeFileName("/opt/digiverso/foo.bar")); Assert.assertEquals("foo.bar", DataFileTools.sanitizeFileName("../../foo.bar")); Assert.assertEquals("foo.bar", DataFileTool... |
DateTools { public static LocalDateTime parseDateTimeFromString(String dateString, boolean fromUTC) { return parseDateTimeFromString(dateString, fromUTC, null); } static List<Date> parseMultipleDatesFromString(String dateString); static LocalDateTime parseDateTimeFromString(String dateString, boolean fromUTC); static ... | @Test public void parseDateTimeFromString_shouldParseIsoDateFormatsCorrectly() throws Exception { { LocalDateTime date = DateTools.parseDateTimeFromString("2017-12-19 00:00:00", false); Assert.assertNotNull(date); Assert.assertEquals(2017, date.getYear()); Assert.assertEquals(12, date.getMonthValue()); Assert.assertEqu... |
CMSStaticPage { public String getPageName() { return pageName; } CMSStaticPage(); CMSStaticPage(String name); @SuppressWarnings("deprecation") CMSStaticPage(CMSPage cmsPage); Optional<CMSPage> getCmsPageOptional(); CMSPage getCmsPage(); void setCmsPage(CMSPage cmsPage); Long getId(); String getPageName(); boolean isL... | @Test public void testGetPageName() { Assert.assertEquals("test", page.getPageName()); } |
DateTools { public static Date createDate(int year, int month, int dayofMonth, int hour, int minute) { return createDate(year, month, dayofMonth, hour, minute, false); } static List<Date> parseMultipleDatesFromString(String dateString); static LocalDateTime parseDateTimeFromString(String dateString, boolean fromUTC); ... | @Test public void createDate_shouldCreateDateCorrectly() throws Exception { Date date = DateTools.createDate(2020, 8, 31, 9, 43, false); Assert.assertNotNull(date); Calendar cal = Calendar.getInstance(); cal.setTime(date); Assert.assertEquals(2020, cal.get(Calendar.YEAR)); Assert.assertEquals(8 - 1, cal.get(Calendar.MO... |
NetTools { protected static String parseMultipleIpAddresses(String address) { if (address == null) { throw new IllegalArgumentException("address may not be null"); } if (address.contains(",")) { String[] addressSplit = address.split(","); if (addressSplit.length > 0) { address = addressSplit[addressSplit.length - 1].tr... | @Test public void parseMultipleIpAddresses_shouldFilterMultipleAddressesCorrectly() throws Exception { Assert.assertEquals("3.3.3.3", NetTools.parseMultipleIpAddresses("1.1.1.1, 2.2.2.2, 3.3.3.3")); } |
NetTools { public static String scrambleEmailAddress(String email) { if (StringUtils.isEmpty(email)) { return email; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < email.length(); ++i) { if (i > 2 && i < email.length() - 3) { sb.append('*'); } else { sb.append(email.charAt(i)); } } return sb.toString(); ... | @Test public void scrambleEmailAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("foo*****com", NetTools.scrambleEmailAddress("foo@bar.com")); } |
NetTools { public static String scrambleIpAddress(String address) { if (StringUtils.isEmpty(address)) { return address; } String[] addressSplit = address.split("[.]"); if (addressSplit.length == 4) { return addressSplit[0] + "." + addressSplit[1] + ".X.X"; } return address; } static String[] callUrlGET(String url); st... | @Test public void scrambleIpAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("192.168.X.X", NetTools.scrambleIpAddress("192.168.0.1")); } |
IndexerTools { public static synchronized boolean deleteRecord(String pi, boolean createTraceDocument, Path hotfolderPath) throws IOException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } if (hotfolderPath == null) { throw new IllegalArgumentException("hotfolderPath may not be null"); ... | @Test public void deleteRecord_shouldCreateDeleteFileCorrectly() throws Exception { Path hotfolder = Paths.get("src/test/resources", DataManager.getInstance().getConfiguration().getHotfolder()); if (!Files.isDirectory(hotfolder)) { Files.createDirectory(hotfolder); } Path file = Paths.get(hotfolder.toAbsolutePath().toS... |
JsonTools { public static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl) throws ViewerConfigurationException { return getRecordJsonObject(doc, rootUrl, null); } static JSONArray getRecordJsonArray(SolrDocumentList result, Map<String, SolrDocumentList> expanded, HttpServletRequest request,
... | @Test public void getRecordJsonObject_shouldAddAllMetadata() throws Exception { String rootUrl = "http: QueryResponse response = DataManager.getInstance().getSearchIndex().search(SolrConstants.PI + ":" + PI, 0, 1, null, null, null); Assert.assertFalse("Required Solr document not found in index: " + PI, response.getResu... |
JsonTools { public static String formatVersionString(String json) { final String notAvailableKey = "admin__dashboard_versions_not_available"; if (StringUtils.isEmpty(json)) { return notAvailableKey; } try { JSONObject jsonObj = new JSONObject(json); return jsonObj.getString("application") + " " + jsonObj.getString("ver... | @Test public void formatVersionString_shouldFormatStringCorrectly() throws Exception { Assert.assertEquals("goobi-viewer-core 1337 2020-06-30 abcdefg", JsonTools.formatVersionString( "{\"application\": \"goobi-viewer-core\", \"version\": \"1337\", \"build-date\": \"2020-06-30\", \"git-revision\": \"abcdefg\"}")); }
@Te... |
CMSStaticPage { public boolean isLanguageComplete(Locale locale) { if (getCmsPageOptional().isPresent()) { return cmsPage.get().isLanguageComplete(locale); } return false; } CMSStaticPage(); CMSStaticPage(String name); @SuppressWarnings("deprecation") CMSStaticPage(CMSPage cmsPage); Optional<CMSPage> getCmsPageOption... | @Test public void testIsLanguageComplete() { Assert.assertFalse(page.isLanguageComplete(Locale.GERMANY)); } |
JsonTools { public static String shortFormatVersionString(String json) { final String notAvailableKey = "admin__dashboard_versions_not_available"; if (StringUtils.isEmpty(json)) { return notAvailableKey; } try { JSONObject jsonObj = new JSONObject(json); return jsonObj.getString("version") + " (" + jsonObj.getString("g... | @Test public void shortFormatVersionString_shouldFormatStringCorrectly() throws Exception { Assert.assertEquals("1337 (abcdefg)", JsonTools.shortFormatVersionString( "{\"application\": \"goobi-viewer-core\", \"version\": \"1337\", \"build-date\": \"2020-06-30\", \"git-revision\": \"abcdefg\"}")); }
@Test public void sh... |
StringTools { public static String escapeHtmlChars(String str) { return replaceCharacters(str, new String[] { "&", "\"", "<", ">" }, new String[] { "&", """, "<", ">" }); } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text,... | @Test public void escapeHtmlChars_shouldEscapeAllCharactersCorrectly() throws Exception { Assert.assertEquals("<i>"A&B"</i>", StringTools.escapeHtmlChars("<i>\"A&B\"</i>")); } |
StringTools { static String replaceCharacters(String str, String[] replace, String[] replaceWith) { if (str == null) { return null; } if (replace == null) { throw new IllegalArgumentException("replace may not be null"); } if (replaceWith == null) { throw new IllegalArgumentException("replaceWith may not be null"); } re... | @Test public void replaceCharacters_shouldReplaceCharactersCorrectly() throws Exception { Assert.assertEquals("|-|3110", StringTools.replaceCharacters("Hello", new String[] { "H", "e", "l", "o" }, new String[] { "|-|", "3", "1", "0" })); } |
StringTools { public static String removeLineBreaks(String s, String replaceWith) { if (s == null) { throw new IllegalArgumentException("s may not be null"); } if (replaceWith == null) { replaceWith = ""; } return s.replace("\r\n", replaceWith) .replace("\n", replaceWith) .replaceAll("\r", replaceWith) .replaceAll("<br... | @Test public void removeLineBreaks_shouldRemoveLineBreaksCorrectly() throws Exception { Assert.assertEquals("foobar", StringTools.removeLineBreaks("foo\r\nbar", "")); }
@Test public void removeLineBreaks_shouldRemoveHtmlLineBreaksCorrectly() throws Exception { Assert.assertEquals("foo bar", StringTools.removeLineBreaks... |
StringTools { public static String stripJS(String s) { if (StringUtils.isBlank(s)) { return s; } return s.replaceAll("(?i)<script[\\s\\S]*<\\/script>", ""); } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); st... | @Test public void stripJS_shouldRemoveJSBlocksCorrectly() throws Exception { Assert.assertEquals("foo bar", StringTools.stripJS("foo <script type=\"javascript\">\nfunction f {\n alert();\n}\n</script> bar")); Assert.assertEquals("foo bar", StringTools.stripJS("foo <SCRIPT>\nfunction f {\n alert();\n}\n</ScRiPt> bar"));... |
StringTools { public static String escapeQuotes(String s) { if (s != null) { s = s.replaceAll("(?<!\\\\)'", "\\\\'"); s = s.replaceAll("(?<!\\\\)\"", "\\\\\""); } return s; } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex... | @Test public void testEscapeQuotes() { String original = "Das ist ein 'String' mit \"Quotes\"."; String reference = "Das ist ein \\'String\\' mit \\\"Quotes\\\"."; String escaped = StringTools.escapeQuotes(original); Assert.assertEquals(reference, escaped); escaped = StringTools.escapeQuotes(reference); Assert.assertEq... |
StringTools { public static boolean isImageUrl(String url) { if (StringUtils.isEmpty(url)) { return false; } String extension = FilenameUtils.getExtension(url); if (StringUtils.isEmpty(extension)) { return false; } switch (extension.toLowerCase()) { case "tif": case "tiff": case "jpg": case "jpeg": case "gif": case "pn... | @Test public void isImageUrl_shouldReturnTrueForImageUrls() throws Exception { Assert.assertTrue(StringTools.isImageUrl("https: Assert.assertTrue(StringTools.isImageUrl("https: } |
CMSStaticPage { public boolean isHasCmsPage() { return getCmsPageId().isPresent(); } CMSStaticPage(); CMSStaticPage(String name); @SuppressWarnings("deprecation") CMSStaticPage(CMSPage cmsPage); Optional<CMSPage> getCmsPageOptional(); CMSPage getCmsPage(); void setCmsPage(CMSPage cmsPage); Long getId(); String getPag... | @Test public void testHasCmsPage() { Assert.assertFalse(page.isHasCmsPage()); } |
StringTools { public static String renameIncompatibleCSSClasses(String html) { if (html == null) { return null; } Pattern p = Pattern.compile("\\.([0-9]+[A-Za-z]+) \\{.*\\}"); Matcher m = p.matcher(html); Map<String, String> replacements = new HashMap<>(); while (m.find()) { if (m.groupCount() > 0) { String oldName = m... | @Test public void renameIncompatibleCSSClasses_shouldRenameClassesCorrectly() throws Exception { Path file = Paths.get("src/test/resources/data/text_example_bad_classes.htm"); Assert.assertTrue(Files.isRegularFile(file)); String html = FileTools.getStringFromFile(file.toFile(), StringTools.DEFAULT_ENCODING); Assert.ass... |
StringTools { public static List<String> getHierarchyForCollection(String collection, String split) { if (StringUtils.isEmpty(collection) || StringUtils.isEmpty(split)) { return Collections.emptyList(); } String useSplit = '[' + split + ']'; String[] hierarchy = collection.contains(split) ? collection.split(useSplit) :... | @Test public void getHierarchyForCollection_shouldCreateListCorrectly() throws Exception { List<String> result = StringTools.getHierarchyForCollection("a.b.c.d", "."); Assert.assertEquals(4, result.size()); Assert.assertEquals("a", result.get(0)); Assert.assertEquals("a.b", result.get(1)); Assert.assertEquals("a.b.c", ... |
StringTools { public static String normalizeWebAnnotationCoordinates(String coords) { if (coords == null) { return null; } if (!coords.startsWith("xywh=")) { return coords; } String ret = coords.substring(5); String[] rectSplit = ret.split(","); if (rectSplit.length == 4) { ret = rectSplit[0].trim() + ", " + rectSplit[... | @Test public void normalizeWebAnnotationCoordinates_shouldNormalizeCoordinatesCorrectly() throws Exception { Assert.assertEquals("1, 2, 4, 6", StringTools.normalizeWebAnnotationCoordinates("xywh=1, 2, 3, 4")); }
@Test public void normalizeWebAnnotationCoordinates_shouldPreserveLegacyCoordinates() throws Exception { Ass... |
StringTools { public static String generateMD5(String myString) { String answer = ""; try { byte[] defaultBytes = myString.getBytes("UTF-8"); MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(defaultBytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString =... | @Test public void generateMD5_shouldHashStringCorrectly() throws Exception { Assert.assertEquals("098f6bcd4621d373cade4e832627b4f6", StringTools.generateMD5("test")); } |
BCrypt { public boolean checkpw(String plaintext, String hashed) { return (hashed.compareTo(hashpw(plaintext, hashed)) == 0); } static String hashpw(String password, String salt); static String gensalt(int log_rounds, SecureRandom random); static String gensalt(int log_rounds); static String gensalt(); boolean checkpw... | @Test public void checkpw_shouldReturnTrueIfPasswordsMatch() throws Exception { Assert.assertTrue(new BCrypt().checkpw("foobar", "$2a$10$riYEc4vydN5ksUpw/c9e0uV643f4qRyeQ2u.NpXW1FOgI4JnIn5dy")); }
@Test public void checkpw_shouldReturnFalseIfPasswordsDontMatch() throws Exception { Assert.assertFalse(new BCrypt().checkp... |
PasswordValidator implements Validator<String> { public static boolean validatePassword(String password) { if (StringUtils.isBlank(password)) { return false; } if (password.length() < 8) { return false; } return true; } @Override void validate(FacesContext context, UIComponent component, String value); static boolean ... | @Test public void validatePassword_shouldReturnTrueIfPasswordGood() throws Exception { Assert.assertTrue(PasswordValidator.validatePassword("12345678")); }
@Test public void validatePassword_shouldReturnFalseIfPasswordEmpty() throws Exception { Assert.assertFalse(PasswordValidator.validatePassword("")); }
@Test public ... |
TileGridBuilder { protected static int countTags(ImageGalleryTile item, Collection<String> tags) { return CollectionUtils.intersection(item.getCategories().stream().map(c -> c.getName()).collect(Collectors.toList()), tags).size(); } TileGridBuilder(HttpServletRequest servletRequest); TileGridBuilder size(int size); Til... | @Test public void testCountTags() { List<String> itemTags = Arrays.asList(new String[] { "tag1", "tag2", "tag3", "other" }); List<CMSCategory> categories = itemTags.stream().map(tag -> getCategory(tag)).collect(Collectors.toList()); List<String> selectionTags = Arrays.asList(new String[] { "tag2", "tag3", "news" }); Li... |
HtmlScriptValidator implements Validator<String> { @Override public void validate(FacesContext context, UIComponent component, String input) throws ValidatorException { if (!validate(input)) { FacesMessage msg = new FacesMessage(ViewerResourceBundle.getTranslation("validate_error_scriptTag", null), ""); msg.setSeverity... | @Test public void test() { Assert.assertTrue("Does not accept <p> tag", new HtmlScriptValidator().validate("abc\njkl h <p>asdasd</p> ashdoha<br/> asdas")); Assert.assertTrue("Does not accept <div> tag with attribute", new HtmlScriptValidator().validate("abc\njkl h <div test=\"asd\">asdasd</div> ashdoha<br/> asdas")); A... |
PIValidator implements Validator<String> { public static boolean validatePi(String pi) { if (StringUtils.isBlank(pi)) { return false; } return !StringUtils.containsAny(pi, ILLEGAL_CHARS); } @Override void validate(FacesContext context, UIComponent component, String value); static boolean validatePi(String pi); } | @Test public void validatePi_shouldReturnFalseIfPiContainsIllegalCharacters() throws Exception { Assert.assertFalse(PIValidator.validatePi("PPN!")); Assert.assertFalse(PIValidator.validatePi("PPN?")); Assert.assertFalse(PIValidator.validatePi("PPN/")); Assert.assertFalse(PIValidator.validatePi("PPN\\")); Assert.assertF... |
HtmlTagValidator implements Validator<String> { @Override public void validate(FacesContext context, UIComponent component, String input) throws ValidatorException { if (!validate(input)) { FacesMessage msg = new FacesMessage(ViewerResourceBundle.getTranslation("validate_error_invalidTag", null), ""); msg.setSeverity(F... | @Test public void test() { Assert.assertFalse("Accepts <p> tag", new HtmlTagValidator().validate("abc\njkl h <p>asdasd</p> ashdoha<br/> asdas")); Assert.assertFalse("Accepts <div> tag with attribute", new HtmlTagValidator().validate("abc\njkl h <div test=\"asd\">asdasd</div> ashdoha<br/> asdas")); Assert.assertTrue("Do... |
EmailValidator implements Validator<String> { public static boolean validateEmailAddress(String email) { if (email == null) { return false; } Matcher m = PATTERN.matcher(email.toLowerCase()); return m.find(); } @Override void validate(FacesContext context, UIComponent component, String value); static boolean validateE... | @Test public void validateEmailAddress_shouldMatchCorrectEmailAddresses() throws Exception { Assert.assertTrue(EmailValidator.validateEmailAddress("a@b.com")); Assert.assertTrue(EmailValidator.validateEmailAddress("A@B.COM")); Assert.assertTrue(EmailValidator.validateEmailAddress("lord.elsington.hallstingdingdingworth@... |
TileGridBuilder { public TileGrid build(List<ImageGalleryTile> items) { if (!tags.isEmpty()) { items = filter(items, tags); } items = items.stream() .filter(item -> tags.isEmpty() || countTags(item, tags) > 0) .sorted(new SemiRandomOrderComparator<ImageGalleryTile>(tile -> tile.getDisplayOrder())) .collect(Collectors.t... | @Test public void testBuild() { List<ImageGalleryTile> items = new ArrayList<>(); CMSMediaItem item1 = new CMSMediaItem(); item1.setId(1l); item1.addCategory(getCategory("tag1")); item1.setPriority(Priority.IMPORTANT); item1.setFileName("file1"); items.add(item1); CMSMediaItem item2 = new CMSMediaItem(); item2.setId(2l... |
AbstractApiUrlManager { static String replaceApiPathParams(String urlString, Object[] pathParams) { return ApiPathParams.replacePathParams(urlString, pathParams); } abstract String getApiUrl(); abstract String getApplicationUrl(); static String subPath(String url, String within); String parseParameter(String template,... | @Test public void replaceApiPathParams_shouldRemoveTrailingSlashIfFileNameContainsPeriod() throws Exception { Assert.assertEquals("http: AbstractApiUrlManager.replaceApiPathParams("http: } |
PdfRequestFilter implements ContainerRequestFilter { static int getNumAllowedPages(int percentage, int numTotalRecordPages) { if (percentage < 0) { throw new IllegalArgumentException("percentage may not be less than 0"); } if (numTotalRecordPages < 0) { throw new IllegalArgumentException("numTotalRecordPages may not be... | @Test public void getNumAllowedPages_shouldReturn0IfPercentage0() throws Exception { Assert.assertEquals(0, PdfRequestFilter.getNumAllowedPages(0, 10)); }
@Test public void getNumAllowedPages_shouldReturn0IfNumberOfPages0() throws Exception { Assert.assertEquals(0, PdfRequestFilter.getNumAllowedPages(50, 0)); }
@Test p... |
RecordFileResource { @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") public String getAlto( @Parameter(description = "Filename of the alto document") @PathParam("filename") String filename) throws Presentation... | @Test public void testGetAlto() throws JDOMException, IOException { String url = urls.path(RECORDS_FILES, RECORDS_FILES_ALTO).params(PI, FILENAME + ".xml").build(); try (Response response = target(url) .request() .accept(MediaType.TEXT_XML) .get()) { assertEquals("Should return status 200", 200, response.getStatus()); ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.