method2testcases
stringlengths 118
6.63k
|
---|
### Question:
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 (sbFullValue.length() > 0) { sbFullValue.append(" > "); } if (sbHierarchy.length() > 0) { sbHierarchy.append('.'); } sbHierarchy.append(s); String displayValue = ViewerResourceBundle.getTranslation(sbHierarchy.toString(), locale); displayValue = StringEscapeUtils.escapeHtml4(displayValue); if (applicationUrl != null) { sbFullValue.append("<a href=\"").append(applicationUrl).append(PageType.browse.getName()).append("/-/1/-/"); if (field != null) { sbFullValue.append(field).append(':'); } sbFullValue.append(sbHierarchy.toString()).append("/\">").append(displayValue).append("</a>"); } else { sbFullValue.append(displayValue); } } return sbFullValue.toString(); } Metadata(); Metadata(String label, String masterValue, String paramValue); Metadata(String label, String masterValue, MetadataParameter param, String paramValue); Metadata(String label, String masterValue, int type, List<MetadataParameter> params, boolean group); Metadata(String label, String masterValue, int type, List<MetadataParameter> params, boolean group, int number); @Override int hashCode(); @Override boolean equals(Object obj); boolean isHasLabel(); String getLabel(); String getMasterValue(); int getType(); List<MetadataValue> getValues(); void setParamValue(int valueIndex, int paramIndex, List<String> inValues, String label, String url, Map<String, String> options,
String groupType, Locale locale); List<MetadataParameter> getParams(); boolean hasParam(String paramName); boolean isBlank(); @SuppressWarnings("unchecked") boolean populate(StructElement se, Locale locale); static String getPersonDisplayName(String aggregatedMetadata); int getNumber(); boolean isGroup(); static List<Metadata> filterMetadataByLanguage(List<Metadata> metadataList, String recordLanguage); @Override String toString(); }### Answer:
@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 > a.b.c > a.b.c.d", value); } } |
### Question:
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(Comment comment, String oldText, Locale locale); boolean mayEdit(User user); String getDisplayDate(Date date); void checkAndCleanScripts(); Long getId(); void setId(Long id); String getPi(); void setPi(String pi); Integer getPage(); void setPage(Integer page); User getOwner(); void setOwner(User owner); void setText(String text); String getText(); String getDisplayText(); String getOldText(); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); }### Answer:
@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 User(); Comment comment = new Comment("PPN123", 1, owner, "comment text", null); Assert.assertFalse(comment.mayEdit(null)); } |
### Question:
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 selectedLocale); @Override int hashCode(); @Override boolean equals(Object obj); @JsonIgnore List<CampaignVisibility> getCampaignVisibilityValues(); long getNumRecords(); long getNumRecordsForStatus(String status); long getNumRecordsToAnnotate(); long getContributorCount(); int getProgress(); long getDaysBeforeStart(); long getDaysLeft(); String getDaysLeftAsString(); boolean isHasStarted(); boolean isHasEnded(); boolean isUserAllowedAction(User user, CampaignRecordStatus status); String getTitle(); void setTitle(String title); String getMenuTitle(); String getMenuTitleOrElseTitle(); String getMenuTitleOrElseTitle(String lang, boolean useFallback); void setMenuTitle(String menuTitle); String getDescription(); void setDescription(String description); String getTitle(String lang); String getTitle(String lang, boolean useFallback); String getDescription(String lang); String getDescription(String lang, boolean useFallback); String getMenuTitle(String lang); String getMenuTitle(String lang, boolean useFallback); @JsonIgnore Long getId(); static Long getId(URI idAsURI); @JsonProperty("id") URI getIdAsURI(); void setId(Long id); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); CampaignVisibility getVisibility(); void setVisibility(CampaignVisibility visibility); Date getDateStart(); void setDateStart(Date dateStart); String getDateStartString(); void setDateStartString(String dateStartString); Date getDateEnd(); void setDateEnd(Date dateEnd); String getDateEndString(); void setDateEndString(String dateEndString); CMSContentItem getContentItem(); String getSolrQuery(); void setSolrQuery(String solrQuery); String getPermalink(); void setPermalink(String permalink); String getBreadcrumbParentCmsPageId(); void setBreadcrumbParentCmsPageId(String breadcrumbParentCmsPageId); List<CampaignTranslation> getTranslations(); void setTranslations(List<CampaignTranslation> translations); List<Question> getQuestions(); void setQuestions(List<Question> questions); Map<String, CampaignRecordStatistic> getStatistics(); void setStatistics(Map<String, CampaignRecordStatistic> statistics); Locale getSelectedLocale(); void setSelectedLocale(Locale selectedLocale); boolean isDirty(); void setDirty(boolean dirty); String getRandomizedTarget(CampaignRecordStatus status, String piToIgnore); boolean isEligibleToEdit(String pi, CampaignRecordStatus status, User user); boolean hasRecordsToReview(User user); boolean hasRecordsToAnnotate(User user); boolean mayAnnotate(User user, String pi); boolean mayReview(User user, String pi); CampaignRecordStatus getRecordStatus(String pi); void setRecordStatus(String pi, CampaignRecordStatus status, Optional<User> user); @Override void setMediaItem(CMSMediaItem item); @Override CMSMediaItem getMediaItem(); @Override @JsonIgnore String getMediaFilter(); @Override boolean hasMediaItem(); @Override @JsonIgnore CategorizableTranslatedSelectable<CMSMediaItem> getMediaItemWrapper(); }### Answer:
@Test public void getDaysLeft_shouldReturn1IfNoDateEnd() throws Exception { Campaign campaign = new Campaign(); Assert.assertEquals(-1, campaign.getDaysLeft()); } |
### Question:
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().getChild("text", null); if (eleText != null && eleText.getChild("body", null) != null) { String language = eleText.getAttributeValue("lang", Namespace.getNamespace("xml", "http: Element eleBody = eleText.getChild("body", null); Element eleNewRoot = new Element("tempRoot"); for (Element ele : eleBody.getChildren()) { eleNewRoot.addContent(ele.clone()); } String ret = XmlTools.getStringFromElement(eleNewRoot, null).replace("<tempRoot>", "").replace("</tempRoot>", "").trim(); ret = ret.replaceAll("<note>[\\s\\S]*?<\\/note>", ""); return ret; } } return null; } static String getTeiFulltext(String tei); static String convertTeiToHtml(String tei); }### Answer:
@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.toFile(), StringTools.DEFAULT_ENCODING); Assert.assertFalse(StringUtils.isEmpty(tei)); Assert.assertTrue(tei.contains("<note>")); String text = TEITools.getTeiFulltext(tei); Assert.assertFalse(StringUtils.isEmpty(text)); Assert.assertFalse(text.contains("<note>")); } |
### Question:
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(); Campaign(Locale selectedLocale); @Override int hashCode(); @Override boolean equals(Object obj); @JsonIgnore List<CampaignVisibility> getCampaignVisibilityValues(); long getNumRecords(); long getNumRecordsForStatus(String status); long getNumRecordsToAnnotate(); long getContributorCount(); int getProgress(); long getDaysBeforeStart(); long getDaysLeft(); String getDaysLeftAsString(); boolean isHasStarted(); boolean isHasEnded(); boolean isUserAllowedAction(User user, CampaignRecordStatus status); String getTitle(); void setTitle(String title); String getMenuTitle(); String getMenuTitleOrElseTitle(); String getMenuTitleOrElseTitle(String lang, boolean useFallback); void setMenuTitle(String menuTitle); String getDescription(); void setDescription(String description); String getTitle(String lang); String getTitle(String lang, boolean useFallback); String getDescription(String lang); String getDescription(String lang, boolean useFallback); String getMenuTitle(String lang); String getMenuTitle(String lang, boolean useFallback); @JsonIgnore Long getId(); static Long getId(URI idAsURI); @JsonProperty("id") URI getIdAsURI(); void setId(Long id); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); CampaignVisibility getVisibility(); void setVisibility(CampaignVisibility visibility); Date getDateStart(); void setDateStart(Date dateStart); String getDateStartString(); void setDateStartString(String dateStartString); Date getDateEnd(); void setDateEnd(Date dateEnd); String getDateEndString(); void setDateEndString(String dateEndString); CMSContentItem getContentItem(); String getSolrQuery(); void setSolrQuery(String solrQuery); String getPermalink(); void setPermalink(String permalink); String getBreadcrumbParentCmsPageId(); void setBreadcrumbParentCmsPageId(String breadcrumbParentCmsPageId); List<CampaignTranslation> getTranslations(); void setTranslations(List<CampaignTranslation> translations); List<Question> getQuestions(); void setQuestions(List<Question> questions); Map<String, CampaignRecordStatistic> getStatistics(); void setStatistics(Map<String, CampaignRecordStatistic> statistics); Locale getSelectedLocale(); void setSelectedLocale(Locale selectedLocale); boolean isDirty(); void setDirty(boolean dirty); String getRandomizedTarget(CampaignRecordStatus status, String piToIgnore); boolean isEligibleToEdit(String pi, CampaignRecordStatus status, User user); boolean hasRecordsToReview(User user); boolean hasRecordsToAnnotate(User user); boolean mayAnnotate(User user, String pi); boolean mayReview(User user, String pi); CampaignRecordStatus getRecordStatus(String pi); void setRecordStatus(String pi, CampaignRecordStatus status, Optional<User> user); @Override void setMediaItem(CMSMediaItem item); @Override CMSMediaItem getMediaItem(); @Override @JsonIgnore String getMediaFilter(); @Override boolean hasMediaItem(); @Override @JsonIgnore CategorizableTranslatedSelectable<CMSMediaItem> getMediaItemWrapper(); }### Answer:
@Test public void getDaysBeforeStart_shouldReturn1IfNoDateStart() throws Exception { Campaign campaign = new Campaign(); Assert.assertEquals(-1, campaign.getDaysBeforeStart()); } |
### Question:
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(); @Override boolean equals(Object obj); @JsonIgnore List<CampaignVisibility> getCampaignVisibilityValues(); long getNumRecords(); long getNumRecordsForStatus(String status); long getNumRecordsToAnnotate(); long getContributorCount(); int getProgress(); long getDaysBeforeStart(); long getDaysLeft(); String getDaysLeftAsString(); boolean isHasStarted(); boolean isHasEnded(); boolean isUserAllowedAction(User user, CampaignRecordStatus status); String getTitle(); void setTitle(String title); String getMenuTitle(); String getMenuTitleOrElseTitle(); String getMenuTitleOrElseTitle(String lang, boolean useFallback); void setMenuTitle(String menuTitle); String getDescription(); void setDescription(String description); String getTitle(String lang); String getTitle(String lang, boolean useFallback); String getDescription(String lang); String getDescription(String lang, boolean useFallback); String getMenuTitle(String lang); String getMenuTitle(String lang, boolean useFallback); @JsonIgnore Long getId(); static Long getId(URI idAsURI); @JsonProperty("id") URI getIdAsURI(); void setId(Long id); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); CampaignVisibility getVisibility(); void setVisibility(CampaignVisibility visibility); Date getDateStart(); void setDateStart(Date dateStart); String getDateStartString(); void setDateStartString(String dateStartString); Date getDateEnd(); void setDateEnd(Date dateEnd); String getDateEndString(); void setDateEndString(String dateEndString); CMSContentItem getContentItem(); String getSolrQuery(); void setSolrQuery(String solrQuery); String getPermalink(); void setPermalink(String permalink); String getBreadcrumbParentCmsPageId(); void setBreadcrumbParentCmsPageId(String breadcrumbParentCmsPageId); List<CampaignTranslation> getTranslations(); void setTranslations(List<CampaignTranslation> translations); List<Question> getQuestions(); void setQuestions(List<Question> questions); Map<String, CampaignRecordStatistic> getStatistics(); void setStatistics(Map<String, CampaignRecordStatistic> statistics); Locale getSelectedLocale(); void setSelectedLocale(Locale selectedLocale); boolean isDirty(); void setDirty(boolean dirty); String getRandomizedTarget(CampaignRecordStatus status, String piToIgnore); boolean isEligibleToEdit(String pi, CampaignRecordStatus status, User user); boolean hasRecordsToReview(User user); boolean hasRecordsToAnnotate(User user); boolean mayAnnotate(User user, String pi); boolean mayReview(User user, String pi); CampaignRecordStatus getRecordStatus(String pi); void setRecordStatus(String pi, CampaignRecordStatus status, Optional<User> user); @Override void setMediaItem(CMSMediaItem item); @Override CMSMediaItem getMediaItem(); @Override @JsonIgnore String getMediaFilter(); @Override boolean hasMediaItem(); @Override @JsonIgnore CategorizableTranslatedSelectable<CMSMediaItem> getMediaItemWrapper(); }### Answer:
@Test public void isHasEnded_shouldReturnFalseIfDateEndNull() throws Exception { Campaign campaign = new Campaign(); Assert.assertFalse(campaign.isHasEnded()); } |
### Question:
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 selectedLocale); @Override int hashCode(); @Override boolean equals(Object obj); @JsonIgnore List<CampaignVisibility> getCampaignVisibilityValues(); long getNumRecords(); long getNumRecordsForStatus(String status); long getNumRecordsToAnnotate(); long getContributorCount(); int getProgress(); long getDaysBeforeStart(); long getDaysLeft(); String getDaysLeftAsString(); boolean isHasStarted(); boolean isHasEnded(); boolean isUserAllowedAction(User user, CampaignRecordStatus status); String getTitle(); void setTitle(String title); String getMenuTitle(); String getMenuTitleOrElseTitle(); String getMenuTitleOrElseTitle(String lang, boolean useFallback); void setMenuTitle(String menuTitle); String getDescription(); void setDescription(String description); String getTitle(String lang); String getTitle(String lang, boolean useFallback); String getDescription(String lang); String getDescription(String lang, boolean useFallback); String getMenuTitle(String lang); String getMenuTitle(String lang, boolean useFallback); @JsonIgnore Long getId(); static Long getId(URI idAsURI); @JsonProperty("id") URI getIdAsURI(); void setId(Long id); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); CampaignVisibility getVisibility(); void setVisibility(CampaignVisibility visibility); Date getDateStart(); void setDateStart(Date dateStart); String getDateStartString(); void setDateStartString(String dateStartString); Date getDateEnd(); void setDateEnd(Date dateEnd); String getDateEndString(); void setDateEndString(String dateEndString); CMSContentItem getContentItem(); String getSolrQuery(); void setSolrQuery(String solrQuery); String getPermalink(); void setPermalink(String permalink); String getBreadcrumbParentCmsPageId(); void setBreadcrumbParentCmsPageId(String breadcrumbParentCmsPageId); List<CampaignTranslation> getTranslations(); void setTranslations(List<CampaignTranslation> translations); List<Question> getQuestions(); void setQuestions(List<Question> questions); Map<String, CampaignRecordStatistic> getStatistics(); void setStatistics(Map<String, CampaignRecordStatistic> statistics); Locale getSelectedLocale(); void setSelectedLocale(Locale selectedLocale); boolean isDirty(); void setDirty(boolean dirty); String getRandomizedTarget(CampaignRecordStatus status, String piToIgnore); boolean isEligibleToEdit(String pi, CampaignRecordStatus status, User user); boolean hasRecordsToReview(User user); boolean hasRecordsToAnnotate(User user); boolean mayAnnotate(User user, String pi); boolean mayReview(User user, String pi); CampaignRecordStatus getRecordStatus(String pi); void setRecordStatus(String pi, CampaignRecordStatus status, Optional<User> user); @Override void setMediaItem(CMSMediaItem item); @Override CMSMediaItem getMediaItem(); @Override @JsonIgnore String getMediaFilter(); @Override boolean hasMediaItem(); @Override @JsonIgnore CategorizableTranslatedSelectable<CMSMediaItem> getMediaItemWrapper(); }### Answer:
@Test public void isHasStarted_shouldReturnTrueIfDateStartNull() throws Exception { Campaign campaign = new Campaign(); Assert.assertTrue(campaign.isHasStarted()); } |
### Question:
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 x2r = x2; double y2r = y2; switch (rotation) { case 270: x1r = y1; y1r = w - x2; x2r = y2; y2r = w - x1; break; case 90: x1r = h - y2; y1r = x1; x2r = h - y1; y2r = x2; break; case 180: x1r = w - x2; y1r = h - y2; x2r = w - x1; y2r = h - y1; ; break; default: } return new Rectangle((int) x1r, (int) y1r, (int) (x2r - x1r), (int) (y2r - y1r)); } static String getFulltext(Path path, String encoding); static String getFullText(String alto, boolean mergeLineBreakWords, HttpServletRequest request); static List<TagCount> getNERTags(String alto, NERTag.Type type); static List<String> getWordCoords(String altoString, Set<String> searchTerms); static String getRotatedCoordinates(String coords, int rotation, Dimension pageSize); static List<String> getWordCoords(String altoString, Set<String> searchTerms, int rotation); static int getMatchALTOWord(Word eleWord, String[] words); static String getALTOCoords(GeometricData element); static final String TAG_LABEL_IGNORE_REGEX; }### Answer:
@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, rect); } |
### Question:
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 mergeLineBreakWords, HttpServletRequest request); static List<TagCount> getNERTags(String alto, NERTag.Type type); static List<String> getWordCoords(String altoString, Set<String> searchTerms); static String getRotatedCoordinates(String coords, int rotation, Dimension pageSize); static List<String> getWordCoords(String altoString, Set<String> searchTerms, int rotation); static int getMatchALTOWord(Word eleWord, String[] words); static String getALTOCoords(GeometricData element); static final String TAG_LABEL_IGNORE_REGEX; }### Answer:
@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() > 100); } |
### Question:
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(); CMSSidebarElement(CMSSidebarElement original, CMSPage owner); static CMSSidebarElement copy(CMSSidebarElement original, CMSPage ownerPage); int compareTo(Object o); @Override int hashCode(); @Override boolean equals(Object o); String getHtml(); void setHtml(String html); Long getId(); void setId(Long id); CMSPage getOwnerPage(); void setOwnerPage(CMSPage ownerPage); String getType(); void setType(String type); String getValue(); void setValue(String value); int getOrder(); void setOrder(int order); String getContent(); boolean hasHtml(); WidgetMode getWidgetMode(); void setWidgetMode(WidgetMode widgetMode); String getCssClass(); void setCssClass(String className); boolean isValid(); SidebarElementType.Category getCategory(); @Override String toString(); int getSortingId(); PageList getLinkedPages(); void setLinkedPages(PageList linkedPages); String getLinkedPagesString(); void setLinkedPagesString(String linkedPagesList); void serialize(); void deSerialize(); Long getGeoMapId(); void setGeoMapId(Long geoMapId); void setGeoMap(GeoMap geoMap); synchronized GeoMap getGeoMap(); String getWidgetTitle(); void setWidgetTitle(String widgetTitle); boolean isHasWidgetTitle(); boolean isHasLinkedPages(); String getWidgetType(); }### Answer:
@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>", CMSSidebarElement.cleanupHtmlTag("<tag />")); } |
### Question:
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(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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 = FileNotFoundException.class) public void getStringFromFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.getStringFromFile(file, null); } |
### Question:
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(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.getStringFromFilePath(file.getPath()); } |
### Question:
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 len; while ((len = fis.read(buffer)) != -1) { gzipOS.write(buffer, 0, len); } } } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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")); } |
### Question:
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 len; while ((len = gis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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")); } |
### Question:
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); try (FileWriterWithEncoding writer = new FileWriterWithEncoding(file, encoding, append)) { writer.write(string); } return file; } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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()); } |
### Question:
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 getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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)); } } |
### Question:
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 String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@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 { Assert.assertEquals("", FileTools.getBottomFolderFromPathString("00000001.xml")); } |
### Question:
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, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getFilenameFromPathString_shouldReturnFileNameCorrectly() throws Exception { Assert.assertEquals("00000001.xml", FileTools.getFilenameFromPathString("data/1/alto/PPN123/00000001.xml")); } |
### Question:
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_639-2T=\"" + isoCode + "\"]"); } if (nodes.isEmpty()) { nodes = config.configurationsAt("language[iso_639-2B=\"" + isoCode + "\"]"); } languageConfig = (SubnodeConfiguration) nodes.get(0); } else if (isoCode.length() == 2) { languageConfig = (SubnodeConfiguration) config.configurationsAt("language[iso_639-1=\"" + isoCode + "\"]").get(0); } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("No matching language found for " + isoCode); } catch (Throwable e) { throw new IllegalArgumentException(e); } if (languageConfig == null) { throw new IllegalArgumentException("No matching language found for " + isoCode); } Language language = createLanguage(languageConfig); return language; } LanguageHelper(String configFilePath); List<Language> getAllLanguages(); List<Language> getMajorLanguages(); Language getLanguage(String isoCode); Language createLanguage(HierarchicalConfiguration languageConfig); }### Answer:
@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")); } |
### Question:
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(fileName, dataRepository, format); } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@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/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", null, SolrConstants._METS)); }
@Test public void getSourceFilePath_shouldConstructLIDOFilePathCorrectly() throws Exception { Assert.assertEquals("src/test/resources/data/viewer/data/1/indexed_lido/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", "1", SolrConstants._LIDO)); Assert.assertEquals("src/test/resources/data/viewer/indexed_lido/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", null, SolrConstants._LIDO)); }
@Test public void getSourceFilePath_shouldConstructDenkXwebFilePathCorrectly() throws Exception { Assert.assertEquals("src/test/resources/data/viewer/data/1/indexed_denkxweb/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", "1", SolrConstants._DENKXWEB)); Assert.assertEquals("src/test/resources/data/viewer/indexed_denkxweb/PPN123.xml", DataFileTools.getSourceFilePath("PPN123.xml", null, SolrConstants._DENKXWEB)); }
@Test(expected = IllegalArgumentException.class) public void getSourceFilePath_shouldThrowIllegalArgumentExceptionIfFileNameIsNull() throws Exception { DataFileTools.getSourceFilePath(null, null, SolrConstants._METS); }
@Test(expected = IllegalArgumentException.class) public void getSourceFilePath_shouldThrowIllegalArgumentExceptionIfFormatIsUnknown() throws Exception { DataFileTools.getSourceFilePath("1.xml", null, "bla"); } |
### Question:
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 getDataFolder(pi, dataFolderName, dataRepository); } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@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_shouldReturnCorrectFolderIfDataRepositoryUsed() throws Exception { { Path folder = DataFileTools.getDataFolder("PPN123", "media", "1"); Assert.assertEquals(Paths.get("src/test/resources/data/viewer/data/1/media/PPN123"), folder); } { Path folder = DataFileTools.getDataFolder("PPN123", "media", "/opt/digiverso/data/1/"); Assert.assertEquals(Paths.get("/opt/digiverso/data/1/media/PPN123"), folder); } } |
### Question:
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("Check tag '{}' for validity", tag); if (disallowedTags != null && disallowedTags.contains(tag)) { logger.debug("Tag '{}' is not allowed in sidebar widget HTML.", tag); return false; } } } return true; } CMSSidebarElement(); CMSSidebarElement(CMSSidebarElement original, CMSPage owner); static CMSSidebarElement copy(CMSSidebarElement original, CMSPage ownerPage); int compareTo(Object o); @Override int hashCode(); @Override boolean equals(Object o); String getHtml(); void setHtml(String html); Long getId(); void setId(Long id); CMSPage getOwnerPage(); void setOwnerPage(CMSPage ownerPage); String getType(); void setType(String type); String getValue(); void setValue(String value); int getOrder(); void setOrder(int order); String getContent(); boolean hasHtml(); WidgetMode getWidgetMode(); void setWidgetMode(WidgetMode widgetMode); String getCssClass(); void setCssClass(String className); boolean isValid(); SidebarElementType.Category getCategory(); @Override String toString(); int getSortingId(); PageList getLinkedPages(); void setLinkedPages(PageList linkedPages); String getLinkedPagesString(); void setLinkedPagesString(String linkedPagesList); void serialize(); void deSerialize(); Long getGeoMapId(); void setGeoMapId(Long geoMapId); void setGeoMap(GeoMap geoMap); synchronized GeoMap getGeoMap(); String getWidgetTitle(); void setWidgetTitle(String widgetTitle); boolean isHasWidgetTitle(); boolean isHasLinkedPages(); String getWidgetType(); }### Answer:
@Test public void isValidTest() { String html = "<dl>dsdf <br /> sadasdsdf</dl>"; CMSSidebarElement element = new CMSSidebarElement(); element.setHtml(html); assertTrue(element.isValid()); } |
### Question:
DataFileTools { static String getDataRepositoryPath(String dataRepositoryPath) { if (StringUtils.isBlank(dataRepositoryPath)) { return DataManager.getInstance().getConfiguration().getViewerHome(); } if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryPath)).isAbsolute()) { return dataRepositoryPath + '/'; } return DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + dataRepositoryPath + '/'; } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForEmptyDataRepository() throws Exception { Assert.assertEquals(DataManager.getInstance().getConfiguration().getViewerHome(), DataFileTools.getDataRepositoryPath(null)); }
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForDataRepositoryName() throws Exception { Assert.assertEquals(DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + "1/", DataFileTools.getDataRepositoryPath("1")); }
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForAbsoluteDataRepositoryPath() throws Exception { Assert.assertEquals("/opt/digiverso/viewer/1/", DataFileTools.getDataRepositoryPath("/opt/digiverso/viewer/1")); } |
### Question:
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 pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@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", DataFileTools.sanitizeFileName("/foo.bar")); } |
### Question:
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 isLanguageComplete(Locale locale); boolean isHasCmsPage(); Optional<Long> getCmsPageId(); void setCmsPageId(Long cmsPageId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetPageName() { Assert.assertEquals("test", page.getPageName()); } |
### Question:
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); static LocalDateTime parseDateTimeFromString(String dateString, boolean fromUTC, Integer zoneOffset); static Date parseDateFromString(String dateString); static Date convertLocalDateTimeToDateViaInstant(LocalDateTime dateToConvert, boolean utc); static LocalDateTime convertDateToLocalDateTimeViaInstant(Date dateToConvert); static String format(Date date, DateTimeFormatter formatter, boolean utc); static String format(LocalDateTime localDateTime, DateTimeFormatter formatter, boolean utc); static String getLocalDate(Date date, String language); static String formatDate(Date date, Locale locale); static Date createDate(int year, int month, int dayofMonth, int hour, int minute); static Date createDate(int year, int month, int dayofMonth, int hour, int minute, boolean useUTC); static DateTimeFormatter formatterISO8601Full; static DateTimeFormatter formatterISO8601DateTimeInstant; static DateTimeFormatter formatterISO8601DateTimeWithOffset; static java.time.format.DateTimeFormatter formatterISO8601Date; static java.time.format.DateTimeFormatter formatterISO8601Time; static DateTimeFormatter formatterISO8601DateReverse; static DateTimeFormatter formatterISO8601YearMonth; static DateTimeFormatter formatterISO8601DateTime; static DateTimeFormatter formatterISO8601DateTimeMS; static DateTimeFormatter formatterDEDate; static DateTimeFormatter formatterENDate; static DateTimeFormatter formatterCNDate; static DateTimeFormatter formatterJPDate; static DateTimeFormatter formatterDEDateTime; static DateTimeFormatter formatterENDateTime; static DateTimeFormatter formatterDEDateTimeNoSeconds; static DateTimeFormatter formatterENDateTimeNoSeconds; static DateTimeFormatter formatterISO8601BasicDateNoYear; static DateTimeFormatter formatterISO8601BasicDate; static DateTimeFormatter formatterISO8601BasicDateTime; }### Answer:
@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.MONTH)); Assert.assertEquals(31, cal.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(9, cal.get(Calendar.HOUR_OF_DAY)); Assert.assertEquals(43, cal.get(Calendar.MINUTE)); } |
### Question:
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].trim(); } } return address; } static String[] callUrlGET(String url); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@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")); } |
### Question:
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(); } static String[] callUrlGET(String url); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@Test public void scrambleEmailAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("foo*****com", NetTools.scrambleEmailAddress("[email protected]")); } |
### Question:
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); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@Test public void scrambleIpAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("192.168.X.X", NetTools.scrambleIpAddress("192.168.0.1")); } |
### Question:
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"); } String fileName = pi + (createTraceDocument ? ".delete" : ".purge"); Path file = Paths.get(hotfolderPath.toAbsolutePath().toString(), fileName); try { Files.createFile(file); } catch (FileAlreadyExistsException e) { logger.warn(e.getMessage()); } return (Files.isRegularFile(file)); } static void triggerReIndexRecord(String pi); static synchronized boolean reIndexRecord(String pi); static synchronized boolean reIndexPage(String pi, int page); static synchronized boolean deleteRecord(String pi, boolean createTraceDocument, Path hotfolderPath); static final String SUFFIX_FULLTEXT_CROWDSOURCING; static final String SUFFIX_ALTO_CROWDSOURCING; static final String SUFFIX_USER_GENERATED_CONTENT; static final String SUFFIX_ANNOTATIONS; static final String SUFFIX_CMS; }### Answer:
@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().toString(), "PPN123.delete"); try { Assert.assertTrue(IndexerTools.deleteRecord("PPN123", true, hotfolder)); Assert.assertTrue(Files.isRegularFile(file)); } finally { if (Files.isRegularFile(file)) { Files.delete(file); } if (!Files.isDirectory(hotfolder)) { Files.delete(hotfolder); } } }
@Test public void deleteRecord_shouldCreatePurgeFileCorrectly() 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().toString(), "PPN123.purge"); try { Assert.assertTrue(IndexerTools.deleteRecord("PPN123", false, hotfolder)); Assert.assertTrue(Files.isRegularFile(file)); } finally { if (Files.isRegularFile(file)) { Files.delete(file); } if (!Files.isDirectory(hotfolder)) { Files.delete(hotfolder); } } } |
### Question:
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,
String languageToTranslate); static JSONObject getAsJson(SolrDocument doc, Locale locale); static JSONObject translateJSONObject(Locale locale, JSONObject object); static JSONArray getDateCentricRecordJsonArray(SolrDocumentList result, HttpServletRequest request); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl, String language); static String formatVersionString(String json); static String shortFormatVersionString(String json); }### Answer:
@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.getResults().isEmpty()); SolrDocument doc = response.getResults().get(0); JSONObject json = JsonTools.getRecordJsonObject(doc, rootUrl); Assert.assertNotNull(json); Assert.assertTrue(json.has("id")); Assert.assertEquals(PI, json.get("id")); Assert.assertEquals(doc.getFieldValue(SolrConstants.TITLE), json.get("title")); Assert.assertEquals(doc.getFieldValue(SolrConstants.DATECREATED), json.get("dateCreated")); Assert.assertEquals(doc.getFieldValue(SolrConstants.DC), json.get("collection")); Assert.assertTrue("Thumbnail url was " + ((String) json.get("thumbnailUrl")), ((String) json.get("thumbnailUrl")) .contains("records/" + PI + "/files/images/" + doc.getFieldValue(SolrConstants.THUMBNAIL) + "/full/!100,120/0/default.jpg")); Assert.assertTrue("Image url was " + ((String) json.get("thumbnailUrl")), ((String) json.get("mediumimage")) .contains("records/" + PI + "/files/images/" + doc.getFieldValue(SolrConstants.THUMBNAIL) + "/full/!600,500/0/default.jpg")); Assert.assertEquals(rootUrl + "/" + PageType.viewObject.getName() + "/" + PI + "/1/LOG_0000/", json.get("url")); } |
### Question:
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("version") + " " + jsonObj.getString("build-date") + " " + jsonObj.getString("git-revision"); } catch (JSONException e) { logger.error(e.getMessage()); return notAvailableKey; } } static JSONArray getRecordJsonArray(SolrDocumentList result, Map<String, SolrDocumentList> expanded, HttpServletRequest request,
String languageToTranslate); static JSONObject getAsJson(SolrDocument doc, Locale locale); static JSONObject translateJSONObject(Locale locale, JSONObject object); static JSONArray getDateCentricRecordJsonArray(SolrDocumentList result, HttpServletRequest request); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl, String language); static String formatVersionString(String json); static String shortFormatVersionString(String json); }### Answer:
@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\"}")); }
@Test public void formatVersionString_shouldReturnNotAvailableKeyIfJsonInvalid() throws Exception { Assert.assertEquals("admin__dashboard_versions_not_available", JsonTools.formatVersionString("not json")); } |
### Question:
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> getCmsPageOptional(); CMSPage getCmsPage(); void setCmsPage(CMSPage cmsPage); Long getId(); String getPageName(); boolean isLanguageComplete(Locale locale); boolean isHasCmsPage(); Optional<Long> getCmsPageId(); void setCmsPageId(Long cmsPageId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testIsLanguageComplete() { Assert.assertFalse(page.isLanguageComplete(Locale.GERMANY)); } |
### Question:
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("git-revision") + ")"; } catch (JSONException e) { logger.error(e.getMessage()); return notAvailableKey; } } static JSONArray getRecordJsonArray(SolrDocumentList result, Map<String, SolrDocumentList> expanded, HttpServletRequest request,
String languageToTranslate); static JSONObject getAsJson(SolrDocument doc, Locale locale); static JSONObject translateJSONObject(Locale locale, JSONObject object); static JSONArray getDateCentricRecordJsonArray(SolrDocumentList result, HttpServletRequest request); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl); static JSONObject getRecordJsonObject(SolrDocument doc, String rootUrl, String language); static String formatVersionString(String json); static String shortFormatVersionString(String json); }### Answer:
@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 shortFormatVersionString_shouldReturnNotAvailableKeyIfJsonInvalid() throws Exception { Assert.assertEquals("admin__dashboard_versions_not_available", JsonTools.shortFormatVersionString("not json")); } |
### Question:
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, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@Test public void escapeHtmlChars_shouldEscapeAllCharactersCorrectly() throws Exception { Assert.assertEquals("<i>"A&B"</i>", StringTools.escapeHtmlChars("<i>\"A&B\"</i>")); } |
### Question:
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"); } return StringUtils.replaceEach(str, replace, replaceWith); } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@Test public void replaceCharacters_shouldReplaceCharactersCorrectly() throws Exception { Assert.assertEquals("|-|3110", StringTools.replaceCharacters("Hello", new String[] { "H", "e", "l", "o" }, new String[] { "|-|", "3", "1", "0" })); } |
### Question:
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>", replaceWith) .replaceAll("<br\\s*/>", replaceWith); } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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("foo<br>bar", " ")); Assert.assertEquals("foo bar", StringTools.removeLineBreaks("foo<br/>bar", " ")); Assert.assertEquals("foo bar", StringTools.removeLineBreaks("foo<br />bar", " ")); } |
### Question:
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); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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")); } |
### Question:
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, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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.assertEquals(reference, escaped); } |
### Question:
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 "png": case "jp2": return true; default: return false; } } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@Test public void isImageUrl_shouldReturnTrueForImageUrls() throws Exception { Assert.assertTrue(StringTools.isImageUrl("https: Assert.assertTrue(StringTools.isImageUrl("https: } |
### Question:
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 getPageName(); boolean isLanguageComplete(Locale locale); boolean isHasCmsPage(); Optional<Long> getCmsPageId(); void setCmsPageId(Long cmsPageId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testHasCmsPage() { Assert.assertFalse(page.isHasCmsPage()); } |
### Question:
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.group(1); StringBuilder sbMain = new StringBuilder(); StringBuilder sbNum = new StringBuilder(); for (char c : oldName.toCharArray()) { if (Character.isDigit(c)) { sbNum.append(c); } else { sbMain.append(c); } } replacements.put(oldName, sbMain.toString() + sbNum.toString()); } } if (!replacements.isEmpty()) { for (String key : replacements.keySet()) { html = html.replace(key, replacements.get(key)); } } return html; } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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.assertNotNull(html); Assert.assertTrue(html.contains(".20Formatvorlage")); Assert.assertTrue(html.contains("class=\"20Formatvorlage")); html = StringTools.renameIncompatibleCSSClasses(html); Assert.assertFalse(html.contains(".20Formatvorlage")); Assert.assertFalse(html.contains("class=\"20Formatvorlage")); Assert.assertTrue(html.contains(".Formatvorlage20")); Assert.assertTrue(html.contains("class=\"Formatvorlage20")); } |
### Question:
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) : new String[] { collection }; List<String> ret = new ArrayList<>(hierarchy.length); StringBuilder sb = new StringBuilder(); for (String level : hierarchy) { if (sb.length() > 0) { sb.append(split); } sb.append(level); ret.add(sb.toString()); } return ret; } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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", result.get(2)); Assert.assertEquals("a.b.c.d", result.get(3)); }
@Test public void getHierarchyForCollection_shouldReturnSingleValueCorrectly() throws Exception { List<String> result = StringTools.getHierarchyForCollection("a", "."); Assert.assertEquals(1, result.size()); Assert.assertEquals("a", result.get(0)); } |
### Question:
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[1].trim() + ", " + (Integer.parseInt(rectSplit[0].trim()) + Integer.parseInt(rectSplit[2].trim()) + ", " + (Integer.parseInt(rectSplit[1].trim()) + Integer.parseInt(rectSplit[3].trim()))); } return ret; } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@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 { Assert.assertEquals("1, 2, 3, 4", StringTools.normalizeWebAnnotationCoordinates("1, 2, 3, 4")); } |
### Question:
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 = new StringBuffer(); for (byte element : messageDigest) { String hex = Integer.toHexString(0xFF & element); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } answer = hexString.toString(); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } return answer; } static String encodeUrl(String string); static String decodeUrl(String string); static Optional<String> findFirstMatch(String text, String regex, int group); static String escapeHtmlChars(String str); static String escapeHtmlLtGt(String str); static String removeDiacriticalMarks(String s); static String removeLineBreaks(String s, String replaceWith); static String stripJS(String s); static int getLength(String s); static String escapeHtml(String text); static String escapeQuotes(String s); static String convertStringEncoding(String string, String from, String to); static boolean isImageUrl(String url); static String renameIncompatibleCSSClasses(String html); static List<String> getHierarchyForCollection(String collection, String split); static String normalizeWebAnnotationCoordinates(String coords); static String getMatch(String s, String pattern); static String intern(String string); static String generateMD5(String myString); static final String REGEX_QUOTATION_MARKS; static final String REGEX_PARENTHESES; static final String REGEX_PARENTESES_DATES; static final String REGEX_BRACES; static final String REGEX_WORDS; static final String DEFAULT_ENCODING; }### Answer:
@Test public void generateMD5_shouldHashStringCorrectly() throws Exception { Assert.assertEquals("098f6bcd4621d373cade4e832627b4f6", StringTools.generateMD5("test")); } |
### Question:
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(String plaintext, String hashed); }### Answer:
@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().checkpw("barfoo", "$2a$10$riYEc4vydN5ksUpw/c9e0uV643f4qRyeQ2u.NpXW1FOgI4JnIn5dy")); } |
### Question:
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 validatePassword(String password); }### Answer:
@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 void validatePassword_shouldReturnFalseIfPasswordBlank() throws Exception { Assert.assertFalse(PasswordValidator.validatePassword(" ")); }
@Test public void validatePassword_shouldReturnFalseIfPasswordTooShort() throws Exception { Assert.assertFalse(PasswordValidator.validatePassword("1234567")); } |
### Question:
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); TileGridBuilder reserveForHighPriority(int reserve); TileGridBuilder tags(Collection<String> tags); TileGridBuilder tags(String... tags); TileGrid build(List<ImageGalleryTile> items); TileGridBuilder language(String language); }### Answer:
@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" }); List<CMSCategory> selectionCategories = selectionTags.stream().map(tag -> getCategory(tag)).collect(Collectors.toList()); CMSMediaItem item = new CMSMediaItem(); item.setCategories(categories); Assert.assertEquals(2, TileGridBuilder.countTags(item, selectionCategories.stream().map(c -> c.getName()).collect(Collectors.toList()))); } |
### Question:
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(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } @Override void validate(FacesContext context, UIComponent component, String input); boolean validate(String input); }### Answer:
@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")); Assert.assertTrue("Does not accept text with em and br", new HtmlScriptValidator().validate("abc\njkl h <em>asdasd</em> ashdoha<br/> asdas")); Assert.assertTrue("Does not accept text with em with attribute", new HtmlScriptValidator().validate("abc\njkl h <em test=\"asd\">asdasd</em> ashdoha<br/> asdas")); Assert.assertFalse("Accepts text with script tag", new HtmlScriptValidator().validate("abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas")); Assert.assertFalse("Accepts <script> tag in html body", new HtmlScriptValidator() .validate("<head><p>asdas</p></head> <body>abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas</body>")); Assert.assertTrue("Does not accept <body> tag with <div>", new HtmlScriptValidator().validate("<body>abc\njkl h <div type=\"hidden\">asdasd</div> ashdoha<br/> asdas")); Assert.assertFalse("Accepts <body> tag with <script>", new HtmlScriptValidator() .validate("<head></head><body>abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas</body>")); Assert.assertFalse("Accepts <script> tag in html", new HtmlScriptValidator().validate("<html><script>var i = 1;</script><head></head><body>asdas</body></html>")); Assert.assertFalse("Accepts pure <script> tag", new HtmlScriptValidator().validate("<script>var i = 1;</script>")); } |
### Question:
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); }### Answer:
@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.assertFalse(PIValidator.validatePi("PPN:")); }
@Test public void validatePi_shouldReturnFalseIfPiEmptyBlankOrNull() throws Exception { Assert.assertFalse(PIValidator.validatePi(null)); Assert.assertFalse(PIValidator.validatePi("")); Assert.assertFalse(PIValidator.validatePi(" ")); }
@Test public void validatePi_shouldReturnTrueIfPiGood() throws Exception { Assert.assertTrue(PIValidator.validatePi("PPN123456789")); } |
### Question:
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(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } @Override void validate(FacesContext context, UIComponent component, String input); boolean validate(String input); }### Answer:
@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("Does not accept text with em and br", new HtmlTagValidator().validate("abc\njkl h <em>asdasd</em> ashdoha<br/> asdas")); Assert.assertTrue("Does not accept text with em with attribute", new HtmlTagValidator().validate("abc\njkl h <em test=\"asd\">asdasd</em> ashdoha<br/> asdas")); Assert.assertFalse("Accepts text with script tag", new HtmlTagValidator().validate("abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas")); Assert.assertFalse("Accepts tags in header", new HtmlTagValidator() .validate("<head><p>asdas</p></head> <body>abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas</body>")); Assert.assertFalse("Accepts <body> tag with <div>", new HtmlTagValidator().validate("<body>abc\njkl h <div type=\"hidden\">asdasd</div> ashdoha<br/> asdas")); Assert.assertFalse("Accepts <body> tag with <script>", new HtmlTagValidator().validate("<head></head><body>abc\njkl h <script type=\"hidden\">asdasd</script> ashdoha<br/> asdas</body>")); Assert.assertFalse("Accepts <script> tag in html", new HtmlTagValidator().validate("<html><script>var i = 1;</script><head></head><body>asdas</body></html>")); Assert.assertFalse("Accepts pure <script> tag", new HtmlTagValidator().validate("<script>var i = 1;</script>")); } |
### Question:
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 validateEmailAddress(String email); }### Answer:
@Test public void validateEmailAddress_shouldMatchCorrectEmailAddresses() throws Exception { Assert.assertTrue(EmailValidator.validateEmailAddress("[email protected]")); Assert.assertTrue(EmailValidator.validateEmailAddress("[email protected]")); Assert.assertTrue(EmailValidator.validateEmailAddress("lord.elsington.hallstingdingdingworth@royal.chamber.of.carpetbaggery.co.uk")); }
@Test public void validateEmailAddress_shouldMatchEntireEmailAddressOnly() throws Exception { Assert.assertFalse(EmailValidator.validateEmailAddress("[email protected]###")); }
@Test public void validateEmailAddress_shouldNotMatchInvalidAddresses() throws Exception { Assert.assertFalse(EmailValidator.validateEmailAddress("blup")); } |
### Question:
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.toList()); List<ImageGalleryTile> priorityItems = filter(items, Priority.IMPORTANT); priorityItems = priorityItems.subList(0, Math.min(gridSize, Math.min(priorityItems.size(), reserveForHighPriority))); List<ImageGalleryTile> defaultItems = filter(items, Priority.DEFAULT); defaultItems = defaultItems.subList(0, Math.min(defaultItems.size(), gridSize - priorityItems.size())); items = new ArrayList<>(); items.addAll(priorityItems); items.addAll(defaultItems); return new TileGrid(items, tags, language, request); } TileGridBuilder(HttpServletRequest servletRequest); TileGridBuilder size(int size); TileGridBuilder reserveForHighPriority(int reserve); TileGridBuilder tags(Collection<String> tags); TileGridBuilder tags(String... tags); TileGrid build(List<ImageGalleryTile> items); TileGridBuilder language(String language); }### Answer:
@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); item2.addCategory(getCategory("tag2")); item2.setPriority(Priority.IMPORTANT); item2.setFileName("file2"); items.add(item2); CMSMediaItem item3 = new CMSMediaItem(); item3.setId(3l); item3.addCategory(getCategory("tag1")); item3.setPriority(Priority.DEFAULT); item3.setFileName("file3"); items.add(item3); CMSMediaItem item4 = new CMSMediaItem(); item4.setId(4l); item4.addCategory(getCategory("tag1")); item4.setPriority(Priority.DEFAULT); item4.setFileName("file4"); items.add(item4); for (int i = 0; i < 20; i++) { TileGrid grid = new TileGridBuilder(null).size(2).reserveForHighPriority(1).tags("tag1").build(items); Assert.assertEquals(2, grid.getItems().size()); Assert.assertTrue("Grid does not contain " + item1, contains(grid.getItems(), item1)); Assert.assertTrue("Grid does not contain item 3 or 4: " + grid, contains(grid.getItems(), item3) || contains(grid.getItems(), item4)); } } |
### Question:
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, String url, String parameter); String getApiPath(); ApiPath path(String... paths); ApiInfo getInfo(); }### Answer:
@Test public void replaceApiPathParams_shouldRemoveTrailingSlashIfFileNameContainsPeriod() throws Exception { Assert.assertEquals("http: AbstractApiUrlManager.replaceApiPathParams("http: } |
### Question:
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 less than 0"); } if (numTotalRecordPages == 0 || percentage == 0) { return 0; } if (percentage == 100) { return numTotalRecordPages; } return (int) Math.floor(((double) numTotalRecordPages / 100 * percentage)); } @Override void filter(ContainerRequestContext request); }### Answer:
@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 public void getNumAllowedPages_shouldReturnNumberOfPagesIfPercentage100() throws Exception { Assert.assertEquals(10, PdfRequestFilter.getNumAllowedPages(100, 10)); }
@Test public void getNumAllowedPages_shouldCalculateNumberCorrectly() throws Exception { Assert.assertEquals(35, PdfRequestFilter.getNumAllowedPages(35, 100)); Assert.assertEquals(3, PdfRequestFilter.getNumAllowedPages(35, 10)); Assert.assertEquals(1, PdfRequestFilter.getNumAllowedPages(19, 10)); Assert.assertEquals(0, PdfRequestFilter.getNumAllowedPages(9, 10)); } |
### Question:
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 PresentationException, IndexUnreachableException, ContentNotFoundException, ServiceNotAllowedException, DAOException { checkFulltextAccessConditions(pi, filename); if (servletResponse != null) { servletResponse.setCharacterEncoding(StringTools.DEFAULT_ENCODING); } return builder.getAltoDocument(pi, filename); } RecordFileResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") String getAlto(
@Parameter(description = "Filename of the alto document") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") String getPlaintext(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") String getTEI(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") Response getPDF(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) StreamingOutput getSourceFile(
@Parameter(description = "Source file name") @PathParam("filename") String filename); }### Answer:
@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()); String data = response.readEntity(String.class); assertTrue(StringUtils.isNotBlank(data)); } } |
### Question:
RecordFileResource { @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") public String getPlaintext( @Parameter(description = "Filename containing the text") @PathParam("filename") String filename) throws ContentNotFoundException, PresentationException, IndexUnreachableException, DAOException, ServiceNotAllowedException { checkFulltextAccessConditions(pi, filename); if (servletResponse != null) { servletResponse.setCharacterEncoding(StringTools.DEFAULT_ENCODING); } return builder.getFulltext(pi, filename); } RecordFileResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") String getAlto(
@Parameter(description = "Filename of the alto document") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") String getPlaintext(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") String getTEI(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") Response getPDF(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) StreamingOutput getSourceFile(
@Parameter(description = "Source file name") @PathParam("filename") String filename); }### Answer:
@Test public void testGetPlaintext() throws JDOMException, IOException { String url = urls.path(RECORDS_FILES, RECORDS_FILES_PLAINTEXT).params(PI, FILENAME + ".txt").build(); try (Response response = target(url) .request() .accept(MediaType.TEXT_PLAIN) .get()) { assertEquals(response.getStatusInfo().getReasonPhrase(), 200, response.getStatus()); String data = response.readEntity(String.class); assertTrue(StringUtils.isNotBlank(data)); } } |
### Question:
RecordFileResource { @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") public String getTEI( @Parameter(description = "Filename containing the text") @PathParam("filename") String filename) throws PresentationException, IndexUnreachableException, DAOException, ContentLibException { checkFulltextAccessConditions(pi, filename); if (servletResponse != null) { servletResponse.setCharacterEncoding(StringTools.DEFAULT_ENCODING); } return builder.getFulltextAsTEI(pi, filename); } RecordFileResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") String getAlto(
@Parameter(description = "Filename of the alto document") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") String getPlaintext(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") String getTEI(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") Response getPDF(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) StreamingOutput getSourceFile(
@Parameter(description = "Source file name") @PathParam("filename") String filename); }### Answer:
@Test public void testGetTEI() throws JDOMException, IOException { String url = urls.path(RECORDS_FILES, RECORDS_FILES_TEI).params(PI, FILENAME + ".xml").build(); try (Response response = target(url) .request() .accept(MediaType.TEXT_XML) .get()) { assertEquals(response.getStatusInfo().getReasonPhrase(), 200, response.getStatus()); String data = response.readEntity(String.class); assertTrue(StringUtils.isNotBlank(data)); } } |
### Question:
RecordFileResource { @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") public Response getPDF( @Parameter(description = "Filename containing the text") @PathParam("filename") String filename) throws ContentLibException { logger.trace("getPDF: {}/{}", pi, filename); String url = urls.path(RECORDS_FILES_IMAGE, RECORDS_FILES_IMAGE_PDF).params(pi, filename).build(); try { Response resp = Response.seeOther(PathConverter.toURI(url)).build(); return resp; } catch (URISyntaxException e) { throw new ContentLibException("Cannot create redirect url to " + url); } } RecordFileResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") String getAlto(
@Parameter(description = "Filename of the alto document") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") String getPlaintext(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") String getTEI(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") Response getPDF(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) StreamingOutput getSourceFile(
@Parameter(description = "Source file name") @PathParam("filename") String filename); }### Answer:
@Test public void testGetPdf() { String url = urls.path(RECORDS_FILES, RECORDS_FILES_PDF).params(PI, FILENAME).build(); try (Response response = target(url) .request() .accept("application/pdf") .get()) { assertEquals(response.getStatusInfo().getReasonPhrase(), 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); byte[] entity = response.readEntity(byte[].class); assertTrue(entity.length >= 5 * 5 * 8 * 3); } } |
### Question:
RecordFileResource { @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) public StreamingOutput getSourceFile( @Parameter(description = "Source file name") @PathParam("filename") String filename) throws ContentLibException, PresentationException, IndexUnreachableException, DAOException { Path path = DataFileTools.getDataFilePath(pi, DataManager.getInstance().getConfiguration().getOrigContentFolder(), null, filename); if (!Files.isRegularFile(path)) { throw new ContentNotFoundException("Source file " + filename + " not found"); } boolean access = !AccessConditionUtils.checkContentFileAccessPermission(pi, servletRequest, Collections.singletonList(path)) .containsValue(Boolean.FALSE); if (!access) { throw new ServiceNotAllowedException("Access to source file " + filename + " not allowed"); } try { String contentType = Files.probeContentType(path); logger.trace("content type: {}", contentType); if (StringUtils.isNotBlank(contentType)) { servletResponse.setContentType(contentType); } servletResponse.setHeader("Content-Disposition", new StringBuilder("attachment;filename=").append(filename).toString()); servletResponse.setHeader("Content-Length", String.valueOf(Files.size(path))); } catch (IOException e) { logger.error("Failed to probe file content type"); } return (out) -> { try (InputStream in = Files.newInputStream(path)) { IOUtils.copy(in, out); } }; } RecordFileResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @GET @javax.ws.rs.Path(RECORDS_FILES_ALTO) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get Alto fulltext for a single page") String getAlto(
@Parameter(description = "Filename of the alto document") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PLAINTEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records" }, summary = "Get plaintext for a single page") String getPlaintext(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_TEI) @Produces({ MediaType.TEXT_XML }) @Operation(tags = { "records" }, summary = "Get fulltext for a single page in TEI format") String getTEI(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_PDF) @Produces({ "application/pdf" }) @Operation(tags = { "records" }, summary = "Non-canonical URL to PDF file") Response getPDF(
@Parameter(description = "Filename containing the text") @PathParam("filename") String filename); @GET @javax.ws.rs.Path(RECORDS_FILES_SOURCE) @Operation(tags = { "records" }, summary = "Get source files of record") @Produces(MediaType.APPLICATION_OCTET_STREAM) StreamingOutput getSourceFile(
@Parameter(description = "Source file name") @PathParam("filename") String filename); }### Answer:
@Test public void testGetSourceFile() { String url = urls.path(RECORDS_FILES, RECORDS_FILES_SOURCE).params(PI, "text.txt").build(); try (Response response = target(url) .request() .get()) { assertEquals(response.getStatusInfo().getReasonPhrase(), 200, response.getStatus()); String contentType = response.getHeaderString("Content-Type"); String entity = response.readEntity(String.class); assertEquals("application/octet-stream", contentType); assertEquals("apples", entity.trim()); } } |
### Question:
SemiRandomOrderComparator implements Comparator<T> { @Override public int compare(T a, T b) { Integer nA = comparisonOperator.apply(a); Integer nB = comparisonOperator.apply(b); if (nA.equals(0)) { nA = Integer.MAX_VALUE; } if (nB.equals(0)) { nB = Integer.MAX_VALUE; } if (nA.equals(nB)) { return Integer.compare(valueFor(a), valueFor(b)); } else { int res = nA.compareTo(nB); return res; } } SemiRandomOrderComparator(Function<T, Integer> comparisonOperator); @Override int compare(T a, T b); }### Answer:
@Test public void testComparatorContract() { Random picker = new Random(System.nanoTime()); for (int i = 0; i < testRuns; i++) { SortTestObject o1 = testArray[picker.nextInt(testArray.length)]; SortTestObject o2 = testArray[picker.nextInt(testArray.length)]; SemiRandomOrderComparator<SortTestObject> comparator = new SemiRandomOrderComparator<>(o -> o.number); int resA = comparator.compare(o1, o2); int resB = comparator.compare(o2, o1); Assert.assertEquals("Contract violated for " + o1 + ", " + o2, -Math.signum(resA), Math.signum(resB), 0.0); } for (int i = 0; i < testRuns; i++) { SortTestObject o1 = testArray[picker.nextInt(testArray.length)]; SortTestObject o2 = testArray[picker.nextInt(testArray.length)]; SortTestObject o3 = testArray[picker.nextInt(testArray.length)]; SemiRandomOrderComparator<SortTestObject> comparator = new SemiRandomOrderComparator<>(o -> o.number); int resA = comparator.compare(o1, o2); int resB = comparator.compare(o2, o3); int resC = comparator.compare(o1, o3); if (resA > 0 && resB > 0) { Assert.assertEquals("Contract violated for " + o1 + ", " + o2 + ", " + o3, 1.0, Math.signum(resC), 0.0); } else if (resA < 0 && resB < 0) { Assert.assertEquals("Contract violated for " + o1 + ", " + o2 + ", " + o3, -1.0, Math.signum(resC), 0.0); } else if (resA == 0) { Assert.assertEquals("Contract violated for " + o1 + ", " + o2 + ", " + o3, Math.signum(resB), Math.signum(resC), 0.0); } else if (resB == 0) { Assert.assertEquals("Contract violated for " + o1 + ", " + o2 + ", " + o3, Math.signum(resA), Math.signum(resC), 0.0); } } } |
### Question:
RecordSectionResource { @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_FILE) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Download ris as file") public String getRISAsFile() throws PresentationException, IndexUnreachableException, DAOException, ContentLibException { StructElement se = getStructElement(pi, divId); String fileName = se.getPi() + "_" + se.getLogid() + ".ris"; servletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); String ris = new RisResourceBuilder(servletRequest, servletResponse).getRIS(se); return ris; } RecordSectionResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi,
@Parameter(description = "Logical div ID of METS section") @PathParam("divId") String divId); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_FILE) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Download ris as file") String getRISAsFile(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_TEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Get ris as text") String getRISAsText(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RANGE) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = {"records", "iiif"}, summary = "Get IIIF range for section") @IIIFPresentationBinding IPresentationModelElement getRange(); }### Answer:
@Test public void testGetRISAsFile() { try(Response response = target(urls.path(RECORDS_SECTIONS, RECORDS_SECTIONS_RIS_FILE).params(PI, DIVID).build()) .request() .get()) { assertEquals("Should return status 200", 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); String entity = response.readEntity(String.class); assertTrue(entity.contains("TY - FIGURE")); assertTrue(entity.contains("TI - Wappen 1")); String fileName = PI + "_LOG_0004.ris"; assertEquals( "attachment; filename=\"" + fileName + "\"", response.getHeaderString("Content-Disposition")); } } |
### Question:
RecordSectionResource { @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_TEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Get ris as text") public String getRISAsText() throws PresentationException, IndexUnreachableException, ContentNotFoundException, DAOException { StructElement se = getStructElement(pi, divId); return new RisResourceBuilder(servletRequest, servletResponse).getRIS(se); } RecordSectionResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi,
@Parameter(description = "Logical div ID of METS section") @PathParam("divId") String divId); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_FILE) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Download ris as file") String getRISAsFile(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_TEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Get ris as text") String getRISAsText(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RANGE) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = {"records", "iiif"}, summary = "Get IIIF range for section") @IIIFPresentationBinding IPresentationModelElement getRange(); }### Answer:
@Test public void testGetRISAsText() { try(Response response = target(urls.path(RECORDS_SECTIONS, RECORDS_SECTIONS_RIS_TEXT).params(PI, DIVID).build()) .request() .accept(MediaType.TEXT_PLAIN) .get()) { assertEquals("Should return status 200", 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); String entity = response.readEntity(String.class); assertTrue(entity.contains("TY - FIGURE")); assertTrue(entity.contains("TI - Wappen 1")); } } |
### Question:
RecordSectionResource { @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RANGE) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = {"records", "iiif"}, summary = "Get IIIF range for section") @IIIFPresentationBinding public IPresentationModelElement getRange() throws ContentNotFoundException, PresentationException, IndexUnreachableException, URISyntaxException, ViewerConfigurationException, DAOException { IIIFPresentationResourceBuilder builder = new IIIFPresentationResourceBuilder(urls); return builder.getRange(pi, divId); } RecordSectionResource(
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi,
@Parameter(description = "Logical div ID of METS section") @PathParam("divId") String divId); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_FILE) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Download ris as file") String getRISAsFile(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RIS_TEXT) @Produces({ MediaType.TEXT_PLAIN }) @Operation(tags = { "records"}, summary = "Get ris as text") String getRISAsText(); @GET @javax.ws.rs.Path(RECORDS_SECTIONS_RANGE) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = {"records", "iiif"}, summary = "Get IIIF range for section") @IIIFPresentationBinding IPresentationModelElement getRange(); }### Answer:
@Test public void testGetRange() throws JsonMappingException, JsonProcessingException { String url = urls.path(RECORDS_SECTIONS, RECORDS_SECTIONS_RANGE).params(PI, DIVID).build(); try(Response response = target(url) .request() .accept(MediaType.APPLICATION_JSON) .get()) { assertEquals("Should return status 200", 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); String entity = response.readEntity(String.class); assertNotNull(entity); Range range = mapper.readValue(entity, Range.class); assertEquals(URI.create(url), range.getId()); } } |
### Question:
ViewerRecordPDFResource extends MetsPdfResource { @Override @GET @Path(ApiUrls.RECORDS_PDF) @Produces("application/pdf") @ContentServerPdfBinding @Operation(tags = { "records" }, summary = "Get PDF for entire record") public StreamingOutput getPdf() throws ContentLibException { logger.trace("getPdf: {}", filename); response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); return super.getPdf(); } ViewerRecordPDFResource(
@Context ContainerRequestContext context, @Context HttpServletRequest request, @Context HttpServletResponse response,
@Context AbstractApiUrlManager urls,
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi); @Override @GET @Path(ApiUrls.RECORDS_PDF) @Produces("application/pdf") @ContentServerPdfBinding @Operation(tags = { "records" }, summary = "Get PDF for entire record") StreamingOutput getPdf(); @Override @GET @Path(ApiUrls.RECORDS_PDF_INFO) @Produces({ MediaType.APPLICATION_JSON }) @ContentServerPdfInfoBinding @Operation(tags = { "records" }, summary = "Get information about PDF for entire record") PdfInformation getInfoAsJson(); }### Answer:
@Test public void testGetPdf() { String url = urls.path(RECORDS_RECORD, RECORDS_PDF).params(PI).build(); try (Response response = target(url) .request() .header("x-forwarded-for", "1.2.3.4") .accept("application/pdf") .get()) { assertEquals("Should return status 200", 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); byte[] entity = response.readEntity(byte[].class); String contentDisposition = response.getHeaderString("Content-Disposition"); assertEquals("attachment; filename=\"" + PI + ".pdf" + "\"", contentDisposition); assertTrue(entity.length >= 5 * 5 * 8 * 3); } } |
### Question:
ViewerSectionPDFResource extends MetsPdfResource { @GET @Path(ApiUrls.RECORDS_SECTIONS_PDF) @Produces("application/pdf") @ContentServerPdfBinding @Operation(tags = { "records"}, summary = "Get PDF for section of record") public StreamingOutput getPdf() throws ContentLibException { response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); return super.getPdf(divId); } ViewerSectionPDFResource(
@Context ContainerRequestContext context, @Context HttpServletRequest request, @Context HttpServletResponse response,
@Context AbstractApiUrlManager urls,
@Parameter(description = "Persistent identifier of the record") @PathParam("pi") String pi,
@Parameter(description = "Logical div ID of METS section") @PathParam("divId") String divId); @GET @Path(ApiUrls.RECORDS_SECTIONS_PDF) @Produces("application/pdf") @ContentServerPdfBinding @Operation(tags = { "records"}, summary = "Get PDF for section of record") StreamingOutput getPdf(); @GET @Path(ApiUrls.RECORDS_SECTIONS_PDF_INFO) @Produces({ MediaType.APPLICATION_JSON, MEDIA_TYPE_APPLICATION_JSONLD }) @ContentServerPdfInfoBinding @Override @Operation(tags = { "records"}, summary = "Get information about PDF for section of record") PdfInformation getInfoAsJson(); }### Answer:
@Test public void testGetPdf() { String url = urls.path(RECORDS_SECTIONS, RECORDS_SECTIONS_PDF).params(PI, LOGID).build(); try (Response response = target(url) .request() .header("x-forwarded-for", "1.2.3.4") .accept("application/pdf") .get()) { assertEquals(response.getStatusInfo().getReasonPhrase(), 200, response.getStatus()); assertNotNull("Should return user object as json", response.getEntity()); byte[] entity = response.readEntity(byte[].class); String contentDisposition = response.getHeaderString("Content-Disposition"); assertEquals("attachment; filename=\"" + PI + "_" + LOGID + ".pdf" + "\"", contentDisposition); assertTrue(entity.length >= 5 * 5 * 8 * 3); } } |
### Question:
CollectionsResource { @GET @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get all collections as IIIF presentation collection") @ApiResponse(responseCode="400", description="No collections available for field") public Collection getAllCollections( @Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping ) throws PresentationException, IndexUnreachableException, DAOException, ContentLibException, URISyntaxException, ViewerConfigurationException { IIIFPresentationResourceBuilder builder = new IIIFPresentationResourceBuilder(urls); Collection collection; if(StringUtils.isBlank(grouping)) { collection = builder.getCollections(solrField); } else { collection = builder.getCollectionsWithGrouping(solrField, grouping); } if(collection.getMembers() == null || collection.getMembers().isEmpty()) { throw new IllegalRequestException("No collections found for field " + solrField); } return collection; } CollectionsResource(
@Parameter(description="Name of the SOLR field the collection is based on. Typically 'DC'")@PathParam("field")String solrField
); @GET @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get all collections as IIIF presentation collection") @ApiResponse(responseCode="400", description="No collections available for field") Collection getAllCollections(
@Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping
); @GET @javax.ws.rs.Path(COLLECTIONS_COLLECTION) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get given collection as a IIIF presentation collection") @ApiResponse(responseCode="400", description="Invalid collection name or field") Collection getCollection(
@Parameter(description="Name of the collection. Must be a value of the SOLR field the collection is based on")@PathParam("collection")String collectionName,
@Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping
); @GET @javax.ws.rs.Path(COLLECTIONS_CONTENTASSIST) @Produces({ MediaType.APPLICATION_JSON }) @ApiResponse(responseCode="400", description="No collections available for field") // @Operation(tags = { "collections"}, summary = "Return a list of collections starting with the given input") List<String> contentAssist(
@Parameter(description="User input for which content assist is requested")@QueryParam("query")String input); }### Answer:
@Test public void testGetAllCollections() throws JsonMappingException, JsonProcessingException { String url = urls.path(COLLECTIONS).params(SOLR_FIELD).build(); try(Response response = target(url) .request() .accept(MediaType.APPLICATION_JSON) .get()) { String entity = response.readEntity(String.class); assertEquals("Should return status 200; answer; " + entity, 200, response.getStatus()); assertNotNull(entity); JSONObject collection = new JSONObject(entity); assertEquals(url, collection.getString("@id")); assertEquals(20, collection.getJSONArray("members").length()); } } |
### Question:
CollectionsResource { @GET @javax.ws.rs.Path(COLLECTIONS_COLLECTION) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get given collection as a IIIF presentation collection") @ApiResponse(responseCode="400", description="Invalid collection name or field") public Collection getCollection( @Parameter(description="Name of the collection. Must be a value of the SOLR field the collection is based on")@PathParam("collection")String collectionName, @Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping ) throws PresentationException, IndexUnreachableException, DAOException, ContentLibException, URISyntaxException, ViewerConfigurationException { IIIFPresentationResourceBuilder builder = new IIIFPresentationResourceBuilder(urls); collectionName = StringTools.decodeUrl(collectionName); Collection collection; if(StringUtils.isBlank(grouping)) { collection = builder.getCollection(solrField, collectionName); } else { collection = builder.getCollectionWithGrouping(solrField, collectionName, grouping); } if(collection.getMembers() == null || collection.getMembers().isEmpty()) { throw new IllegalRequestException("No valid collection: " + solrField + ":" + collectionName); } return collection; } CollectionsResource(
@Parameter(description="Name of the SOLR field the collection is based on. Typically 'DC'")@PathParam("field")String solrField
); @GET @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get all collections as IIIF presentation collection") @ApiResponse(responseCode="400", description="No collections available for field") Collection getAllCollections(
@Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping
); @GET @javax.ws.rs.Path(COLLECTIONS_COLLECTION) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags = { "iiif" }, summary = "Get given collection as a IIIF presentation collection") @ApiResponse(responseCode="400", description="Invalid collection name or field") Collection getCollection(
@Parameter(description="Name of the collection. Must be a value of the SOLR field the collection is based on")@PathParam("collection")String collectionName,
@Parameter(description ="Add values of this field to response to allow grouping of results")@QueryParam("grouping")String grouping
); @GET @javax.ws.rs.Path(COLLECTIONS_CONTENTASSIST) @Produces({ MediaType.APPLICATION_JSON }) @ApiResponse(responseCode="400", description="No collections available for field") // @Operation(tags = { "collections"}, summary = "Return a list of collections starting with the given input") List<String> contentAssist(
@Parameter(description="User input for which content assist is requested")@QueryParam("query")String input); }### Answer:
@Test public void testGetCollection() { String url = urls.path(COLLECTIONS, COLLECTIONS_COLLECTION).params(SOLR_FIELD, COLLECTION).build(); try(Response response = target(url) .request() .accept(MediaType.APPLICATION_JSON) .get()) { String entity = response.readEntity(String.class); assertEquals("Should return status 200; answer; " + entity, 200, response.getStatus()); assertNotNull(entity); JSONObject collection = new JSONObject(entity); assertEquals(url, collection.getString("@id")); assertEquals(4, collection.getJSONArray("members").length()); } } |
### Question:
TranslationResource { @GET @Path(ApiUrls.LOCALIZATION_TRANSLATIONS) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags= {"localization"}, summary = "Get translations for message keys", description = "Pass a list of message keys to get translations for all configured languages") @ApiResponse(responseCode = "200", description = "Return translations for given keys") @ApiResponse(responseCode = "400", description = "No keys passed") public TranslationList getTranslations( @QueryParam("keys") @Parameter(description = "A comma separated list of message keys") String keys) throws IllegalRequestException { logger.trace("getTranslations: {}", keys); Collection<String> keysCollection; if(StringUtils.isBlank(keys)) { throw new IllegalRequestException("Must provide query parameter 'keys'"); } else { keysCollection = Arrays.asList(keys.split("\\s*,\\s*")); } List<Translation> translations = new ArrayList<>(); for (String key : keysCollection) { translations.addAll(MessagesTranslation.getTranslations(key)); } return new TranslationList(translations); } @GET @Path(ApiUrls.LOCALIZATION_TRANSLATIONS) @Produces({ MediaType.APPLICATION_JSON }) @Operation(tags= {"localization"}, summary = "Get translations for message keys", description = "Pass a list of message keys to get translations for all configured languages") @ApiResponse(responseCode = "200", description = "Return translations for given keys") @ApiResponse(responseCode = "400", description = "No keys passed") TranslationList getTranslations(
@QueryParam("keys") @Parameter(description = "A comma separated list of message keys") String keys); }### Answer:
@Test public void testGetTranslations() throws JsonMappingException, JsonProcessingException { try(Response response = target(urls.path(LOCALIZATION, LOCALIZATION_TRANSLATIONS).build()) .queryParam("keys", "cancel,ok") .request() .accept(MediaType.APPLICATION_JSON) .get()) { assertEquals("Should return status 200", 200, response.getStatus()); String entity = response.readEntity(String.class); assertNotNull(entity); JSONObject translations = new JSONObject(entity); assertEquals("Cancel", translations.getJSONObject("cancel").getJSONArray("en").get(0)); assertEquals("ok", translations.getJSONObject("ok").getJSONArray("en").get(0)); } } |
### Question:
ApplicationResource { @GET @Produces(MediaType.APPLICATION_JSON) public ApiInfo getApiInfo() { ApiInfo info = new ApiInfo(); info.name = "Goobi viewer REST API"; info.version = "v1"; info.specification = urls.getApiUrl() + "/openapi.json"; return info; } @GET @Produces(MediaType.APPLICATION_JSON) ApiInfo getApiInfo(); }### Answer:
@Test public void testGetApiInfo() { try(Response response = target(urls.path().build()) .request() .accept(MediaType.APPLICATION_JSON) .get()) { ApiInfo info = response.readEntity(ApiInfo.class); assertNotNull(info); assertEquals("v1", info.version); } } |
### Question:
CampaignItemResource { @GET @Path("/{campaignId}/{pi}") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding public CampaignItem getItemForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi) throws URISyntaxException, DAOException, ContentNotFoundException { URI manifestURI = new ManifestBuilder(urls).getManifestURI(pi); Campaign campaign = DataManager.getInstance().getDao().getCampaign(campaignId); if (campaign != null) { CampaignItem item = new CampaignItem(); item.setSource(manifestURI); item.setCampaign(campaign); return item; } throw new ContentNotFoundException("No campaign found with id " + campaignId); } CampaignItemResource(); CampaignItemResource(AbstractApiUrlManager urls); @GET @Path("/{campaignId}/{pi}") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding CampaignItem getItemForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setItemForManifest(CampaignItem item, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @GET @Path("/{campaignId}/{pi}/annotations") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding List<WebAnnotation> getAnnotationsForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/annotations") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setAnnotationsForManifest(List<AnnotationPage> pages, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); }### Answer:
@Test public void testGetItemForManifest() throws ContentNotFoundException, URISyntaxException, DAOException { Campaign campaign = DataManager.getInstance().getDao().getCampaign(1l); CampaignItem item = resource.getItemForManifest(1l, "PPN1234"); Assert.assertNotNull(item); Assert.assertEquals(campaign, item.getCampaign()); URI manifestUrl = new ManifestBuilder(new ApiUrls()) .getManifestURI("PPN1234"); Assert.assertEquals(manifestUrl, item.getSource()); } |
### Question:
CampaignItemResource { @PUT @Path("/{campaignId}/{pi}/") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding public void setItemForManifest(CampaignItem item, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi) throws DAOException { CampaignRecordStatus status = item.getRecordStatus(); Campaign campaign = DataManager.getInstance().getDao().getCampaign(campaignId); User user = null; Long userId = User.getId(item.getCreatorURI()); if (userId != null) { user = DataManager.getInstance().getDao().getUser(userId); } if (status != null && campaign != null) { campaign.setRecordStatus(pi, status, Optional.ofNullable(user)); DataManager.getInstance().getDao().updateCampaign(campaign); if (status.equals(CampaignRecordStatus.FINISHED)) { IndexerTools.triggerReIndexRecord(pi); } } } CampaignItemResource(); CampaignItemResource(AbstractApiUrlManager urls); @GET @Path("/{campaignId}/{pi}") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding CampaignItem getItemForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setItemForManifest(CampaignItem item, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @GET @Path("/{campaignId}/{pi}/annotations") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding List<WebAnnotation> getAnnotationsForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/annotations") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setAnnotationsForManifest(List<AnnotationPage> pages, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); }### Answer:
@Test public void testSetItemForManifest() throws ContentNotFoundException, URISyntaxException, DAOException { String pi = "PPN1234"; CampaignItem item = resource.getItemForManifest(1l, pi); User user = DataManager.getInstance().getDao().getUser(1l); item.setCreatorURI(user.getIdAsURI()); item.setRecordStatus(CampaignRecordStatus.REVIEW); Assert.assertEquals(user.getIdAsURI(), item.getCreatorURI()); resource.setItemForManifest(item, 1l, pi); Campaign campaign = DataManager.getInstance().getDao().getCampaign(1l); Assert.assertEquals(CampaignRecordStatus.REVIEW, campaign.getRecordStatus(pi)); Assert.assertTrue(campaign.getStatistics().get(pi).getAnnotators().contains(user)); } |
### Question:
CampaignItemResource { @GET @Path("/{campaignId}/{pi}/annotations") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding public List<WebAnnotation> getAnnotationsForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi) throws URISyntaxException, DAOException { Campaign campaign = DataManager.getInstance().getDao().getCampaign(campaignId); List<PersistentAnnotation> annotations = DataManager.getInstance().getDao().getAnnotationsForCampaignAndWork(campaign, pi); List<WebAnnotation> webAnnotations = new ArrayList<>(); for (PersistentAnnotation anno : annotations) { WebAnnotation webAnno = annoBuilder.getAsWebAnnotation(anno); webAnnotations.add(webAnno); } return webAnnotations; } CampaignItemResource(); CampaignItemResource(AbstractApiUrlManager urls); @GET @Path("/{campaignId}/{pi}") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding CampaignItem getItemForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setItemForManifest(CampaignItem item, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @GET @Path("/{campaignId}/{pi}/annotations") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding List<WebAnnotation> getAnnotationsForManifest(@PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); @PUT @Path("/{campaignId}/{pi}/annotations") @Consumes({ MediaType.APPLICATION_JSON }) @CORSBinding void setAnnotationsForManifest(List<AnnotationPage> pages, @PathParam("campaignId") Long campaignId, @PathParam("pi") String pi); }### Answer:
@Test public void testGetAnnotationsForManifest() throws URISyntaxException, DAOException { String pi = "PI_1"; List<WebAnnotation> annotationList = resource.getAnnotationsForManifest(1l, pi); Assert.assertEquals(2, annotationList.size()); } |
### Question:
CMSContentResource { @GET @Path("/content/{pageId}/{language}/{contentId}") @Produces({ MediaType.TEXT_HTML }) public String getContentHtml(@PathParam("pageId") Long pageId, @PathParam("language") String language, @PathParam("contentId") String contentId) throws IOException, DAOException, ServletException { if (servletResponse != null) { servletResponse.setCharacterEncoding(StringTools.DEFAULT_ENCODING); } String output = createResponseInThread(TargetType.CONTENT, pageId, language, contentId, REQUEST_TIMEOUT); return wrap(output, false); } @GET @Path("/content/{pageId}/{language}/{contentId}") @Produces({ MediaType.TEXT_HTML }) String getContentHtml(@PathParam("pageId") Long pageId, @PathParam("language") String language, @PathParam("contentId") String contentId); @GET @Path("/page/{pageId}") @Produces({ MediaType.TEXT_HTML }) String getPageUrl(@PathParam("pageId") Long pageId); @GET @Path("/sidebar/{elementId}") @Produces({ MediaType.TEXT_PLAIN }) String getSidebarElementHtml(@PathParam("elementId") Long elementId); static String getPageUrl(CMSPage cmsPage); static String getContentUrl(CMSContentItem item); static String getSidebarElementUrl(CMSSidebarElement item); }### Answer:
@Test public void testGetContentHtml() throws IOException, DAOException, ServletException { String output = resource.getContentHtml(1l, "de", "C1"); String expectedOutput = "<b>Hello CMS</b>"; Assert.assertEquals(resource.wrap(expectedOutput, true), output); } |
### Question:
CMSContentResource { @GET @Path("/sidebar/{elementId}") @Produces({ MediaType.TEXT_PLAIN }) public String getSidebarElementHtml(@PathParam("elementId") Long elementId) throws IOException, DAOException, ServletException { String output = createResponseInThread(TargetType.SIDEBAR, elementId, null, null, REQUEST_TIMEOUT); return wrap(output, true); } @GET @Path("/content/{pageId}/{language}/{contentId}") @Produces({ MediaType.TEXT_HTML }) String getContentHtml(@PathParam("pageId") Long pageId, @PathParam("language") String language, @PathParam("contentId") String contentId); @GET @Path("/page/{pageId}") @Produces({ MediaType.TEXT_HTML }) String getPageUrl(@PathParam("pageId") Long pageId); @GET @Path("/sidebar/{elementId}") @Produces({ MediaType.TEXT_PLAIN }) String getSidebarElementHtml(@PathParam("elementId") Long elementId); static String getPageUrl(CMSPage cmsPage); static String getContentUrl(CMSContentItem item); static String getSidebarElementUrl(CMSSidebarElement item); }### Answer:
@Test public void testGetSidebarElementHtml() throws IOException, DAOException, ServletException { String output = resource.getSidebarElementHtml(1l); String expectedOutput = "<h1>Hello Sidebar</h1>"; Assert.assertEquals(resource.wrap(expectedOutput, true), output); } |
### Question:
CMSContentResource { public static String getContentUrl(CMSContentItem item) { if (item != null) { StringBuilder urlBuilder = new StringBuilder(BeanUtils.getServletPathWithHostAsUrlFromJsfContext()); urlBuilder.append("/rest/cms/"); urlBuilder.append(TargetType.CONTENT.name().toLowerCase()); urlBuilder.append("/"); urlBuilder.append(item.getOwnerPageLanguageVersion().getOwnerPage().getId()); urlBuilder.append("/"); urlBuilder.append(item.getOwnerPageLanguageVersion().getLanguage()); urlBuilder.append("/"); urlBuilder.append(item.getItemId()).append("/"); urlBuilder.append("?timestamp=").append(System.currentTimeMillis()); logger.debug("CMS rest api url = {}", urlBuilder.toString()); return urlBuilder.toString(); } return ""; } @GET @Path("/content/{pageId}/{language}/{contentId}") @Produces({ MediaType.TEXT_HTML }) String getContentHtml(@PathParam("pageId") Long pageId, @PathParam("language") String language, @PathParam("contentId") String contentId); @GET @Path("/page/{pageId}") @Produces({ MediaType.TEXT_HTML }) String getPageUrl(@PathParam("pageId") Long pageId); @GET @Path("/sidebar/{elementId}") @Produces({ MediaType.TEXT_PLAIN }) String getSidebarElementHtml(@PathParam("elementId") Long elementId); static String getPageUrl(CMSPage cmsPage); static String getContentUrl(CMSContentItem item); static String getSidebarElementUrl(CMSSidebarElement item); }### Answer:
@Test public void testGetContentUrl() throws DAOException, CmsElementNotFoundException { CMSPage page = DataManager.getInstance().getDao().getCMSPage(1l); CMSContentItem item = page.getContentItem("C1", "de"); String url = CMSContentResource.getContentUrl(item); url = url.substring(0, url.indexOf("?")); Assert.assertEquals("/rest/cms/content/1/de/C1/", url); } |
### Question:
CMSContentResource { public static String getSidebarElementUrl(CMSSidebarElement item) { if (item != null && item.hasHtml()) { StringBuilder urlBuilder = new StringBuilder(BeanUtils.getServletPathWithHostAsUrlFromJsfContext()); urlBuilder.append("/rest/cms/"); urlBuilder.append(TargetType.SIDEBAR.name().toLowerCase()); urlBuilder.append("/"); urlBuilder.append(item.getId()).append("/"); urlBuilder.append("?timestamp=").append(System.currentTimeMillis()); return urlBuilder.toString(); } return ""; } @GET @Path("/content/{pageId}/{language}/{contentId}") @Produces({ MediaType.TEXT_HTML }) String getContentHtml(@PathParam("pageId") Long pageId, @PathParam("language") String language, @PathParam("contentId") String contentId); @GET @Path("/page/{pageId}") @Produces({ MediaType.TEXT_HTML }) String getPageUrl(@PathParam("pageId") Long pageId); @GET @Path("/sidebar/{elementId}") @Produces({ MediaType.TEXT_PLAIN }) String getSidebarElementHtml(@PathParam("elementId") Long elementId); static String getPageUrl(CMSPage cmsPage); static String getContentUrl(CMSContentItem item); static String getSidebarElementUrl(CMSSidebarElement item); }### Answer:
@Test public void testGetSidebarElementUrl() throws DAOException { CMSSidebarElement element = DataManager.getInstance().getDao().getCMSSidebarElement(1); String url = CMSContentResource.getSidebarElementUrl(element); url = url.substring(0, url.indexOf("?")); Assert.assertEquals("/rest/cms/sidebar/1/", url); } |
### Question:
ManifestResource extends AbstractResource { @GET @Path("/{pi}/manifest") @Produces({ MediaType.APPLICATION_JSON }) public IPresentationModelElement getManifest(@PathParam("pi") String pi) throws PresentationException, IndexUnreachableException, URISyntaxException, ViewerConfigurationException, DAOException, ContentNotFoundException { return createManifest(pi, BuildMode.IIIF); } ManifestResource(); ManifestResource(HttpServletRequest request, HttpServletResponse response); @GET @Path("/{pi}") @Produces({ MediaType.APPLICATION_JSON }) Response geManifestAlt(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("pi") String pi); @GET @Path("/{pi}/manifest") @Produces({ MediaType.APPLICATION_JSON }) IPresentationModelElement getManifest(@PathParam("pi") String pi); @GET @Path("/{pi}/manifest/search") @Produces({ MediaType.APPLICATION_JSON }) SearchResult searchInManifest(@PathParam("pi") String pi, @QueryParam("q") String query, @QueryParam("motivation") String motivation,
@QueryParam("date") String date, @QueryParam("user") String user, @QueryParam("page") Integer page); @GET @Path("/{pi}/manifest/autocomplete") @Produces({ MediaType.APPLICATION_JSON }) AutoSuggestResult autoCompleteInManifest(@PathParam("pi") String pi, @QueryParam("q") String query,
@QueryParam("motivation") String motivation, @QueryParam("date") String date, @QueryParam("user") String user,
@QueryParam("page") Integer page); @GET @Path("/{pi}/manifest/simple") @Produces({ MediaType.APPLICATION_JSON }) IPresentationModelElement getManifestSimple(@PathParam("pi") String pi); @GET @Path("/{pi}/manifest/base") @Produces({ MediaType.APPLICATION_JSON }) IPresentationModelElement getManifestBase(@PathParam("pi") String pi); @GET @Path("/{pi}/sequence/basic") @Produces({ MediaType.APPLICATION_JSON }) Sequence getBasicSequence(@PathParam("pi") String pi); @GET @Path("/{pi}/{preferredView}/thumbnails") @Produces({ MediaType.APPLICATION_JSON }) List<Canvas> getThumbnailSequence(@PathParam("preferredView") String preferredView, @PathParam("pi") String pi); @GET @Path("/{pi}/range/{logId}") @Produces({ MediaType.APPLICATION_JSON }) Range getRange(@PathParam("pi") String pi, @PathParam("logId") String logId); @GET @Path("/{pi}/canvas/{physPageNo}") @Produces({ MediaType.APPLICATION_JSON }) Canvas getCanvas(@PathParam("pi") String pi, @PathParam("physPageNo") int physPageNo); @GET @Path("/{pi}/list/{physPageNo}/{type}") @Produces({ MediaType.APPLICATION_JSON }) AnnotationList getOtherContent(@PathParam("pi") String pi, @PathParam("physPageNo") int physPageNo, @PathParam("type") String typeName); @GET @Path("/{pi}/list/{type}") @Produces({ MediaType.APPLICATION_JSON }) AnnotationList getOtherContent(@PathParam("pi") String pi, @PathParam("type") String typeName); @GET @Path("/{pi}/layer/{type}") @Produces({ MediaType.APPLICATION_JSON }) Layer getLayer(@PathParam("pi") String pi, @PathParam("type") String typeName); ManifestBuilder getManifestBuilder(); SequenceBuilder getSequenceBuilder(); LayerBuilder getLayerBuilder(); }### Answer:
@Test public void testGetManifest() throws ViewerConfigurationException, ContentNotFoundException, PresentationException, IndexUnreachableException, URISyntaxException, DAOException { IPresentationModelElement manifest = resource.getManifest(PP_NUAG_FOTO_V4); Assert.assertTrue(manifest instanceof Manifest); } |
### Question:
SessionResource { @GET @Path("/info") @Produces({ MediaType.TEXT_PLAIN }) @CORSBinding public String getSessionInfo() { if (servletRequest == null) { return "Servlet request not found"; } StringBuilder sb = new StringBuilder(); Map<String, String> sessionMap = DataManager.getInstance().getSessionMap().get(servletRequest.getSession().getId()); if (sessionMap == null) { return "Session " + servletRequest.getSession().getId() + " not found"; } for (String key : sessionMap.keySet()) { sb.append(key).append(": ").append(sessionMap.get(key)).append('\n'); } return sb.toString(); } SessionResource(); protected SessionResource(HttpServletRequest request); @GET @Path("/info") @Produces({ MediaType.TEXT_PLAIN }) @CORSBinding String getSessionInfo(); }### Answer:
@Test public void getSessionInfo_shouldReturnSessionInfoCorrectly() throws Exception { Map<String, String> sessionMd = new HashMap<>(); sessionMd.put("foo", "bar"); DataManager.getInstance().getSessionMap().put(TEST_SESSION_ID, sessionMd); String ret = resource.getSessionInfo(); Assert.assertTrue(ret, resource.getSessionInfo().equals("foo: bar\n")); } |
### Question:
NormdataResource { static JSONObject addNormDataValuesToJSON(NormData normData, Locale locale) { JSONObject jsonObj = new JSONObject(); String translation = ViewerResourceBundle.getTranslation(normData.getKey(), locale); String translatedKey = StringUtils.isNotEmpty(translation) ? translation : normData.getKey(); for (NormDataValue value : normData.getValues()) { JSONArray valueList; try { valueList = (JSONArray) jsonObj.get(translatedKey); } catch (JSONException e) { valueList = new JSONArray(); jsonObj.put(translatedKey, valueList); } Map<String, String> valueMap = new HashMap<>(); if (value.getText() != null) { if (value.getText().startsWith("<div ")) { valueMap.put("html", value.getText()); } else { valueMap.put("text", value.getText()); } } if (value.getIdentifier() != null) { valueMap.put("identifier", value.getIdentifier()); } if (value.getUrl() != null && !StringTools.isImageUrl(value.getUrl())) { valueMap.put("url", value.getUrl()); } if (value.getImageFileName() != null) { valueMap.put("image", value.getImageFileName()); } if (value.getLabel() != null) { valueMap.put("label", value.getLabel()); } valueList.put(valueMap); if (valueMap.get("text") == null) { valueMap.put("text", valueMap.get("identifier")); } } return jsonObj; } NormdataResource(); protected NormdataResource(HttpServletRequest request); @GET @Path("/get/{url}/{template}/{lang}") @Produces({ MediaType.APPLICATION_JSON }) @CORSBinding String getNormData(@PathParam("url") String url, @PathParam("template") String template, @PathParam("lang") String lang); @GET @Path("/get/{url}/{lang}") @Produces({ MediaType.APPLICATION_JSON }) String getNormData(@PathParam("url") String url, @PathParam("lang") String lang); }### Answer:
@Test public void addNormDataValuesToJSON_shouldAddValuesCorrectly() throws Exception { NormData normData = new NormData(); normData.setKey("NORM_FOO"); normData.getValues().add(new NormDataValue("bar", null, null)); JSONObject jsonObj =NormdataResource.addNormDataValuesToJSON(normData, null); Assert.assertNotNull(jsonObj); Assert.assertTrue(jsonObj.has("NORM_FOO")); JSONArray jsonArray = (JSONArray) jsonObj.get("NORM_FOO"); Assert.assertEquals(1, jsonArray.length()); Assert.assertEquals("bar", ((JSONObject) jsonArray.get(0)).getString("text")); } |
### Question:
CMSPageTemplate implements Serializable { public static CMSPageTemplate loadFromXML(Path file) { if (file == null) { throw new IllegalArgumentException("file may not be null"); } Document doc; try { doc = XmlTools.readXmlFile(file); } catch (IOException | JDOMException e1) { logger.error(e1.toString(), e1); return null; } if (doc != null) { Element root = doc.getRootElement(); try { CMSPageTemplate template = new CMSPageTemplate(); template.setTemplateFileName(file.getFileName().toString()); template.setId(root.getAttributeValue("id")); template.setVersion(root.getAttributeValue("version")); template.setName(root.getChildText("name")); template.setDescription(root.getChildText("description")); template.setIconFileName(root.getChildText("icon")); template.setHtmlFileName(root.getChildText("html")); for (Element eleContentItem : root.getChild("content").getChildren("item")) { CMSContentItemType type = CMSContentItemType.getByName(eleContentItem.getAttributeValue("type")); CMSContentItemTemplate item = new CMSContentItemTemplate(type); item.setItemId(eleContentItem.getAttributeValue("id")); item.setItemLabel(eleContentItem.getAttributeValue("label")); item.setMandatory(Boolean.valueOf(eleContentItem.getAttributeValue("mandatory"))); item.setMode(ContentItemMode.get(eleContentItem.getAttributeValue("mode"))); item.setMediaFilter(eleContentItem.getAttributeValue("filter")); item.setInlineHelp(eleContentItem.getAttributeValue("inlinehelp")); item.setPreview(Boolean.parseBoolean(eleContentItem.getAttributeValue("preview"))); if (eleContentItem.getAttribute("order") != null) { try { int order = Integer.parseInt(eleContentItem.getAttributeValue("order")); item.setOrder(order); } catch (NumberFormatException e) { logger.error("Error parsing order attribute of cms template {}. Value is {}", file.getFileName(), eleContentItem.getAttributeValue("order")); } } template.getContentItems().add(item); } Collections.sort(template.getContentItems()); Element options = root.getChild("options"); if (options != null) { template.setDisplaySortingField(parseBoolean(options.getChildText("useSorterField"))); template.setAppliesToExpandedUrl(parseBoolean(options.getChildText("appliesToExpandedUrl"), true)); } template.validate(); return template; } catch (NullPointerException e) { logger.error("Could not parse CMS template file '{}', check document structure.", file.getFileName()); } } return null; } static CMSPageTemplate loadFromXML(Path file); void validate(); CMSPage createNewPage(List<Locale> locales); CMSPageLanguageVersion createNewLanguageVersion(CMSPage page, String language); String getId(); void setId(String id); String getName(); void setName(String name); String getVersion(); void setVersion(String version); String getDescription(); void setDescription(String description); String getHtmlFileName(); void setHtmlFileName(String htmlFileName); String getTemplateFileName(); void setTemplateFileName(String templateFileName); String getIconFileName(); void setIconFileName(String iconFileName); List<CMSContentItemTemplate> getContentItems(); CMSContentItemTemplate getContentItem(String itemId); void setContentItems(List<CMSContentItemTemplate> contentItems); boolean isDisplaySortingField(); void setDisplaySortingField(boolean displaySortingField); boolean isThemeTemplate(); void setThemeTemplate(boolean themeTemplate); CMSPageTemplateEnabled getEnabled(); void setEnabled(CMSPageTemplateEnabled enabled); void setAppliesToExpandedUrl(boolean appliesToExpandedUrl); boolean isAppliesToExpandedUrl(); static boolean parseBoolean(String text, boolean defaultValue); static boolean parseBoolean(String text); }### Answer:
@Test(expected = IllegalArgumentException.class) public void loadFromXML_shouldThrowIllegalArgumentExceptionIfFileIsNull() throws Exception { CMSPageTemplate.loadFromXML(null); } |
### Question:
SearchHitsNotificationResource { public List<SearchHit> getNewHits(Search search) throws PresentationException, IndexUnreachableException, DAOException, ViewerConfigurationException { Search tempSearch = new Search(search); SearchFacets facets = new SearchFacets(); facets.setCurrentFacetString(tempSearch.getFacetString()); tempSearch.execute(facets, null, 0, 0, null, DataManager.getInstance().getConfiguration().isAggregateHits()); if (tempSearch.getHitsCount() > tempSearch.getLastHitsCount()) { int newHitsCount = (int) (tempSearch.getHitsCount() - tempSearch.getLastHitsCount()); newHitsCount = Math.min(100, newHitsCount); tempSearch.setSortString('!' + SolrConstants.DATECREATED); tempSearch.setPage(1); tempSearch.setHitsCount(0); tempSearch.execute(facets, null, newHitsCount, 0, null, DataManager.getInstance().getConfiguration().isAggregateHits()); List<SearchHit> newHits = tempSearch.getHits(); search.setLastHitsCount(tempSearch.getHitsCount()); return newHits; } return new ArrayList<>(); } @GET @Path("/sendnotifications/") @Produces({ MediaType.TEXT_HTML }) @AuthenticationBinding String sendNewHitsNotifications(); List<SearchHit> getNewHits(Search search); static final String RESOURCE_PATH; }### Answer:
@Test public void testcheckSearchUpdate() throws PresentationException, IndexUnreachableException, DAOException, ViewerConfigurationException { SearchHitsNotificationResource resource = new SearchHitsNotificationResource(); Search search = new Search(); search.setQuery("ISWORK:*"); search.setLastHitsCount(200); search.setPage(1); List<SearchHit> newHits = resource.getNewHits(search); assertFalse(newHits.isEmpty()); assertEquals(newHits.size(), Math.min(search.getLastHitsCount() - 200, 100)); } |
### Question:
IdentifierResolver extends HttpServlet { static String constructUrl(SolrDocument targetDoc, boolean pageResolverUrl) { int order = 1; if (targetDoc.containsKey(SolrConstants.THUMBPAGENO)) { order = (int) targetDoc.getFieldValue(SolrConstants.THUMBPAGENO); } else if (targetDoc.containsKey(SolrConstants.ORDER)) { order = (int) targetDoc.getFieldValue(SolrConstants.ORDER); } return constructUrl(targetDoc, pageResolverUrl, order); } }### Answer:
@Test public void constructUrl_shouldConstructUrlCorrectly() throws Exception { String pi = PI_KLEIUNIV; QueryResponse qr = DataManager.getInstance().getSearchIndex().search(SolrConstants.PI + ":" + pi, 0, 1, null, null, null); Assert.assertEquals(1, qr.getResults().size()); Assert.assertEquals("/object/" + pi + "/1/LOG_0000/", IdentifierResolver.constructUrl(qr.getResults().get(0), false)); }
@Test public void constructUrl_shouldConstructAnchorUrlCorrectly() throws Exception { String pi = "306653648"; QueryResponse qr = DataManager.getInstance().getSearchIndex().search(SolrConstants.PI + ":" + pi, 0, 1, null, null, null); Assert.assertEquals(1, qr.getResults().size()); Assert.assertEquals("/toc/" + pi + "/1/LOG_0000/", IdentifierResolver.constructUrl(qr.getResults().get(0), false)); }
@Test public void constructUrl_shouldConstructGroupUrlCorrectly() throws Exception { String pi = "PPN_GROUP"; SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.DOCTYPE, DocType.GROUP.toString()); doc.setField(SolrConstants.PI_TOPSTRUCT, pi); Assert.assertEquals("/toc/" + pi + "/1/-/", IdentifierResolver.constructUrl(doc, false)); }
@Test public void constructUrl_shouldConstructPageUrlCorrectly() throws Exception { String urn = "urn\\:nbn\\:at\\:at-akw\\:g-86493"; String pi = "AC11442160"; QueryResponse qr = DataManager.getInstance().getSearchIndex().search(SolrConstants.IMAGEURN + ":" + urn, 0, 1, null, null, null); Assert.assertEquals(1, qr.getResults().size()); Assert.assertEquals("/object/" + pi + "/2/-/", IdentifierResolver.constructUrl(qr.getResults().get(0), true)); }
@Test public void constructUrl_shouldConstructPreferredViewUrlCorrectly() throws Exception { String pi = "123"; SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.DOCSTRCT, "Catalogue"); doc.setField(SolrConstants.PI_TOPSTRUCT, "123"); Assert.assertEquals("/toc/" + pi + "/1/-/", IdentifierResolver.constructUrl(doc, false)); }
@Test public void constructUrl_shouldConstructApplicationMimeTypeUrlCorrectly() throws Exception { String pi = "123"; SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.DOCSTRCT, "Monograph"); doc.setField(SolrConstants.PI_TOPSTRUCT, "123"); doc.setField(SolrConstants.MIMETYPE, "application"); Assert.assertEquals("/metadata/" + pi + "/1/-/", IdentifierResolver.constructUrl(doc, false)); } |
### Question:
IdentifierResolver extends HttpServlet { static void parseFieldValueParameters(Map<String, String[]> parameterMap, Map<Integer, String> moreFields, Map<Integer, String> moreValues) { if (parameterMap == null || parameterMap.isEmpty()) { return; } for (String key : parameterMap.keySet()) { if (parameterMap.get(key) == null || parameterMap.get(key).length == 0) { continue; } if (key.startsWith(CUSTOM_FIELD_PARAMETER) && key.length() > CUSTOM_FIELD_PARAMETER.length()) { String number = key.substring(CUSTOM_FIELD_PARAMETER.length()); moreFields.put(Integer.valueOf(number), parameterMap.get(key)[0]); } else if (key.startsWith("value") && key.length() > "value".length()) { String number = key.substring("value".length()); moreValues.put(Integer.valueOf(number), parameterMap.get(key)[0]); } } } }### Answer:
@Test public void parseFieldValueParameters_shouldParseFieldsAndValuesCorrectly() throws Exception { Map<Integer, String> moreFields = new HashMap<>(); Map<Integer, String> moreValues = new HashMap<>(); Map<String, String[]> parameterMap = new HashMap<>(6); parameterMap.put("field2", new String[] { "FIELD2" }); parameterMap.put("field3", new String[] { "FIELD3" }); parameterMap.put("value2", new String[] { "val2" }); parameterMap.put("value3", new String[] { "val3" }); IdentifierResolver.parseFieldValueParameters(parameterMap, moreFields, moreValues); Assert.assertEquals(2, moreFields.size()); Assert.assertEquals("FIELD2", moreFields.get(2)); Assert.assertEquals("FIELD3", moreFields.get(3)); Assert.assertEquals(2, moreValues.size()); Assert.assertEquals("val2", moreValues.get(2)); Assert.assertEquals("val3", moreValues.get(3)); } |
### Question:
JPAClassLoader extends ClassLoader { static Document scanPersistenceXML(URL masterFileUrl, List<URL> moduleUrls) throws IOException, JDOMException { logger.trace("scanPersistenceXML(): {}", masterFileUrl); Document docMerged = new Document(); Document docMaster = XmlTools.readXmlFile(masterFileUrl); Element eleMasterRoot = docMaster.getRootElement(); Map<String, Set<String>> masterExistingClasses = new HashMap<>(2); Map<String, Element> masterPuMap = new HashMap<>(2); for (Element elePU : eleMasterRoot.getChildren("persistence-unit", null)) { String puName = elePU.getAttributeValue("name"); masterPuMap.put(puName, elePU); for (Element eleClass : elePU.getChildren("class", null)) { Set<String> classNames = masterExistingClasses.get(puName); if (classNames == null) { classNames = new HashSet<>(); masterExistingClasses.put(puName, classNames); } classNames.add(eleClass.getText().trim()); } } for (URL url : moduleUrls) { logger.trace("Processing {}", url.toString()); Document docModule = XmlTools.readXmlFile(url); for (Element eleModulePU : docModule.getRootElement().getChildren("persistence-unit", null)) { String puName = eleModulePU.getAttributeValue("name"); if (masterPuMap.containsKey(puName)) { Element eleMasterPU = masterPuMap.get(puName); for (Element eleModuleClass : eleModulePU.getChildren("class", null)) { String className = eleModuleClass.getText().trim(); if (!masterExistingClasses.get(puName).contains(className)) { eleMasterPU.addContent(new Element("class").setText(className).setNamespace(eleModuleClass.getNamespace())); logger.debug("Added class '{}' to persistence unit '{}'.", className, puName); } } } else { logger.debug("Persistence unit {} not found in master persistence.xml", puName); } } } eleMasterRoot.detach(); docMerged.addContent(eleMasterRoot); return docMerged; } JPAClassLoader(final ClassLoader parent); @Override Enumeration<URL> getResources(final String name); static final String PERSISTENCE_XML; static final String PERSISTENCE_XML_MODULE; }### Answer:
@Test public void scanPersistenceXML_shouldMergePersistenceXmlFilesCorrectly() throws Exception { File masterFile = new File("src/main/resources/META-INF/persistence.xml"); Assert.assertTrue(masterFile.isFile()); URL masterUrl = new URL("file: File file = new File("src/test/resources/modules/persistence.xml"); Assert.assertTrue(file.isFile()); URL moduleUrl = new URL("file: Document doc = JPAClassLoader.scanPersistenceXML(masterUrl, Collections.singletonList(moduleUrl)); Assert.assertNotNull(doc); logger.trace(new XMLOutputter().outputString(doc)); Element eleRoot = doc.getRootElement(); Assert.assertNotNull(eleRoot); List<Element> eleListPU = eleRoot.getChildren(); Assert.assertEquals(2, eleListPU.size()); { Element elePU1 = eleListPU.get(0); Assert.assertEquals(42, elePU1.getChildren("class", null).size()); Set<String> classes = new HashSet<>(); for (Element eleClass : elePU1.getChildren("class", null)) { classes.add(eleClass.getText()); logger.trace(eleClass.getText()); } Assert.assertTrue(classes.contains("io.goobi.viewer.model.dummymodule.DummyClass1")); Assert.assertTrue(classes.contains("io.goobi.viewer.model.dummymodule.DummyClass2")); } { Element elePU2 = eleListPU.get(1); Set<String> classes = new HashSet<>(); for (Element eleClass : elePU2.getChildren("class", null)) { classes.add(eleClass.getText()); logger.trace(eleClass.getText()); } Assert.assertTrue(classes.contains("io.goobi.viewer.model.dummymodule.DummyClass3")); Assert.assertTrue(classes.contains("io.goobi.viewer.model.dummymodule.DummyClass4")); } } |
### Question:
ManifestBuilder extends AbstractBuilder { public IPresentationModelElement generateManifest(StructElement ele) throws URISyntaxException, PresentationException, IndexUnreachableException, ViewerConfigurationException, DAOException { final AbstractPresentationModelElement manifest; if (ele.isAnchor()) { manifest = new Collection(getManifestURI(ele.getPi()), ele.getPi()); manifest.addViewingHint(ViewingHint.multipart); } else { manifest = new Manifest(getManifestURI(ele.getPi())); SearchService search = new SearchService(getSearchServiceURI(manifest.getId())); search.setLabel(ViewerResourceBundle.getTranslations("label__iiif_api_search")); AutoSuggestService autoComplete = new AutoSuggestService(getAutoSuggestServiceURI(manifest.getId())); search.addService(autoComplete); manifest.addService(search); } populate(ele, manifest); return manifest; } ManifestBuilder(AbstractApiUrlManager apiUrlManager); IPresentationModelElement generateManifest(StructElement ele); void populate(StructElement ele, final AbstractPresentationModelElement manifest); void addVolumes(Collection anchor, List<StructElement> volumes); void addAnchor(Manifest manifest, String anchorPI); BuildMode getBuildMode(); ManifestBuilder setBuildMode(BuildMode buildMode); }### Answer:
@Test public void test() throws PresentationException, IndexUnreachableException, ViewerConfigurationException, DAOException, URISyntaxException, ContentNotFoundException, IOException { DataManager.getInstance().injectConfiguration(new Configuration("src/test/resources/config_viewer.test.xml")); ManifestBuilder builder = new ManifestBuilder(new ApiUrls("https: SequenceBuilder sequenceBuilder = new SequenceBuilder(new ApiUrls("https: StructureBuilder structureBuilder = new StructureBuilder(new ApiUrls("https: SolrDocumentList allDocs = DataManager.getInstance().getSearchIndex().search("PI:*"); for (SolrDocument solrDocument : allDocs) { String pi = SolrSearchIndex.getSingleFieldStringValue(solrDocument, "PI"); } List<StructElement> docs = builder.getDocumentWithChildren(PI); if (docs.isEmpty()) { throw new ContentNotFoundException("No document found for pi " + PI); } StructElement mainDoc = docs.get(0); IPresentationModelElement manifest = builder.generateManifest(mainDoc); ((Manifest) manifest).setContext(IIIFPresentationResponseFilter.CONTEXT); sequenceBuilder.addBaseSequence((Manifest) manifest, mainDoc, manifest.getId().toString()); String topLogId = mainDoc.getMetadataValue(SolrConstants.LOGID); if (StringUtils.isNotBlank(topLogId)) { List<Range> ranges = structureBuilder.generateStructure(docs, PI, false); ranges.forEach(range -> { ((Manifest) manifest).addStructure(range); }); } ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); ObjectWriter writer = mapper.writer().forType(Manifest.class); String json = writer.writeValueAsString(manifest); Assert.assertTrue(StringUtils.isNotBlank(json)); } |
### Question:
GeoMapMarker { public String toJSONString() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(this); } GeoMapMarker(String name); GeoMapMarker(); String getIcon(); void setIcon(String icon); String getMarkerColor(); void setMarkerColor(String markerColor); String getShape(); void setShape(String shape); String getExtraClasses(); void setExtraClasses(String extraClasses); String getPrefix(); void setPrefix(String prefix); String getIconColor(); void setIconColor(String iconColor); int getIconRotate(); void setIconRotate(int iconRotation); String getNumber(); void setNumber(String number); boolean isSvg(); void setSvg(boolean svg); String getName(); void setName(String name); boolean isShadow(); void setShadow(boolean shadow); String toJSONString(); static GeoMapMarker fromJSONString(String json); }### Answer:
@Test public void testToJSONString() throws JsonProcessingException { String s = testObject.toJSONString(); Assert.assertEquals(testString, s); } |
### Question:
AbstractBuilder { protected Map<String, List<String>> getEventFields() { List<String> eventStrings = DataManager.getInstance().getConfiguration().getIIIFEventFields(); Map<String, List<String>> events = new HashMap<>(); for (String string : eventStrings) { String event, field; int separatorIndex = string.indexOf("/"); if (separatorIndex > -1) { event = string.substring(0, separatorIndex); field = string.substring(separatorIndex + 1); } else { event = ""; field = string; } List<String> eventFields = events.get(event); if (eventFields == null) { eventFields = new ArrayList<>(); events.put(event, eventFields); } eventFields.add(field); } return events; } AbstractBuilder(AbstractApiUrlManager apiUrlManager); URI absolutize(URI uri); URI absolutize(String uri); String getMetsResolverUrl(StructElement ele); String getLidoResolverUrl(StructElement ele); String getViewUrl(PhysicalElement ele, PageType pageType); static Optional<IMetadataValue> getLabelIfExists(SolrDocument solrDocument); void addMetadata(AbstractPresentationModelElement manifest, StructElement ele); List<StructElement> getDocumentWithChildren(String pi); StructElement getDocument(String pi); Map<Integer, List<OpenAnnotation>> getCrowdsourcingAnnotations(String pi, boolean urlOnlyTarget); IAnnotation getCrowdsourcingAnnotation(String id); OpenAnnotation createUGCOpenAnnotation(SolrDocument doc, boolean urlOnlyTarget); OpenAnnotation createUGCOpenAnnotation(String pi, SolrDocument doc, boolean urlOnlyTarget); void addCrowdourcingAnnotations(List<Canvas> canvases, Map<Integer, List<OpenAnnotation>> crowdsourcingAnnotations,
Map<AnnotationType, List<AnnotationList>> annotationMap); List<String> getSolrFieldList(); URI getCollectionURI(String collectionField, String baseCollectionName); URI getManifestURI(String pi); URI getManifestURI(String pi, BuildMode mode); URI getRangeURI(String pi, String logId); URI getSequenceURI(String pi, String label); URI getCanvasURI(String pi, int pageNo); Integer getPageOrderFromCanvasURI(URI uri); String getPIFromCanvasURI(URI uri); URI getAnnotationListURI(String pi, int pageNo, AnnotationType type); URI getAnnotationListURI(String pi, AnnotationType type); URI getCommentAnnotationURI(long id); URI getLayerURI(String pi, AnnotationType type); URI getImageAnnotationURI(String pi, int order); URI getAnnotationURI(String pi, int order, AnnotationType type, int annoNum); URI getAnnotationURI(String id); URI getSearchServiceURI(URI target); URI getSearchServiceURI(String pi); URI getAutoSuggestServiceURI(URI target); URI getAutoCompleteServiceURI(String pi); URI getSearchURI(String pi, String query, List<String> motivation); URI getAutoSuggestURI(String pi, String query, List<String> motivation); static final String[] REQUIRED_SOLR_FIELDS; static final String[] UGC_SOLR_FIELDS; }### Answer:
@Test public void testGetEventFields() { Map<String, List<String>> events = builder.getEventFields(); Assert.assertNotNull(events); Assert.assertEquals(3, events.size()); Assert.assertEquals(2, events.get("").size()); Assert.assertEquals(2, events.get("Provenienz").size()); Assert.assertEquals(1, events.get("Expression Creation").size()); Assert.assertEquals("MD_EVENTARTIST", events.get("Expression Creation").iterator().next()); } |
### Question:
SearchResultConverter { public SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment) { SearchHit hit = new SearchHit(); String text = comment.getDisplayText(); Matcher m = Pattern.compile(AbstractSearchParser.getSingleWordRegex(queryRegex)).matcher(text); while (m.find()) { String match = m.group(1); int indexStart = m.start(1); int indexEnd = m.end(1); String before = AbstractSearchParser.getPrecedingText(text, indexStart, Integer.MAX_VALUE); String after = AbstractSearchParser.getSucceedingText(text, indexEnd, Integer.MAX_VALUE); if (!StringUtils.isAllBlank(before, after)) { TextQuoteSelector textSelector = new TextQuoteSelector(); textSelector.setFragment(match); if (StringUtils.isNotBlank(before)) { textSelector.setPrefix(before); } if (StringUtils.isNotBlank(after)) { textSelector.setSuffix(after); } hit.addSelector(textSelector); } hit.setMatch(match); IAnnotation anno = createAnnotation(pi, comment); hit.addAnnotation(anno); } return hit; } SearchResultConverter(AbstractApiUrlManager urls, String pi, Integer pageNo); void setPi(String pi); String getPi(); void setPageNo(Integer pageNo); Integer getPageNo(); AbstractBuilder getPresentationBuilder(); SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment); SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc); SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc); AnnotationResultList getAnnotationsFromAlto(Path path, String query); AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount,
int firstIndex, int numHits); SearchTermList getSearchTerms(String regex, SolrDocument doc, List<String> fieldsToSearch, List<String> searchMotivation); SearchTermList getSearchTerms(String regex, String value, List<String> searchMotivation); SearchHit convertAltoToHit(List<Word> altoElements); SearchHit createAltoHit(List<Line> lines, Range<Integer> position, List<Line> containingLines); SearchHit createFulltextHit(String queryRegex, String text, String pi, Integer pageNo); }### Answer:
@Test public void testConvertCommentToHit() { Comment comment = new Comment(pi, pageNo, null, text, null); comment.setId(1l); String query = "in"; String queryRegex = AbstractSearchParser.getQueryRegex(query); SearchHit hit = converter.convertCommentToHit(queryRegex, pi, comment); String url = urls.path(ANNOTATIONS, ANNOTATIONS_COMMENT).params(comment.getId()).query("format", "oa").toString(); Assert.assertNotNull(hit); Assert.assertEquals(url, hit.getAnnotations().get(0).getId().toString()); Assert.assertEquals("in", hit.getMatch()); TextQuoteSelector selector1 = (TextQuoteSelector) hit.getSelectors().get(0); TextQuoteSelector selector2 = (TextQuoteSelector) hit.getSelectors().get(1); Assert.assertEquals("A bird ", selector1.getPrefix()); Assert.assertEquals(" the hand is worth\ntwo in the bush.", selector1.getSuffix()); Assert.assertEquals("A bird in the hand is worth\ntwo ", selector2.getPrefix()); Assert.assertEquals(" the bush.", selector2.getSuffix()); } |
### Question:
SearchResultConverter { public SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc) { SearchHit hit = new SearchHit(); String mdText = SolrSearchIndex.getMetadataValues(ugc, SolrConstants.UGCTERMS).stream().collect(Collectors.joining("; ")); String type = SolrSearchIndex.getSingleFieldStringValue(ugc, SolrConstants.UGCTYPE); Matcher m = Pattern.compile(AbstractSearchParser.getSingleWordRegex(queryRegex)).matcher(mdText); while (m.find()) { String match = m.group(1); int indexStart = m.start(1); int indexEnd = m.end(1); if (!match.equals(type)) { String before = AbstractSearchParser.getPrecedingText(mdText, indexStart, Integer.MAX_VALUE); before = before.replace(type, ""); String after = AbstractSearchParser.getSucceedingText(mdText, indexEnd, Integer.MAX_VALUE); after = after.replace(type, ""); if (!StringUtils.isAllBlank(before, after)) { TextQuoteSelector textSelector = new TextQuoteSelector(); textSelector.setFragment(match); if (StringUtils.isNotBlank(before)) { textSelector.setPrefix(before); } if (StringUtils.isNotBlank(after)) { textSelector.setSuffix(after); } hit.addSelector(textSelector); } } hit.setMatch(match); OpenAnnotation anno = getPresentationBuilder().createUGCOpenAnnotation(ugc, true); hit.addAnnotation(anno); } return hit; } SearchResultConverter(AbstractApiUrlManager urls, String pi, Integer pageNo); void setPi(String pi); String getPi(); void setPageNo(Integer pageNo); Integer getPageNo(); AbstractBuilder getPresentationBuilder(); SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment); SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc); SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc); AnnotationResultList getAnnotationsFromAlto(Path path, String query); AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount,
int firstIndex, int numHits); SearchTermList getSearchTerms(String regex, SolrDocument doc, List<String> fieldsToSearch, List<String> searchMotivation); SearchTermList getSearchTerms(String regex, String value, List<String> searchMotivation); SearchHit convertAltoToHit(List<Word> altoElements); SearchHit createAltoHit(List<Line> lines, Range<Integer> position, List<Line> containingLines); SearchHit createFulltextHit(String queryRegex, String text, String pi, Integer pageNo); }### Answer:
@Test public void testConvertUGCToHit() { SolrDocument ugc = new SolrDocument(); ugc.setField(SolrConstants.UGCTERMS, text); ugc.setField(SolrConstants.UGCTYPE, "ADDRESS"); ugc.setField(SolrConstants.PI_TOPSTRUCT, pi); ugc.setField(SolrConstants.ORDER, pageNo); ugc.setField(SolrConstants.IDDOC, 123456789); String query = "in"; String queryRegex = AbstractSearchParser.getQueryRegex(query); SearchHit hit = converter.convertUGCToHit(queryRegex, ugc); String url = urls.path(ANNOTATIONS, ANNOTATIONS_UGC).params(123456789).build(); Assert.assertNotNull(hit); Assert.assertEquals(url, hit.getAnnotations().get(0).getId().toString()); Assert.assertEquals("in", hit.getMatch()); TextQuoteSelector selector1 = (TextQuoteSelector) hit.getSelectors().get(0); TextQuoteSelector selector2 = (TextQuoteSelector) hit.getSelectors().get(1); Assert.assertEquals("A bird ", selector1.getPrefix()); Assert.assertEquals(" the hand is worth\ntwo in the bush.", selector1.getSuffix()); Assert.assertEquals("A bird in the hand is worth\ntwo ", selector2.getPrefix()); Assert.assertEquals(" the bush.", selector2.getSuffix()); } |
### Question:
SearchResultConverter { public SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc) { SearchHit hit = new SearchHit(); String mdText = SolrSearchIndex.getMetadataValues(doc, fieldName).stream().collect(Collectors.joining("; ")); Matcher m = Pattern.compile(AbstractSearchParser.getSingleWordRegex(queryRegex)).matcher(mdText); while (m.find()) { String match = m.group(1); int indexStart = m.start(1); int indexEnd = m.end(1); String before = AbstractSearchParser.getPrecedingText(mdText, indexStart, Integer.MAX_VALUE); String after = AbstractSearchParser.getSucceedingText(mdText, indexEnd, Integer.MAX_VALUE); if (!StringUtils.isAllBlank(before, after)) { TextQuoteSelector textSelector = new TextQuoteSelector(); textSelector.setFragment(match); if (StringUtils.isNotBlank(before)) { textSelector.setPrefix(before); } if (StringUtils.isNotBlank(after)) { textSelector.setSuffix(after); } hit.addSelector(textSelector); } hit.setMatch(match); } OpenAnnotation anno = createAnnotation(fieldName, doc); hit.addAnnotation(anno); return hit; } SearchResultConverter(AbstractApiUrlManager urls, String pi, Integer pageNo); void setPi(String pi); String getPi(); void setPageNo(Integer pageNo); Integer getPageNo(); AbstractBuilder getPresentationBuilder(); SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment); SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc); SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc); AnnotationResultList getAnnotationsFromAlto(Path path, String query); AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount,
int firstIndex, int numHits); SearchTermList getSearchTerms(String regex, SolrDocument doc, List<String> fieldsToSearch, List<String> searchMotivation); SearchTermList getSearchTerms(String regex, String value, List<String> searchMotivation); SearchHit convertAltoToHit(List<Word> altoElements); SearchHit createAltoHit(List<Line> lines, Range<Integer> position, List<Line> containingLines); SearchHit createFulltextHit(String queryRegex, String text, String pi, Integer pageNo); }### Answer:
@Test public void testConvertMetadataToHit() { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.TITLE, text); doc.setField(SolrConstants.PI_TOPSTRUCT, pi); doc.setField(SolrConstants.LOGID, logId); doc.setField(SolrConstants.PI, pi); doc.setField(SolrConstants.THUMBPAGENO, pageNo); doc.setField(SolrConstants.IDDOC, 123456789); String query = "in"; String queryRegex = AbstractSearchParser.getQueryRegex(query); SearchHit hit = converter.convertMetadataToHit(queryRegex, SolrConstants.TITLE, doc); String annoUrl = urls.path(ApiUrls.ANNOTATIONS, ApiUrls.ANNOTATIONS_METADATA).params(pi, logId, "MD_TITLE").query("format", "oa").build(); Assert.assertNotNull(hit); Assert.assertEquals(annoUrl, hit.getAnnotations().get(0).getId().toString()); Assert.assertEquals("in", hit.getMatch()); TextQuoteSelector selector1 = (TextQuoteSelector) hit.getSelectors().get(0); TextQuoteSelector selector2 = (TextQuoteSelector) hit.getSelectors().get(1); Assert.assertEquals("A bird ", selector1.getPrefix()); Assert.assertEquals(" the hand is worth\ntwo in the bush.", selector1.getSuffix()); Assert.assertEquals("A bird in the hand is worth\ntwo ", selector2.getPrefix()); Assert.assertEquals(" the bush.", selector2.getSuffix()); } |
### Question:
SearchResultConverter { public AnnotationResultList getAnnotationsFromAlto(Path path, String query) throws IOException, JDOMException { AnnotationResultList results = new AnnotationResultList(); AltoSearchParser parser = new AltoSearchParser(); AltoDocument doc = AltoDocument.getDocumentFromFile(path.toFile()); List<Word> words = parser.getWords(doc); if (!words.isEmpty()) { List<List<Word>> matches = parser.findWordMatches(words, query); for (List<Word> wordsHit : matches) { SearchHit hit = convertAltoToHit(wordsHit); results.add(hit); } } else { List<Line> lines = parser.getLines(doc); if (!lines.isEmpty()) { Map<Range<Integer>, List<Line>> hits = parser.findLineMatches(lines, query); for (Range<Integer> position : hits.keySet()) { List<Line> containingLines = hits.get(position); SearchHit hit = createAltoHit(lines, position, containingLines); results.add(hit); } } } return results; } SearchResultConverter(AbstractApiUrlManager urls, String pi, Integer pageNo); void setPi(String pi); String getPi(); void setPageNo(Integer pageNo); Integer getPageNo(); AbstractBuilder getPresentationBuilder(); SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment); SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc); SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc); AnnotationResultList getAnnotationsFromAlto(Path path, String query); AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount,
int firstIndex, int numHits); SearchTermList getSearchTerms(String regex, SolrDocument doc, List<String> fieldsToSearch, List<String> searchMotivation); SearchTermList getSearchTerms(String regex, String value, List<String> searchMotivation); SearchHit convertAltoToHit(List<Word> altoElements); SearchHit createAltoHit(List<Line> lines, Range<Integer> position, List<Line> containingLines); SearchHit createFulltextHit(String queryRegex, String text, String pi, Integer pageNo); }### Answer:
@Test public void testGetAnnotationsFromAlto() throws IOException, JDOMException { String query = "Hollywood"; String queryRegex = AbstractSearchParser.getQueryRegex(query); Assert.assertNotNull("Converter is null", converter); Assert.assertNotNull("Alto file is null", altoFile); Assert.assertTrue("Query regex is Blank", StringUtils.isNotBlank(queryRegex)); AnnotationResultList results = converter.getAnnotationsFromAlto(altoFile, queryRegex); Assert.assertEquals(9, results.hits.size()); SearchHit hit1 = results.hits.get(0); Assert.assertEquals("Hollywood!", hit1.getMatch()); String url = urls.path(ApiUrls.ANNOTATIONS, ApiUrls.ANNOTATIONS_ALTO).params(pi, pageNo, "Word_14").query("format", "oa").build(); Assert.assertEquals(url, hit1.getAnnotations().get(0).getId().toString()); } |
### Question:
SearchResultConverter { public AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount, int firstIndex, int numHits) { AnnotationResultList results = new AnnotationResultList(); long firstPageHitIndex = previousHitCount; long lastPageHitIndex = firstPageHitIndex; if (firstIndex <= lastPageHitIndex && firstIndex + numHits - 1 >= firstPageHitIndex) { results.add(createFulltextHit(query, text, pi, pageNo)); } return results; } SearchResultConverter(AbstractApiUrlManager urls, String pi, Integer pageNo); void setPi(String pi); String getPi(); void setPageNo(Integer pageNo); Integer getPageNo(); AbstractBuilder getPresentationBuilder(); SearchHit convertCommentToHit(String queryRegex, String pi, Comment comment); SearchHit convertUGCToHit(String queryRegex, SolrDocument ugc); SearchHit convertMetadataToHit(String queryRegex, String fieldName, SolrDocument doc); AnnotationResultList getAnnotationsFromAlto(Path path, String query); AnnotationResultList getAnnotationsFromFulltext(String text, String pi, Integer pageNo, String query, long previousHitCount,
int firstIndex, int numHits); SearchTermList getSearchTerms(String regex, SolrDocument doc, List<String> fieldsToSearch, List<String> searchMotivation); SearchTermList getSearchTerms(String regex, String value, List<String> searchMotivation); SearchHit convertAltoToHit(List<Word> altoElements); SearchHit createAltoHit(List<Line> lines, Range<Integer> position, List<Line> containingLines); SearchHit createFulltextHit(String queryRegex, String text, String pi, Integer pageNo); }### Answer:
@Test public void testGetAnnotationsFromFulltext() { String query = "in"; String queryRegex = AbstractSearchParser.getQueryRegex(query); AnnotationResultList results = converter.getAnnotationsFromFulltext(text, pi, pageNo, queryRegex, 0, 0, 1000); Assert.assertEquals(1, results.hits.size()); Assert.assertEquals(2, results.hits.get(0).getSelectors().size()); } |
### Question:
AltoSearchParser extends AbstractSearchParser { public List<List<Word>> findWordMatches(List<Word> words, String regex) { ListIterator<Word> iterator = words.listIterator(); List<List<Word>> results = new ArrayList<>(); while (iterator.hasNext()) { Word word = iterator.next(); if (Pattern.matches(regex, word.getSubsContent())) { List<Word> phrase = new ArrayList<>(); phrase.add(word); while (iterator.hasNext()) { Word nextWord = iterator.next(); if (Pattern.matches(regex, nextWord.getSubsContent())) { phrase.add(nextWord); } else { break; } } results.add(phrase); } } return results; } List<List<Word>> findWordMatches(List<Word> words, String regex); Map<Range<Integer>, List<Line>> findLineMatches(List<Line> lines, String regex); String getText(List<Line> lines); List<Line> getLines(AltoDocument doc); List<Word> getWords(AltoDocument doc); List<Line> getContainingLines(List<Line> allLines, int indexStart, int indexEnd); int getLineStartIndex(List<Line> allLines, Line line); int getLineEndIndex(List<Line> allLines, Line line); String getPrecedingText(Word w, int maxLength); String getSucceedingText(Word w, int maxLength); }### Answer:
@Test public void testFindWordMatches() { String query = "diese* schönste*"; String regex = parser.getQueryRegex(query); List<Word> words = doc.getFirstPage().getAllWordsAsList().stream().filter(l -> l instanceof Word).map(l -> (Word) l).collect(Collectors.toList()); Assert.assertFalse("No words found in " + altoFile, words == null || words.isEmpty()); Assert.assertNotNull("AltoSearchParser is not initialized", parser); List<List<Word>> hits = parser.findWordMatches(words, regex); Assert.assertEquals(6, hits.size()); Assert.assertEquals(1, hits.get(0).size()); Assert.assertEquals(2, hits.get(1).size()); } |
### Question:
AltoSearchParser extends AbstractSearchParser { public Map<Range<Integer>, List<Line>> findLineMatches(List<Line> lines, String regex) { String text = getText(lines); Map<Range<Integer>, List<Line>> map = new LinkedHashMap<>(); String singleWordRegex = getSingleWordRegex(regex); Matcher matcher = Pattern.compile(singleWordRegex).matcher(text); while (matcher.find()) { int indexStart = matcher.start(1); int indexEnd = matcher.end(1); List<Line> containingLines = getContainingLines(lines, indexStart, indexEnd); Range<Integer> range = Range.between(indexStart, indexEnd); map.put(range, containingLines); } return map; } List<List<Word>> findWordMatches(List<Word> words, String regex); Map<Range<Integer>, List<Line>> findLineMatches(List<Line> lines, String regex); String getText(List<Line> lines); List<Line> getLines(AltoDocument doc); List<Word> getWords(AltoDocument doc); List<Line> getContainingLines(List<Line> allLines, int indexStart, int indexEnd); int getLineStartIndex(List<Line> allLines, Line line); int getLineEndIndex(List<Line> allLines, Line line); String getPrecedingText(Word w, int maxLength); String getSucceedingText(Word w, int maxLength); }### Answer:
@Test public void testFindLineMatches() { String query = "diese* schönste*"; String regex = parser.getQueryRegex(query); List<Line> lines = doc.getFirstPage().getAllLinesAsList().stream().filter(l -> l instanceof Line).map(l -> (Line) l).collect(Collectors.toList()); Map<Range<Integer>, List<Line>> hits = parser.findLineMatches(lines, regex); String text = parser.getText(lines); for (Range<Integer> position : hits.keySet()) { List<Line> containingLines = hits.get(position); String match = text.substring(position.getMinimum(), position.getMaximum() + 1); } Assert.assertEquals(6, hits.size()); } |
### Question:
StructElement extends StructElementStub implements Comparable<StructElementStub>, Serializable { public StructElement getParent() throws IndexUnreachableException { StructElement parent = null; try { String parentIddoc = getMetadataValue(SolrConstants.IDDOC_PARENT); if (parentIddoc != null) { parent = new StructElement(Long.valueOf(parentIddoc), null); } } catch (NumberFormatException e) { logger.error("Malformed number with get the parent element for Lucene IDDOC: {}", luceneId); } return parent; } StructElement(); StructElement(long luceneId); StructElement(long luceneId, SolrDocument doc); StructElement(long luceneId, SolrDocument doc, SolrDocument docToMerge); boolean isHasParentOrChildren(); boolean isHasParent(); StructElement getParent(); boolean isHasChildren(); StructElement getTopStruct(); boolean isGroupMember(); boolean isGroup(); String getGroupLabel(String groupIdentifier, String altValue); boolean isExists(); boolean isDeleted(); @Override String getPi(); @Override int getImageNumber(); String getImageUrl(int width, int height); List<EventElement> generateEventElements(Locale locale); boolean isAnchorChild(); String getCollection(); List<String> getCollections(); boolean isFulltextAvailable(); void setFulltextAvailable(boolean fulltextAvailable); boolean isAltoAvailable(); boolean isNerAvailable(); boolean isAccessPermissionDownloadMetadata(); boolean isAccessPermissionGenerateIiifManifest(); @Deprecated String getTitle(); StructElementStub createStub(); Map<String, String> getAncestors(); Map<String, String> getGroupMemberships(); String getDisplayLabel(); IMetadataValue getMultiLanguageDisplayLabel(); String getGroupIdField(); String getFirstVolumeFieldValue(String field); StructElement getFirstVolume(List<String> fields); String getFirstPageFieldValue(String field); boolean mayShowThumbnail(); List<ShapeMetadata> getShapeMetadata(); boolean hasShapeMetadata(); void setShapeMetadata(List<ShapeMetadata> shapeMetadata); boolean isRtl(); void setRtl(boolean rtl); }### Answer:
@Test public void getParent_shouldReturnParentCorrectly() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getIddocByLogid(PI_KLEIUNIV, "LOG_0002"); Assert.assertNotEquals(-1, iddoc); StructElement element = new StructElement(iddoc); StructElement parent = element.getParent(); Assert.assertNotNull(parent); Assert.assertEquals(iddocKleiuniv, parent.getLuceneId()); } |
### Question:
StructElement extends StructElementStub implements Comparable<StructElementStub>, Serializable { public boolean isAnchorChild() throws IndexUnreachableException { if (isWork() && isHasParent()) { return true; } return false; } StructElement(); StructElement(long luceneId); StructElement(long luceneId, SolrDocument doc); StructElement(long luceneId, SolrDocument doc, SolrDocument docToMerge); boolean isHasParentOrChildren(); boolean isHasParent(); StructElement getParent(); boolean isHasChildren(); StructElement getTopStruct(); boolean isGroupMember(); boolean isGroup(); String getGroupLabel(String groupIdentifier, String altValue); boolean isExists(); boolean isDeleted(); @Override String getPi(); @Override int getImageNumber(); String getImageUrl(int width, int height); List<EventElement> generateEventElements(Locale locale); boolean isAnchorChild(); String getCollection(); List<String> getCollections(); boolean isFulltextAvailable(); void setFulltextAvailable(boolean fulltextAvailable); boolean isAltoAvailable(); boolean isNerAvailable(); boolean isAccessPermissionDownloadMetadata(); boolean isAccessPermissionGenerateIiifManifest(); @Deprecated String getTitle(); StructElementStub createStub(); Map<String, String> getAncestors(); Map<String, String> getGroupMemberships(); String getDisplayLabel(); IMetadataValue getMultiLanguageDisplayLabel(); String getGroupIdField(); String getFirstVolumeFieldValue(String field); StructElement getFirstVolume(List<String> fields); String getFirstPageFieldValue(String field); boolean mayShowThumbnail(); List<ShapeMetadata> getShapeMetadata(); boolean hasShapeMetadata(); void setShapeMetadata(List<ShapeMetadata> shapeMetadata); boolean isRtl(); void setRtl(boolean rtl); }### Answer:
@Test public void isAnchorChild_shouldReturnTrueIfCurrentRecordIsVolume() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getIddocFromIdentifier("306653648_1891"); Assert.assertNotEquals(-1, iddoc); StructElement element = new StructElement(iddoc); Assert.assertTrue(element.isAnchorChild()); }
@Test public void isAnchorChild_shouldReturnFalseIfCurrentRecordIsNotVolume() throws Exception { StructElement element = new StructElement(iddocKleiuniv); Assert.assertFalse(element.isAnchorChild()); } |
### Question:
CMSCategoryUpdate implements IModelUpdate { public boolean convertData() throws DAOException { if (this.entityMap == null || this.media == null || this.pages == null || this.content == null || this.categories == null) { throw new IllegalStateException("Must successfully run loadData() before calling convertData()"); } if (!this.entityMap.containsKey("media") && !this.entityMap.containsKey("content") && !this.entityMap.containsKey("page")) { return false; } List<CMSCategory> categories = createCategories(entityMap); this.categories = synchronize(categories, this.categories); linkToPages(this.categories, entityMap.get("page"), this.pages); linkToContentItems(categories, entityMap.get("content"), this.content); linkToMedia(categories, entityMap.get("media"), this.media); return true; } @Override boolean update(IDAO dao); void persistData(IDAO dao); void loadData(IDAO dao); boolean convertData(); }### Answer:
@Test public void testAddCategoriesToPages() throws DAOException { update.convertData(); CMSPage page = update.pages.stream().filter(p -> p.getId().equals(2l)).findFirst().get(); Assert.assertEquals(2, page.getCategories().size()); Assert.assertEquals("categoryb", page.getCategories().get(0).getName()); Assert.assertEquals("categoryc", page.getCategories().get(1).getName()); }
@Test public void testAddCategoriesToMedia() throws DAOException { update.convertData(); CMSMediaItem media = update.media.stream().filter(p -> p.getId().equals(1l)).findFirst().get(); Assert.assertEquals(1, media.getCategories().size()); Assert.assertEquals("categoryd", media.getCategories().get(0).getName()); }
@Test public void testAddCategoriesToContent() throws DAOException { update.convertData(); CMSContentItem content = update.content.stream().filter(p -> p.getId().equals(3l)).findFirst().get(); Assert.assertEquals(1, content.getCategories().size()); Assert.assertEquals("categoryd", content.getCategories().get(0).getName()); } |
### Question:
CMSCategoryUpdate implements IModelUpdate { protected List<CMSCategory> createCategories(Map<String, Map<String, List<Long>>> entityMap) { return entityMap.values() .stream() .flatMap(map -> map.keySet().stream()) .flatMap(name -> Arrays.stream(name.split(CLASSIFICATION_SEPARATOR_REGEX))) .filter(name -> StringUtils.isNotBlank(name)) .filter(name -> !name.equals("-")) .map(String::toLowerCase) .distinct() .map(name -> new CMSCategory(name)) .collect(Collectors.toList()); } @Override boolean update(IDAO dao); void persistData(IDAO dao); void loadData(IDAO dao); boolean convertData(); }### Answer:
@Test public void testCreateCategories() throws DAOException { update.convertData(); Assert.assertEquals(5, update.categories.size()); Assert.assertTrue(update.categories.stream().anyMatch(cat -> cat.getName().equals("categoryc"))); } |
### Question:
LoginFilter implements Filter { public static boolean isRestrictedUri(String uri) { if (uri == null) { return false; } if (uri.matches("/?viewer/.*")) { uri = uri.replaceAll("/?viewer/", "/"); } logger.trace("uri: {}", uri); switch (uri.trim()) { case "/myactivity/": case "/mysearches/": return true; default: if (uri.startsWith("/user/activate/")) { return false; } if (uri.startsWith("/user/resetpw/")) { return false; } if (uri.startsWith("/user/")) { return true; } if (uri.matches(".*/campaigns/\\d+/(review|annotate)/.*")) { return true; } if (uri.contains("bookmarks/search/") || uri.contains("bookmarks/session/") || uri.contains("bookmarks/key/") || uri.contains("bookmarks/send/") || uri.contains("bookmarks/search/session")) { return false; } if ((uri.contains("/crowd") && !(uri.contains("about")) || uri.contains("/admin") || uri.contains("/userBackend"))) { return true; } } return false; } @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); static boolean isRestrictedUri(String uri); @Override void init(FilterConfig arg0); }### Answer:
@Test public void isRestrictedUri_shouldReturnTrueForCertainPrettyUris() throws Exception { Assert.assertTrue(LoginFilter.isRestrictedUri("/myactivity/")); Assert.assertTrue(LoginFilter.isRestrictedUri("/mysearches/")); Assert.assertTrue(LoginFilter.isRestrictedUri("/user/bookmarks/show")); Assert.assertTrue(LoginFilter.isRestrictedUri("/viewer/user/bookmarks/show")); }
@Test public void isRestrictedUri_shouldReturnTrueForCrowdsourcingUris() throws Exception { Assert.assertTrue(LoginFilter.isRestrictedUri("/crowdMyAss/")); }
@Test public void isRestrictedUri_shouldReturnFalseForCrowdsourcingAboutPage() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/crowdsourcing/about.xhtml")); }
@Test public void isRestrictedUri_shouldReturnTrueForAdminUris() throws Exception { Assert.assertTrue(LoginFilter.isRestrictedUri("/adminMyAss.xhtml")); }
@Test public void isRestrictedUri_shouldReturnTrueForUserBackendUris() throws Exception { Assert.assertTrue(LoginFilter.isRestrictedUri("/userBackendSlap.xhtml")); }
@Test public void isRestrictedUri_shouldReturnTrueForUserBookmarksUris() throws Exception { Assert.assertTrue(LoginFilter.isRestrictedUri("/viewer/user/bookmarks/etc")); }
@Test public void isRestrictedUri_shouldReturnFalseForBookmarksListUri() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/bookmarks")); }
@Test public void isRestrictedUri_shouldReturnFalseForBookmarksSessionUris() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/bookmarks/session/foo")); }
@Test public void isRestrictedUri_shouldReturnFalseForBookmarksShareKeyUris() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/bookmarks/key/somesharekey/")); }
@Test public void isRestrictedUri_shouldReturnFalseForBookmarksSendListUris() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/bookmarks/send/")); }
@Test public void isRestrictedUri_shouldReturnFalseForUserAccountActivationUris() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/user/activate/[email protected]/abcde/")); }
@Test public void isRestrictedUri_shouldReturnFalseForUserPasswordResetUris() throws Exception { Assert.assertFalse(LoginFilter.isRestrictedUri("/user/resetpw/[email protected]/abcde/")); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.