method2testcases
stringlengths
118
6.63k
### Question: EventBus { public void register(Object object) { subscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, EventHandler> handlers); void register(Object object); void unregister(Object object); void post(Object event); }### Answer: @Test public void testRegister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); Event e2 = new Event(); eventBus.post(e2); assertEquals(asList(e1, e2), subscriber.events); }
### Question: EventBus { public void unregister(Object object) { unsubscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, EventHandler> handlers); void register(Object object); void unregister(Object object); void post(Object event); }### Answer: @Test public void testUnregister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); eventBus.unregister(subscriber); Event e2 = new Event(); eventBus.post(e2); assertEquals(singletonList(e1), subscriber.events); }
### Question: CommandContext { public String[] getSlice(int index) { String[] slice = new String[originalArgs.length - index]; System.arraycopy(originalArgs, index, slice, 0, originalArgs.length - index); return slice; } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); CommandContext(String[] args, Set<Character> valueFlags); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals, boolean parseFlags); static String[] split(String args); SuggestionContext getSuggestionContext(); String getCommand(); boolean matches(String command); String getString(int index); String getString(int index, String def); String getJoinedStrings(int initialIndex); String getRemainingString(int start); String getString(int start, int end); int getInteger(int index); int getInteger(int index, int def); double getDouble(int index); double getDouble(int index, double def); String[] getSlice(int index); String[] getPaddedSlice(int index, int padding); String[] getParsedSlice(int index); String[] getParsedPaddedSlice(int index, int padding); boolean hasFlag(char ch); Set<Character> getFlags(); Map<Character, String> getValueFlags(); String getFlag(char ch); String getFlag(char ch, String def); int getFlagInteger(char ch); int getFlagInteger(char ch, int def); double getFlagDouble(char ch); double getFlagDouble(char ch, double def); int argsLength(); CommandLocals getLocals(); }### Answer: @Test public void testSlice() { try { CommandContext context = new CommandContext("foo bar baz"); assertArrayEquals(new String[] { "foo", "bar", "baz" }, context.getSlice(0)); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } }
### Question: BlockMap extends AbstractMap<BlockVector3, V> { @Override public V get(Object key) { BlockVector3 vec = (BlockVector3) key; Int2ObjectMap<V> activeMap = maps.get(toGroupKey(vec)); if (activeMap == null) { return null; } return activeMap.get(toInnerKey(vec)); } private BlockMap(Supplier<Int2ObjectMap<V>> subMapSupplier); private BlockMap(Supplier<Int2ObjectMap<V>> subMapSupplier, Map<? extends BlockVector3, ? extends V> source); static BlockMap<V> create(); static BlockMap<BaseBlock> createForBaseBlock(); static BlockMap<V> copyOf(Map<? extends BlockVector3, ? extends V> source); @Override V put(BlockVector3 key, V value); @Override V getOrDefault(Object key, V defaultValue); @Override void forEach(BiConsumer<? super BlockVector3, ? super V> action); @Override void replaceAll(BiFunction<? super BlockVector3, ? super V, ? extends V> function); @Override V putIfAbsent(BlockVector3 key, V value); @Override boolean remove(Object key, Object value); @Override boolean replace(BlockVector3 key, V oldValue, V newValue); @Override V replace(BlockVector3 key, V value); @Override V computeIfAbsent(BlockVector3 key, Function<? super BlockVector3, ? extends V> mappingFunction); @Override V computeIfPresent(BlockVector3 key, BiFunction<? super BlockVector3, ? super V, ? extends V> remappingFunction); @Override V compute(BlockVector3 key, BiFunction<? super BlockVector3, ? super V, ? extends V> remappingFunction); @Override V merge(BlockVector3 key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction); @Override Set<Entry<BlockVector3, V>> entrySet(); @Override boolean containsValue(Object value); @Override boolean containsKey(Object key); @Override V get(Object key); @Override V remove(Object key); @SuppressWarnings("unchecked") @Override void putAll(Map<? extends BlockVector3, ? extends V> m); @Override void clear(); @Override int size(); @Override Collection<V> values(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @DisplayName("throws ClassCastException if invalid argument to get") void throwsFromGetOnInvalidArgument() { assertThrows(ClassCastException.class, () -> map.get("")); }
### Question: Expression { public double evaluate(double... values) throws EvaluationException { return evaluate(values, WorldEdit.getInstance().getConfiguration().calculationTimeout); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double evaluate(double... values); double evaluate(double[] values, int timeout); void optimize(); String getSource(); @Override String toString(); SlotTable getSlots(); ExpressionEnvironment getEnvironment(); void setEnvironment(ExpressionEnvironment environment); }### Answer: @TestFactory public Stream<DynamicNode> testEvaluate() throws ExpressionException { List<ExpressionTestCase> testCases = ImmutableList.of( testCase("1 - 2 + 3", 2), testCase("2 + +4", 6), testCase("2 - -4", 6), testCase("2 * -4", -8), testCase("sin(5)", sin(5)), testCase("atan2(3, 4)", atan2(3, 4)), testCase("min(1, 2)", 1), testCase("max(1, 2)", 2), testCase("max(1, 2, 3, 4, 5)", 5), testCase("0 || 5", 5), testCase("2 || 5", 2), testCase("2 && 5", 5), testCase("5 && 0", 0), testCase("false ? 1 : 2", 2), testCase("true ? 1 : 2", 1), testCase("true ? true ? 1 : 2 : 3", 1), testCase("true ? false ? 1 : 2 : 3", 2), testCase("false ? true ? 1 : 2 : 3", 3), testCase("false ? false ? 1 : 2 : 3", 3), testCase("return 1; 0", 1) ); return testCases.stream() .map(testCase -> dynamicTest( testCase.getExpression(), () -> checkTestCase(testCase) )); }
### Question: Expression { public static Expression compile(String expression, String... variableNames) throws ExpressionException { return new Expression(expression, variableNames); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double evaluate(double... values); double evaluate(double[] values, int timeout); void optimize(); String getSource(); @Override String toString(); SlotTable getSlots(); ExpressionEnvironment getEnvironment(); void setEnvironment(ExpressionEnvironment environment); }### Answer: @Test public void testErrors() { { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("#")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("x")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("x()")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("return")); assertEquals(6, e.getPosition(), "Error position"); } assertThrows(ExpressionException.class, () -> compile("(")); assertThrows(ExpressionException.class, () -> compile("x(")); { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("atan2(1)")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("atan2(1, 2, 3)")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("rotate(1, 2, 3)")); assertEquals(7, e.getPosition(), "Error position"); } }
### Question: FileSystemSnapshotDatabase implements SnapshotDatabase { public Path getRoot() { return root; } FileSystemSnapshotDatabase(Path root, ArchiveNioSupport archiveNioSupport); static ZonedDateTime tryParseDate(Path path); static URI createUri(String name); static FileSystemSnapshotDatabase maybeCreate( Path root, ArchiveNioSupport archiveNioSupport ); Path getRoot(); @Override String getScheme(); @Override Optional<Snapshot> getSnapshot(URI name); @Override Stream<Snapshot> getSnapshots(String worldName); }### Answer: @DisplayName("makes the root directory absolute if needed") @Test void rootIsAbsoluteDir() throws IOException { Path root = newTempDb(); try { Path relative = root.getFileSystem().getPath("relative"); Files.createDirectories(relative); FileSystemSnapshotDatabase db2 = new FileSystemSnapshotDatabase(relative, ArchiveNioSupports.combined()); assertEquals(root.getFileSystem().getPath(".").toRealPath() .resolve(relative), db2.getRoot()); Path absolute = root.resolve("absolute"); Files.createDirectories(absolute); FileSystemSnapshotDatabase db3 = new FileSystemSnapshotDatabase(absolute, ArchiveNioSupports.combined()); assertEquals(absolute, db3.getRoot()); } finally { deleteTree(root); } }
### Question: DinnerPermsResolver implements PermissionsResolver { @Override @SuppressWarnings("deprecation") public boolean hasPermission(String name, String permission) { return hasPermission(server.getOfflinePlayer(name), permission); } DinnerPermsResolver(Server server); static PermissionsResolver factory(Server server, YAMLProcessor config); @Override void load(); @Override @SuppressWarnings("deprecation") boolean hasPermission(String name, String permission); @Override @SuppressWarnings("deprecation") boolean hasPermission(String worldName, String name, String permission); @Override @SuppressWarnings("deprecation") boolean inGroup(String name, String group); @Override @SuppressWarnings("deprecation") String[] getGroups(String name); @Override boolean hasPermission(OfflinePlayer player, String permission); @Override boolean hasPermission(String worldName, OfflinePlayer player, String permission); @Override boolean inGroup(OfflinePlayer player, String group); @Override String[] getGroups(OfflinePlayer player); Permissible getPermissible(OfflinePlayer offline); int internalHasPermission(Permissible perms, String permission); @Override String getDetectionMessage(); static final String GROUP_PREFIX; }### Answer: @Test public void testBasicResolving() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("testperm.test1", true); assertTrue(resolver.hasPermission(permissible, "testperm.test1")); assertFalse(resolver.hasPermission(permissible, "testperm.somethingelse")); assertFalse(resolver.hasPermission(permissible, "testperm.test1.anything")); assertFalse(resolver.hasPermission(permissible, "completely.unrelated")); permissible.clearPermissions(); } @Test public void testBasicWildcardResolution() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("commandbook.spawnmob.*", true); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.pig")); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.spider")); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.spider.skeleton")); permissible.clearPermissions(); } @Test public void testNegatingNodes() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("commandbook.*", true); permissible.setPermission("commandbook.cuteasianboys", false); permissible.setPermission("commandbook.warp.*", false); permissible.setPermission("commandbook.warp.create", true); assertTrue(resolver.hasPermission(permissible, "commandbook.motd")); assertFalse(resolver.hasPermission(permissible, "commandbook.cuteasianboys")); assertFalse(resolver.hasPermission(permissible, "commandbook.warp.remove")); assertTrue(resolver.hasPermission(permissible, "commandbook.warp.create")); permissible.clearPermissions(); }
### Question: DinnerPermsResolver implements PermissionsResolver { @Override @SuppressWarnings("deprecation") public boolean inGroup(String name, String group) { return inGroup(server.getOfflinePlayer(name), group); } DinnerPermsResolver(Server server); static PermissionsResolver factory(Server server, YAMLProcessor config); @Override void load(); @Override @SuppressWarnings("deprecation") boolean hasPermission(String name, String permission); @Override @SuppressWarnings("deprecation") boolean hasPermission(String worldName, String name, String permission); @Override @SuppressWarnings("deprecation") boolean inGroup(String name, String group); @Override @SuppressWarnings("deprecation") String[] getGroups(String name); @Override boolean hasPermission(OfflinePlayer player, String permission); @Override boolean hasPermission(String worldName, OfflinePlayer player, String permission); @Override boolean inGroup(OfflinePlayer player, String group); @Override String[] getGroups(OfflinePlayer player); Permissible getPermissible(OfflinePlayer offline); int internalHasPermission(Permissible perms, String permission); @Override String getDetectionMessage(); static final String GROUP_PREFIX; }### Answer: @Test public void testInGroup() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("group.a", true); permissible.setPermission("group.b", true); assertTrue(resolver.inGroup(permissible, "a")); assertTrue(resolver.inGroup(permissible, "b")); assertFalse(resolver.inGroup(permissible, "c")); }
### Question: BukkitWorld extends AbstractWorld { public static TreeType toBukkitTreeType(TreeGenerator.TreeType type) { return treeTypeMapping.get(type); } BukkitWorld(World world); @Override List<com.sk89q.worldedit.entity.Entity> getEntities(Region region); @Override List<com.sk89q.worldedit.entity.Entity> getEntities(); @Nullable @Override com.sk89q.worldedit.entity.Entity createEntity(com.sk89q.worldedit.util.Location location, BaseEntity entity); World getWorld(); @Override String getName(); @Override String getId(); @Override Path getStoragePath(); @Override int getBlockLightLevel(BlockVector3 pt); @Override boolean regenerate(Region region, Extent extent, RegenOptions options); @Override boolean clearContainerBlockContents(BlockVector3 pt); static TreeType toBukkitTreeType(TreeGenerator.TreeType type); @Override boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 pt); @Override void dropItem(Vector3 pt, BaseItemStack item); @Override void checkLoadedChunk(BlockVector3 pt); @Override boolean equals(Object other); @Override int hashCode(); @Override int getMaxY(); @SuppressWarnings("deprecation") @Override void fixAfterFastMode(Iterable<BlockVector2> chunks); @Override boolean playEffect(Vector3 position, int type, int data); @Override WeatherType getWeather(); @Override long getRemainingWeatherDuration(); @Override void setWeather(WeatherType weatherType); @Override void setWeather(WeatherType weatherType, long duration); @Override BlockVector3 getSpawnPosition(); @Override void simulateBlockMine(BlockVector3 pt); @Override boolean canPlaceAt(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState blockState); @Override com.sk89q.worldedit.world.block.BlockState getBlock(BlockVector3 position); @Override boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects); @Override BaseBlock getFullBlock(BlockVector3 position); @Override Set<SideEffect> applySideEffects(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState previousType, SideEffectSet sideEffectSet); @Override boolean useItem(BlockVector3 position, BaseItem item, Direction face); @Override boolean fullySupports3DBiomes(); @SuppressWarnings("deprecation") @Override BiomeType getBiome(BlockVector3 position); @SuppressWarnings("deprecation") @Override boolean setBiome(BlockVector3 position, BiomeType biome); }### Answer: @Test public void testTreeTypeMapping() { for (TreeGenerator.TreeType type : TreeGenerator.TreeType.values()) { assertNotNull(BukkitWorld.toBukkitTreeType(type), "No mapping for: " + type); } }
### Question: CommandContext { public int argsLength() { return parsedArgs.size(); } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); CommandContext(String[] args, Set<Character> valueFlags); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals, boolean parseFlags); static String[] split(String args); SuggestionContext getSuggestionContext(); String getCommand(); boolean matches(String command); String getString(int index); String getString(int index, String def); String getJoinedStrings(int initialIndex); String getRemainingString(int start); String getString(int start, int end); int getInteger(int index); int getInteger(int index, int def); double getDouble(int index); double getDouble(int index, double def); String[] getSlice(int index); String[] getPaddedSlice(int index, int padding); String[] getParsedSlice(int index); String[] getParsedPaddedSlice(int index, int padding); boolean hasFlag(char ch); Set<Character> getFlags(); Map<Character, String> getValueFlags(); String getFlag(char ch); String getFlag(char ch, String def); int getFlagInteger(char ch); int getFlagInteger(char ch, int def); double getFlagDouble(char ch); double getFlagDouble(char ch, double def); int argsLength(); CommandLocals getLocals(); }### Answer: @Test public void testEmptyQuote() { try { CommandContext context = new CommandContext("region flag xmas blocked-cmds \"\""); assertEquals(context.argsLength(), 3); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } }
### Question: Location { public Extent getExtent() { return extent; } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetWorld() throws Exception { World world = mock(World.class); Location location = new Location(world); assertEquals(world, location.getExtent()); }
### Question: Location { public Vector3 toVector() { return position; } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testToVector() throws Exception { World world = mock(World.class); Vector3 position = Vector3.at(1, 1, 1); Location location = new Location(world, position); assertEquals(position, location.toVector()); }
### Question: Location { public double getX() { return position.getX(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetX() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getX(), EPSILON); }
### Question: Location { public int getBlockX() { return (int) Math.floor(position.getX()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetBlockX() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getBlockX()); }
### Question: Location { public Location setX(double x) { return new Location(extent, position.withX(x), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testSetX() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setX(TEST_VALUE); assertEquals(0, location1.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getX(), EPSILON); assertEquals(0, location2.getY(), EPSILON); assertEquals(0, location2.getZ(), EPSILON); }
### Question: Location { public double getY() { return position.getY(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetY() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getY(), EPSILON); }
### Question: Location { public int getBlockY() { return (int) Math.floor(position.getY()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetBlockY() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getBlockY()); }
### Question: ViewerResourceBundle extends ResourceBundle { static String replaceParameters(final String msg, String... params) { String ret = msg; if (ret != null && params != null) { for (int i = 0; i < params.length; ++i) { ret = ret.replace(new StringBuilder("{").append(i).append("}").toString(), params[i]); } } return ret; } ViewerResourceBundle(); static Locale getDefaultLocale(); static String getTranslation(final String key, Locale locale); static String getTranslationWithParameters(final String key, final Locale locale, final String... params); static String getTranslation(final String key, Locale locale, boolean useFallback); static String cleanUpTranslation(String value); static List<String> getMessagesValues(Locale locale, String keyPrefix); @Override Enumeration<String> getKeys(); static List<Locale> getAllLocales(); static List<Locale> getFacesLocales(); static IMetadataValue getTranslations(String key); static IMetadataValue getTranslations(String key, boolean allowKeyAsTranslation); static List<Locale> getLocalesFromFacesConfig(); static List<Locale> getLocalesFromFile(Path facesConfigPath); static Thread backgroundThread; }### Answer: @Test public void replaceParameters_shouldReturnNullIfMsgIsNull() throws Exception { Assert.assertNull(ViewerResourceBundle.replaceParameters(null, "one", "two", "three")); } @Test public void replaceParameters_shouldReplaceParametersCorrectly() throws Exception { Assert.assertEquals("one two three", ViewerResourceBundle.replaceParameters("{0} {1} {2}", "one", "two", "three")); }
### Question: StructElement extends StructElementStub implements Comparable<StructElementStub>, Serializable { @Override public String getPi() { if (pi != null && !pi.equals("null")) { return pi; } else if (getMetadataValue(SolrConstants.PI_TOPSTRUCT) != null) { pi = getMetadataValue(SolrConstants.PI_TOPSTRUCT); return pi; } else if (!work && !anchor) { try { return Optional.ofNullable(this.getTopStruct()).map(StructElement::getPi).orElse(null); } catch (PresentationException | IndexUnreachableException e) { return null; } } return null; } 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 getPi_shouldRetrivevePiFromTopstructIfNotTopstruct() throws Exception { long iddoc = DataManager.getInstance().getSearchIndex().getIddocByLogid(PI_KLEIUNIV, "LOG_0002"); Assert.assertNotEquals(-1, iddoc); StructElement element = new StructElement(iddoc); Assert.assertEquals(PI_KLEIUNIV, element.getPi()); } @Test public void getPi_shouldReturnPiIfTopstruct() throws Exception { StructElement element = new StructElement(iddocKleiuniv); Assert.assertEquals(PI_KLEIUNIV, element.getPi()); }
### Question: LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public int getNumPages() throws IndexUnreachableException { if (numPages < 0) { numPages = topElement.getNumPages(); } return numPages; } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getNumPages_shouldReturnSizeCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, 5); Assert.assertEquals(5, pageLoader.getNumPages()); pageLoader = new LeanPageLoader(se, -1); Assert.assertEquals(16, pageLoader.getNumPages()); }
### Question: LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPage(int pageOrder) throws IndexUnreachableException, DAOException { if (pageOrder != currentPageNumber && pageOrder >= firstPageOrder && pageOrder <= lastPageOrder) { try { currentPage = loadPage(pageOrder, null); currentPageNumber = pageOrder; } catch (PresentationException e) { logger.debug("PresentationException thrown here: {}", e.getMessage()); } return currentPage; } else if (pageOrder == currentPageNumber) { ; return currentPage; } else { return null; } } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getPage_shouldReturnCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPage(3); Assert.assertNotNull(pe); Assert.assertEquals(3, pe.getOrder()); } @Test public void getPage_shouldReturnNullIfPageOrderSmallerThanFirstPageOrder() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPage(-1); Assert.assertNull(pe); } @Test public void getPage_shouldReturnNullIfPageOrderLargerThanLastPageOrder() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPage(20); Assert.assertNull(pe); }
### Question: LeanPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPageForFileName(String fileName) throws PresentationException, IndexUnreachableException, DAOException { return loadPage(-1, fileName); } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getPageForFileName_shouldReturnTheCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPageForFileName("00000004.tif"); Assert.assertNotNull(pe); Assert.assertEquals(4, pe.getOrder()); } @Test public void getPageForFileName_shouldReturnNullIfFileNameNotFound() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.getPageForFileName("NOTFOUND.tif"); Assert.assertNull(pe); }
### Question: LeanPageLoader extends AbstractPageLoader implements Serializable { protected PhysicalElement loadPage(int pageNumber, String fileName) throws PresentationException, IndexUnreachableException, DAOException { String pi = topElement.getPi(); if (pageNumber >= 0) { logger.trace("Loading page {} for '{}'...", pageNumber, pi); } List<String> fields = new ArrayList<>(Arrays.asList(FIELDS)); StringBuilder sbQuery = new StringBuilder(); sbQuery.append('+') .append(SolrConstants.PI_TOPSTRUCT) .append(':') .append(pi) .append(" +") .append(SolrConstants.DOCTYPE) .append(':') .append(DocType.PAGE); if (pageNumber >= 0) { sbQuery.append(" +").append(SolrConstants.ORDER).append(':').append(pageNumber); } if (fileName != null) { sbQuery.append(" +").append(SolrConstants.FILENAME).append(":\"").append(fileName).append("\""); } SolrDocumentList result = DataManager.getInstance().getSearchIndex().search(sbQuery.toString(), 1, null, fields); if (result.isEmpty()) { return null; } return loadPageFromDoc(result.get(0), pi, topElement, null); } LeanPageLoader(StructElement topElement, int numPages); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void loadPage_shouldLoadPageCorrectlyViaPageNumber() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.loadPage(3, null); Assert.assertNotNull(pe); Assert.assertEquals(3, pe.getOrder()); } @Test public void loadPage_shouldLoadPageCorrectlyViaFileName() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.loadPage(-1, "00000004.tif"); Assert.assertNotNull(pe); Assert.assertEquals(4, pe.getOrder()); } @Test public void loadPage_shouldReturnNullIfPageNotFound() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); LeanPageLoader pageLoader = new LeanPageLoader(se, -1); PhysicalElement pe = pageLoader.loadPage(-1, "NOTFOUND.tif"); }
### Question: IpRange implements ILicensee, Serializable { public boolean canSatisfyAllAccessConditions(Set<String> conditionList, List<LicenseType> licenseTypes, String privilegeName, String pi) throws PresentationException, IndexUnreachableException, DAOException { if (AccessConditionUtils.isFreeOpenAccess(conditionList, licenseTypes)) { return true; } Map<String, Boolean> permissionMap = new HashMap<>(conditionList.size()); for (String accessCondition : conditionList) { permissionMap.put(accessCondition, false); if (hasLicense(accessCondition, privilegeName, pi)) { permissionMap.put(accessCondition, true); continue; } } return permissionMap.isEmpty() || permissionMap.containsValue(true); } @Override int hashCode(); @Override boolean equals(Object obj); boolean matchIp(String inIp); @Override boolean hasLicense(String licenseName, String privilegeName, String pi); boolean canSatisfyAllAccessConditions(Set<String> conditionList, List<LicenseType> licenseTypes, String privilegeName, String pi); @Override boolean addLicense(License license); @Override boolean removeLicense(License license); Long getId(); void setId(Long id); @Override String getName(); void setName(String name); String getSubnetMask(); void setSubnetMask(String subnetMask); String getDescription(); void setDescription(String description); @Override List<License> getLicenses(); void setLicenses(List<License> licenses); static void main(String[] args); }### Answer: @Test public void canSatisfyAllAccessConditions_shouldReturnFalseIfIpRangeHasNoLicense() throws Exception { IpRange ipRange = DataManager.getInstance().getDao().getIpRange(1); Assert.assertNotNull(ipRange); Assert.assertFalse(ipRange.canSatisfyAllAccessConditions(new HashSet<>(Collections.singletonList("license type 2 name")), null, IPrivilegeHolder.PRIV_LIST, "PPN123")); } @Test public void canSatisfyAllAccessConditions_shouldReturnTrueIfConditionListEmpty() throws Exception { IpRange ipRange = new IpRange(); Assert.assertTrue(ipRange.canSatisfyAllAccessConditions(new HashSet<String>(0), null, "restricted", "PPN123")); } @Test public void canSatisfyAllAccessConditions_shouldReturnTrueIfConditionIsOpenAccess() throws Exception { IpRange ipRange = new IpRange(); Assert.assertTrue(ipRange.canSatisfyAllAccessConditions(new HashSet<>(Collections.singletonList(SolrConstants.OPEN_ACCESS_VALUE)), null, IPrivilegeHolder.PRIV_LIST, "PPN123")); } @Test public void canSatisfyAllAccessConditions_shouldReturnTrueIfIpRangeHasLicense() throws Exception { IpRange ipRange = DataManager.getInstance().getDao().getIpRange(1); Assert.assertNotNull(ipRange); List<String> licences = Arrays.asList(new String[] { "license type 3 name", "restriction on access" }); Assert.assertTrue(ipRange.canSatisfyAllAccessConditions(new HashSet<>(licences), null, IPrivilegeHolder.PRIV_LIST, "PPN123")); }
### Question: EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getNumPages() { return pages.size(); } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getNumPages_shouldReturnSizeCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(16, pageLoader.getNumPages()); }
### Question: EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPage(int pageOrder) { return pages.get(pageOrder); } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getPage_shouldReturnCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); PhysicalElement pe = pageLoader.getPage(3); Assert.assertNotNull(pe); Assert.assertEquals(3, pe.getOrder()); }
### Question: EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public PhysicalElement getPageForFileName(String fileName) { for (int key : pages.keySet()) { PhysicalElement page = pages.get(key); if (fileName.equals(page.getFileName())) { return page; } } return null; } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void getPageForFileName_shouldReturnTheCorrectPage() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); PhysicalElement pe = pageLoader.getPageForFileName("00000004.tif"); Assert.assertNotNull(pe); Assert.assertEquals(4, pe.getOrder()); } @Test public void getPageForFileName_shouldReturnNullIfFileNameNotFound() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); PhysicalElement pe = pageLoader.getPageForFileName("NOTFOUND.tif"); Assert.assertNull(pe); }
### Question: EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getFirstPageOrder() { return firstPageOrder; } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void setFirstAndLastPageOrder_shouldSetFirstPageOrderCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(1, pageLoader.getFirstPageOrder()); }
### Question: EagerPageLoader extends AbstractPageLoader implements Serializable { @Override public int getLastPageOrder() { return lastPageOrder; } EagerPageLoader(StructElement topElement); @Override int getNumPages(); @Override int getFirstPageOrder(); @Override int getLastPageOrder(); @Override PhysicalElement getPage(int pageOrder); @Override PhysicalElement getPageForFileName(String fileName); @Override Long getOwnerIddocForPage(int pageOrder); @Override void generateSelectItems(List<SelectItem> dropdownPages, List<SelectItem> dropdownFulltext, String urlRoot, boolean recordBelowFulltextThreshold, Locale locale); }### Answer: @Test public void setFirstAndLastPageOrder_shouldSetLastPageOrderCorrectly() throws Exception { StructElement se = new StructElement(iddocKleiuniv); Assert.assertNotNull(se); EagerPageLoader pageLoader = new EagerPageLoader(se); Assert.assertEquals(16, pageLoader.getLastPageOrder()); }
### Question: AbstractPageLoader implements IPageLoader { protected String buildPageLabelTemplate(String format, Locale locale) throws IndexUnreachableException { if (format == null) { throw new IllegalArgumentException("format may not be null"); } String labelTemplate = format.replace("{numpages}", String.valueOf(getNumPages())); Pattern p = Pattern.compile("\\{msg\\..*?\\}"); Matcher m = p.matcher(labelTemplate); while (m.find()) { String key = labelTemplate.substring(m.start() + 5, m.end() - 1); labelTemplate = labelTemplate.replace(labelTemplate.substring(m.start(), m.end()), ViewerResourceBundle.getTranslation(key, locale)); } return labelTemplate; } static PhysicalElement loadPage(StructElement topElement, int page); }### Answer: @Test public void buildPageLabelTemplate_shouldReplaceNumpagesCurrectly() throws Exception { StructElement se = new StructElement(); EagerPageLoader loader = new EagerPageLoader(se); Assert.assertEquals("foo 0 bar", loader.buildPageLabelTemplate("foo {numpages} bar", null)); } @Test public void buildPageLabelTemplate_shouldReplaceMessageKeysCorrectly() throws Exception { StructElement se = new StructElement(); EagerPageLoader loader = new EagerPageLoader(se); Assert.assertEquals("1 of 10", loader.buildPageLabelTemplate("1 {msg.of} 10", null)); }
### Question: PhysicalElement implements Comparable<PhysicalElement>, Serializable { protected static String determineFileName(String filePath) { String ret = filePath; if (StringUtils.isNotBlank(ret) && !(ret.startsWith("http: File file = new File(ret); ret = file.getName(); } return ret; } PhysicalElement(String physId, String filePath, int order, String orderLabel, String urn, String purlPart, String pi, String mimeType, String dataRepository); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(PhysicalElement o); String getUrl(); String getSandboxedUrl(); String getWatermarkText(); String getThumbnailUrl(); String getThumbnailUrl(int width, int height); String getId(); String getFilepath(); int getOrder(); String getOrderLabel(); String getUrn(); void setPurlPart(String purlPart); String getPurlPart(); String getDisplayMimeType(); static String getFullMimeType(String baseType, String fileName); @Deprecated String getFullMimeType(); String getMimeType(); void setMimeType(String mimeType); void setWidth(int width); void setHeight(int height); String getFileName(); String getFileNameBase(); String getFileNameExtension(); String getFileIdRoot(); void setFileIdRoot(String fileIdRoot); boolean isDisplayImage(); boolean isHasImage(); void setHasImage(boolean hasImage); boolean isDisplayFulltext(); boolean isFulltextAvailable(); Boolean isFulltextAccessPermission(); void setFulltextAvailable(boolean fulltextAvailable); boolean isAltoAvailable(); boolean isTeiAvailable(); String getFulltextFileName(); void setFulltextFileName(String fulltextFileName); String getAltoFileName(); void setAltoFileName(String altoFileName); String getFullText(); String getFulltextMimeType(); void setFullText(String fullText); List<String> getWordCoords(Set<String> searchTerms); List<String> getWordCoords(Set<String> searchTerms, int rotation); String loadAlto(); Map<String, String> getFileNames(); void setFileNames(Map<String, String> fileNames); String getFileNameForFormat(String format); String getFilename(); String getImageToPdfUrl(); String getMediaUrl(String format); int getVideoWidth(); int getVideoHeight(); int getImageWidth(); int getImageHeight(); int getPhysicalImageHeight(); int getImageZoomFactor(); String getImageUrl(); String getImageUrl(int size); int getMixWidth(); int getPhysicalImageWidth(); String getPi(); Set<String> getAccessConditions(); void setAccessConditions(Set<String> accessConditions); String getPageLinkLabel(); boolean isAccessPermission3DObject(); boolean isAccessPermissionImage(); boolean isAccessPermissionObject(); boolean isAccessPermissionPdf(); boolean isAccessPermissionBornDigital(); boolean isAccessPermissionFulltext(); int getFooterHeight(); int getFooterHeight(String pageType); int getImageFooterHeight(); int getImageFooterHeight(int rotation); Comment getCurrentComment(); void setCurrentComment(Comment currentComment); void resetCurrentComment(); List<Comment> getComments(); void createNewCommentAction(User user); void updateCommentAction(Comment comment); void saveCommentAction(Comment comment); void deleteCommentAction(Comment comment); boolean hasIndividualSize(); String getAltoText(); CoordsFormat getWordCoordsFormat(); String getDataRepository(); long getFileSize(); void setFileSize(long fileSize); String getFileSizeAsString(); ImageType getImageType(); String getFileName(String extension); boolean isDisplayPagePdfLink(); boolean isAdaptImageViewHeight(); List<StructElement> getContainedStructElements(); String getContainedStructElementsAsJson(); static final String WATERMARK_TEXT_TYPE_URN; static final String WATERMARK_TEXT_TYPE_PURL; static final String WATERMARK_TEXT_TYPE_SOLR; static int defaultVideoWidth; static int defaultVideoHeight; }### Answer: @Test public void determineFileName_shouldCutOffEverythingButTheFileNameForNormalFilePaths() throws Exception { Assert.assertEquals("image.jpg", PhysicalElement.determineFileName("image.jpg")); Assert.assertEquals("image.jpg", PhysicalElement.determineFileName("/opt/digiverso/viewer/media/123/image.jpg")); } @Test public void determineFileName_shouldLeaveExternalUrlsIntact() throws Exception { Assert.assertEquals("http: }
### Question: EventElement implements Comparable<EventElement>, Serializable { public Date getDateStart() { return dateStart; } EventElement(SolrDocument doc, Locale locale); @Override int compareTo(EventElement o); String getDisplayDate(); String getLabel(); String getType(); void setType(String type); Date getDateStart(); void setDateStart(Date dateStart); Date getDateEnd(); void setDateEnd(Date dateEnd); List<Metadata> getMetadata(); boolean isHasMetadata(); boolean isHasSidebarMetadata(); List<Metadata> getSidebarMetadata(); }### Answer: @Test public void EventElement_shouldFillInMissingDateStartFromDisplayDate() throws Exception { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.EVENTDATE, "2018-11-23"); EventElement ee = new EventElement(doc, null); Assert.assertNotNull(ee.getDateStart()); Assert.assertEquals("2018-11-23", DateTools.format(ee.getDateStart(), DateTools.formatterISO8601Date, false)); }
### Question: EventElement implements Comparable<EventElement>, Serializable { public Date getDateEnd() { return dateEnd; } EventElement(SolrDocument doc, Locale locale); @Override int compareTo(EventElement o); String getDisplayDate(); String getLabel(); String getType(); void setType(String type); Date getDateStart(); void setDateStart(Date dateStart); Date getDateEnd(); void setDateEnd(Date dateEnd); List<Metadata> getMetadata(); boolean isHasMetadata(); boolean isHasSidebarMetadata(); List<Metadata> getSidebarMetadata(); }### Answer: @Test public void EventElement_shouldFillInMissingDateEndFromDateStart() throws Exception { SolrDocument doc = new SolrDocument(); doc.setField(SolrConstants.EVENTDATESTART, "2018-11-23"); EventElement ee = new EventElement(doc, null); Assert.assertNotNull(ee.getDateEnd()); Assert.assertEquals("2018-11-23", DateTools.format(ee.getDateEnd(), DateTools.formatterISO8601Date, false)); }
### Question: TocMaker { protected static List<String> getSolrFieldsToFetch(String template) { logger.trace("getSolrFieldsToFetch: {}", template); Set<String> ret = new HashSet<>(Arrays.asList(REQUIRED_FIELDS)); List<Metadata> metadataList = DataManager.getInstance().getConfiguration().getTocLabelConfiguration(template); if (metadataList != null && !metadataList.isEmpty()) { for (MetadataParameter param : metadataList.get(0).getParams()) { if (StringUtils.isNotEmpty(param.getKey())) { ret.add(param.getKey()); ret.add(param.getKey() + "_LANG_EN"); ret.add(param.getKey() + "_LANG_DE"); ret.add(param.getKey() + "_LANG_FR"); ret.add(param.getKey() + "_LANG_ES"); ret.add(param.getKey() + "_LANG_PT"); ret.add(param.getKey() + "_LANG_HR"); ret.add(param.getKey() + "_LANG_AR"); } } } List<String> ancestorFields = DataManager.getInstance().getConfiguration().getAncestorIdentifierFields(); if (ancestorFields != null) { ret.addAll(ancestorFields); } return new ArrayList<>(ret); } static LinkedHashMap<String, List<TOCElement>> generateToc(TOC toc, StructElement structElement, boolean addAllSiblings, String mimeType, int tocCurrentPage, int hitsPerPage); @SuppressWarnings("rawtypes") static String getFirstFieldValue(SolrDocument doc, String footerIdField); static IMetadataValue createMultiLanguageValue(SolrDocument doc, String field, String altField); }### Answer: @Test public void getSolrFieldsToFetch_shouldReturnBothStaticAndConfiguredFields() throws Exception { List<?> fields = TocMaker.getSolrFieldsToFetch("_DEFAULT"); Assert.assertNotNull(fields); Assert.assertEquals(33, fields.size()); }
### Question: TOCElement implements Serializable { public String getUrl() { return urlPrefix + urlSuffix; } TOCElement(IMetadataValue label, String pageNo, String pageNoLabel, String iddoc, String logId, int level, String topStructPi, String thumbnailUrl, boolean accessPermissionPdf, boolean anchorOrGroup, boolean hasImages, String recordMimeType, String docStructType, String footerId); @Override int hashCode(); @Override boolean equals(Object obj); String getContentServerPdfUrl(); boolean isAccessPermissionPdf(); String getThumbnailUrl(); String getThumbnailUrl(int width, int height); String getLabel(); String getLabel(Locale locale); String getLabel(String locale); Map<String, String> getMetadata(); String getMetadataValue(String key); String getPageNo(); String getIddoc(); String getPageNoLabel(); String getTopStructPi(); String getLogId(); int getLevel(); @Deprecated String getSubLabel(); String getUrl(); String getUrl(String viewType); String getFullscreenUrl(); @Deprecated String getReadingModeUrl(); boolean isVisible(); void setVisible(boolean visible); int getParentId(); void setParentId(int parentId); int getID(); void setID(int iD); boolean isExpanded(); void setExpanded(boolean expanded); boolean isHasChild(); void setHasChild(boolean hasChild); List<String> getGroupIds(); void setGroupIds(List<String> groupIds); String getRecordMimeType(); boolean isEmpty(); }### Answer: @Test public void getUrl_shouldConstructFullScreenUrlCorrectly() throws Exception { TOCElement tef = new TOCElement(new SimpleMetadataValue("Label"), "1", "first", "123", "LOG_0001", 0, "PPN123", null, false, false, true, "image", null, null); Assert.assertEquals('/' + PageType.viewFullscreen.getName() + "/PPN123/1/LOG_0001/", tef.getUrl(PageType.viewFullscreen.getName())); } @Test public void getUrl_shouldConstructReadingModeUrlCorrectly() throws Exception { TOCElement tef = new TOCElement(new SimpleMetadataValue("Label"), "1", "first", "123", "LOG_0001", 0, "PPN123", null, false, false, true, "image", null, null); Assert.assertEquals('/' + PageType.viewFullscreen.getName() + "/PPN123/1/LOG_0001/", tef.getUrl(PageType.viewFullscreen.getName())); }
### Question: CalendarView { public List<String> getVolumeYears() throws PresentationException, IndexUnreachableException { if (anchorPi == null) { return Collections.emptyList(); } return SearchHelper.getFacetValues("+" + SolrConstants.PI_ANCHOR + ":" + anchorPi + " +" + SolrConstants._CALENDAR_DAY + ":*", SolrConstants._CALENDAR_YEAR, 1); } CalendarView(String pi, String anchorPi, String year); boolean isDisplay(); void populateCalendar(); List<String> getVolumeYears(); String getYear(); void setYear(String year); List<CalendarItemMonth> getCalendarItems(); }### Answer: @Test public void getVolumeYears_shouldOnlyReturnVolumeYearsThatHaveYEARMONTHDAYField() throws Exception { CalendarView cv = new CalendarView("168714434_1805", "168714434", null); List<String> years = cv.getVolumeYears(); Assert.assertEquals(9, years.size()); }
### Question: Sitemap { private Element createUrlElement(String pi, int order, String dateModified, String type, String changefreq, String priority) { return createUrlElement(viewerRootUrl + '/' + type + '/' + pi + '/' + order + '/', dateModified, changefreq, priority); } List<File> generate(String viewerRootUrl, String outputPath); }### Answer: @Test public void createUrlElement_shouldCreateLocElementCorrectly() throws Exception { Sitemap sitemap = new Sitemap(); Element eleUrl = sitemap.createUrlElement("https: Assert.assertNotNull(eleUrl); Assert.assertEquals("https: } @Test public void createUrlElement_shouldCreateLastmodElementCorrectly() throws Exception { Sitemap sitemap = new Sitemap(); Element eleUrl = sitemap.createUrlElement("https: Assert.assertNotNull(eleUrl); Assert.assertEquals("2018-08-21", eleUrl.getChildText("lastmod", Sitemap.nsSitemap)); }
### Question: ViewerPathBuilder { public static boolean startsWith(URI uri, String string) { if (uri != null) { if (uri.toString().endsWith("/") && !string.endsWith("/")) { string = string + "/"; } String[] uriParts = uri.toString().split("/"); String[] stringParts = string.toString().split("/"); if (uriParts.length < stringParts.length) { return false; } boolean match = true; for (int i = 0; i < stringParts.length; i++) { if (!stringParts[i].equals(uriParts[i])) { match = false; } } return match; } else { return false; } } static Optional<ViewerPath> createPath(HttpServletRequest httpRequest); static Optional<ViewerPath> createPath(HttpServletRequest request, String baseUrl); static Optional<ViewerPath> createPath(String applicationUrl, String applicationName, String serviceUrl); static Optional<CMSPage> getCmsPage(URI servicePath); static Optional<Campaign> getCampaign(URI servicePath); static Optional<PageType> getPageType(final URI servicePath); static boolean startsWith(URI uri, String string); static URI resolve(URI master, URI slave); static URI resolve(URI master, String slave); }### Answer: @Test public void testStartsWith() { String url1 = "a"; String url2 = "a/b"; String url3 = "a/b/c"; String url4 = "f"; String url5 = "b/a"; String url6 = "a/bc"; URI uri = URI.create("a/b/cdef"); Assert.assertTrue(ViewerPathBuilder.startsWith(uri, url1)); Assert.assertTrue(ViewerPathBuilder.startsWith(uri, url2)); Assert.assertFalse(ViewerPathBuilder.startsWith(uri, url3)); Assert.assertFalse(ViewerPathBuilder.startsWith(uri, url4)); Assert.assertFalse(ViewerPathBuilder.startsWith(uri, url5)); Assert.assertFalse(ViewerPathBuilder.startsWith(uri, url6)); }
### Question: AdvancedSearchFieldConfiguration { public String getLabel() { if (label == null) { return field; } return label; } AdvancedSearchFieldConfiguration(String field); String getField(); String getLabel(); AdvancedSearchFieldConfiguration setLabel(String label); boolean isHierarchical(); AdvancedSearchFieldConfiguration setHierarchical(boolean hierarchical); boolean isRange(); AdvancedSearchFieldConfiguration setRange(boolean range); boolean isUntokenizeForPhraseSearch(); AdvancedSearchFieldConfiguration setUntokenizeForPhraseSearch(boolean untokenizeForPhraseSearch); boolean isDisabled(); AdvancedSearchFieldConfiguration setDisabled(boolean disabled); }### Answer: @Test public void getLabel_shouldReturnFieldIfLabelNull() throws Exception { Assert.assertEquals("field", new AdvancedSearchFieldConfiguration("field").getLabel()); }
### Question: SearchFacets implements Serializable { static String generateFacetPrefix(List<FacetItem> facetItems, boolean escapeSlashes) { if (facetItems == null) { throw new IllegalArgumentException("facetItems may not be null"); } StringBuilder sb = new StringBuilder(); for (FacetItem facetItem : facetItems) { if (escapeSlashes) { sb.append(BeanUtils.escapeCriticalUrlChracters(facetItem.getLink())); } else { sb.append(facetItem.getLink()); } sb.append(";;"); } return sb.toString(); } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void generateFacetPrefix_shouldEncodeSlashedAndBackslashes() throws Exception { List<FacetItem> list = new ArrayList<>(); list.add(new FacetItem("FIELD:a/b\\c", false)); Assert.assertEquals("FIELD:a/b\\c;;", SearchFacets.generateFacetPrefix(list, false)); Assert.assertEquals("FIELD:aU002FbU005Cc;;", SearchFacets.generateFacetPrefix(list, true)); }
### Question: UserTools { public static int deleteBookmarkListsForUser(User owner) throws DAOException { List<BookmarkList> bookmarkLists = DataManager.getInstance().getDao().getBookmarkLists(owner); if (bookmarkLists.isEmpty()) { return 0; } int count = 0; for (BookmarkList bookmarkList : bookmarkLists) { if (DataManager.getInstance().getDao().deleteBookmarkList(bookmarkList)) { count++; } } logger.debug("{} bookmarklists of user {} deleted.", count, owner.getId()); return count; } static boolean deleteUser(User user); static int deleteUserGroupOwnedByUser(User owner); static int deleteBookmarkListsForUser(User owner); static int deleteSearchesForUser(User owner); static void deleteUserPublicContributions(User user); static boolean anonymizeUserPublicContributions(User user); static User checkAndCreateAnonymousUser(); }### Answer: @Test public void deleteBookmarkListsForUser_shouldDeleteAllBookmarkListsOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertFalse(DataManager.getInstance().getDao().getBookmarkLists(user).isEmpty()); UserTools.deleteBookmarkListsForUser(user); Assert.assertTrue(DataManager.getInstance().getDao().getBookmarkLists(user).isEmpty()); }
### Question: SearchFacets implements Serializable { public String getCurrentFacetString() { String ret = generateFacetPrefix(currentFacets, true); if (StringUtils.isEmpty(ret)) { ret = "-"; } try { return URLEncoder.encode(ret, SearchBean.URL_ENCODING); } catch (UnsupportedEncodingException e) { return ret; } } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void getCurrentFacetString_shouldReturnHyphenIfCurrentFacetsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); String facetString = facets.getCurrentFacetString(); Assert.assertEquals("-", facetString); }
### Question: SearchFacets implements Serializable { String generateFacetFilterQuery(boolean includeRangeFacets) { if (currentFacets.isEmpty()) { return null; } StringBuilder sbQuery = new StringBuilder(); for (FacetItem facetItem : currentFacets) { if (facetItem.isHierarchial()) { continue; } if (facetItem.getField().equals(SolrConstants.DOCSTRCT_SUB)) { continue; } if (!includeRangeFacets && DataManager.getInstance().getConfiguration().getRangeFacetFields().contains(facetItem.getField())) { continue; } if (sbQuery.length() > 0) { sbQuery.append(" AND "); } sbQuery.append(facetItem.getQueryEscapedLink()); logger.trace("Added facet: {}", facetItem.getQueryEscapedLink()); } return sbQuery.toString(); } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void generateFacetFilterQuery_shouldReturnNullIfFacetListIsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertNull(facets.generateFacetFilterQuery(true)); }
### Question: SearchFacets implements Serializable { String generateHierarchicalFacetFilterQuery(int advancedSearchGroupOperator) { if (currentFacets.isEmpty()) { return null; } StringBuilder sbQuery = new StringBuilder(); int count = 0; for (FacetItem facetItem : currentFacets) { if (!facetItem.isHierarchial()) { continue; } if (count > 0) { if (advancedSearchGroupOperator == 1) { sbQuery.append(" OR "); } else { sbQuery.append(" AND "); } } String field = SearchHelper.facetifyField(facetItem.getField()); sbQuery.append('(') .append(field) .append(':') .append("\"" + facetItem.getValue() + "\"") .append(" OR ") .append(field) .append(':') .append(facetItem.getValue()) .append(".*)"); count++; } return sbQuery.toString(); } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void generateHierarchicalFacetFilterQuery_shouldReturnNullIfFacetListIsEmpty() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertNull(facets.generateHierarchicalFacetFilterQuery(1)); }
### Question: SearchFacets implements Serializable { public boolean isHasWrongLanguageCode(String field, String language) { if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (language == null) { throw new IllegalArgumentException("language may not be null"); } if (field.contains(SolrConstants._LANG_) && !field.endsWith(SolrConstants._LANG_ + language.toUpperCase())) { return true; } return false; } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void isHasWrongLanguageCode_shouldReturnTrueIfLanguageCodeDifferent() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertTrue(facets.isHasWrongLanguageCode("MD_TITLE_LANG_DE", "en")); } @Test public void isHasWrongLanguageCode_shouldReturnFalseIfLanguageCodeSame() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertFalse(facets.isHasWrongLanguageCode("MD_TITLE_LANG_DE", "de")); } @Test public void isHasWrongLanguageCode_shouldReturnFalseIfNoLanguageCode() throws Exception { SearchFacets facets = new SearchFacets(); Assert.assertFalse(facets.isHasWrongLanguageCode("MD_TITLE", "en")); }
### Question: SearchFacets implements Serializable { public String updateFacetItem(String field, boolean hierarchical) { updateFacetItem(field, tempValue, currentFacets, hierarchical); return "pretty:search6"; } void resetAvailableFacets(); void resetCurrentFacets(); void resetSliderRange(); List<String> generateFacetFilterQueries(int advancedSearchGroupOperator, boolean includeRangeFacets); FacetItem getCurrentFacetForField(String field); List<FacetItem> getCurrentFacetsForField(String field); boolean isFacetCurrentlyUsed(FacetItem facet); boolean isFacetListSizeSufficient(String field); int getAvailableFacetsListSizeForField(String field); int getCurrentFacetsSizeForField(String field); List<FacetItem> getLimitedFacetListForField(String field); int getDrillDownElementDisplayNumber(String field); void expandDrillDown(String field); void collapseDrillDown(String field); boolean isDisplayDrillDownExpandLink(String field); boolean isDisplayDrillDownCollapseLink(String field); String getCurrentFacetString(); String getCurrentFacetString(boolean urlEncode); @Deprecated String getCurrentHierarchicalFacetString(); @Deprecated String getCurrentCollection(); void setCurrentFacetString(String currentFacetString); @Deprecated void setCurrentHierarchicalFacetString(String currentHierarchicalFacetString); @Deprecated void setCurrentCollection(String currentCollection); String updateFacetItem(String field, boolean hierarchical); static List<String> getHierarchicalFacets(String facetString, List<String> facetFields); static List<String> splitHierarchicalFacet(String facet); String getCurrentMinRangeValue(String field); String getCurrentMaxRangeValue(String field); String getAbsoluteMinRangeValue(String field); String getAbsoluteMaxRangeValue(String field); List<Integer> getValueRange(String field); void resetCurrentFacetString(); String getCurrentFacetStringPrefix(); @Deprecated String getCurrentHierarchicalFacetPrefix(); String removeFacetAction(final String facetQuery, final String ret); boolean isDrillDownExpanded(String field); boolean isDrillDownCollapsed(String field); Map<String, List<FacetItem>> getAllAvailableFacets(); List<String> getConfiguredSubelementFacetFields(); Map<String, List<FacetItem>> getAvailableFacets(); List<FacetItem> getCurrentFacets(); String getTempValue(); void setTempValue(String tempValue); boolean isHasWrongLanguageCode(String field, String language); String getFacetValue(String field); String getFacetDescription(String field); String getFirstHierarchicalFacetValue(); String getFirstHierarchicalFacetDescription(String field); Map<String, String> getLabelMap(); }### Answer: @Test public void updateFacetItem_shouldUpdateFacetItemCorrectly() throws Exception { List<FacetItem> items = new ArrayList<>(2); items.add(new FacetItem("FIELD1:foo", false)); items.add(new FacetItem("FIELD2:bar", false)); SearchFacets.updateFacetItem("FIELD2", "[foo TO bar]", items, false); Assert.assertEquals(2, items.size()); Assert.assertEquals("FIELD2", items.get(1).getField()); Assert.assertEquals("foo", items.get(1).getValue()); Assert.assertEquals("bar", items.get(1).getValue2()); } @Test public void updateFacetItem_shouldAddNewItemCorrectly() throws Exception { List<FacetItem> items = new ArrayList<>(2); items.add(new FacetItem("FIELD1:foo", false)); SearchFacets.updateFacetItem("FIELD2", "bar", items, false); Assert.assertEquals(2, items.size()); Assert.assertEquals("FIELD2", items.get(1).getField()); Assert.assertEquals("bar", items.get(1).getValue()); }
### Question: FacetItem implements Comparable<FacetItem>, Serializable { public String getQueryEscapedLink() { String field = SearchHelper.facetifyField(this.field); String escapedValue = getEscapedValue(value); if (hierarchial) { return new StringBuilder("(").append(field) .append(':') .append(escapedValue) .append(" OR ") .append(field) .append(':') .append(escapedValue) .append(".*)") .toString(); } if (value2 == null) { return new StringBuilder(field).append(':').append(escapedValue).toString(); } String escapedValue2 = getEscapedValue(value2); return new StringBuilder(field).append(":[").append(escapedValue).append(" TO ").append(escapedValue2).append(']').toString(); } FacetItem(boolean hierarchical); FacetItem(String link, boolean hierarchical); FacetItem(String link, String label, boolean hierarchical); private FacetItem(String field, String link, String label, String translatedLabel, long count, boolean hierarchical); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(FacetItem facetItem); static List<FacetItem> generateFilterLinkList(String field, Map<String, Long> values, boolean hierarchical, Locale locale, Map<String, String> labelMap); static List<FacetItem> generateFacetItems(String field, Map<String, Long> values, boolean sort, boolean reverseOrder, boolean hierarchical, Locale locale); String getQueryEscapedLink(); String getEscapedLink(); String getUrlEscapedLink(); String getField(); void setField(String field); String getFullValue(); String getValue(); void setValue(String value); String getValue2(); void setValue2(String value2); String getLink(); void setLink(String link); String getLabel(); FacetItem setLabel(String label); String getTranslatedLabel(); void setTranslatedLabel(String translatedLabel); long getCount(); FacetItem setCount(long count); boolean isHierarchial(); }### Answer: @Test public void getQueryEscapedLink_shouldConstructLinkCorrectly() throws Exception { FacetItem item = new FacetItem("FIELD:value", false); Assert.assertEquals("FIELD:value", item.getQueryEscapedLink()); } @Test public void getQueryEscapedLink_shouldEscapeValuesContainingWhitespaces() throws Exception { FacetItem item = new FacetItem("FIELD:foo bar", false); Assert.assertEquals("FIELD:\"foo\\ bar\"", item.getQueryEscapedLink()); } @Test public void getQueryEscapedLink_shouldConstructHierarchicalLinkCorrectly() throws Exception { FacetItem item = new FacetItem("FIELD:value", true); Assert.assertEquals("(FIELD:value OR FIELD:value.*)", item.getQueryEscapedLink()); } @Test public void getQueryEscapedLink_shouldConstructRangeLinkCorrectly() throws Exception { FacetItem item = new FacetItem("FIELD:[foo TO bar]", false); Assert.assertEquals("FIELD:[foo TO bar]", item.getQueryEscapedLink()); }
### Question: UserTools { public static int deleteSearchesForUser(User owner) throws DAOException { List<Search> searches = DataManager.getInstance().getDao().getSearches(owner); if (searches.isEmpty()) { return 0; } int count = 0; for (Search search : searches) { if (DataManager.getInstance().getDao().deleteSearch(search)) { count++; } } logger.debug("{} saved searches of user {} deleted.", count, owner.getId()); return count; } static boolean deleteUser(User user); static int deleteUserGroupOwnedByUser(User owner); static int deleteBookmarkListsForUser(User owner); static int deleteSearchesForUser(User owner); static void deleteUserPublicContributions(User user); static boolean anonymizeUserPublicContributions(User user); static User checkAndCreateAnonymousUser(); }### Answer: @Test public void deleteSearchesForUser_shouldDeleteAllSearchesOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertFalse(DataManager.getInstance().getDao().getSearches(user).isEmpty()); UserTools.deleteSearchesForUser(user); Assert.assertTrue(DataManager.getInstance().getDao().getSearches(user).isEmpty()); }
### Question: FacetItem implements Comparable<FacetItem>, Serializable { static String getEscapedValue(String value) { if (StringUtils.isEmpty(value)) { return value; } String escapedValue = null; if (value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"' && value.length() > 2) { escapedValue = '"' + ClientUtils.escapeQueryChars(value.substring(1, value.length() - 1)) + '"'; } else { escapedValue = ClientUtils.escapeQueryChars(value); } if (escapedValue.contains(" ") && !escapedValue.startsWith("\"") && !escapedValue.endsWith("\"")) { escapedValue = '"' + escapedValue + '"'; } return escapedValue; } FacetItem(boolean hierarchical); FacetItem(String link, boolean hierarchical); FacetItem(String link, String label, boolean hierarchical); private FacetItem(String field, String link, String label, String translatedLabel, long count, boolean hierarchical); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(FacetItem facetItem); static List<FacetItem> generateFilterLinkList(String field, Map<String, Long> values, boolean hierarchical, Locale locale, Map<String, String> labelMap); static List<FacetItem> generateFacetItems(String field, Map<String, Long> values, boolean sort, boolean reverseOrder, boolean hierarchical, Locale locale); String getQueryEscapedLink(); String getEscapedLink(); String getUrlEscapedLink(); String getField(); void setField(String field); String getFullValue(); String getValue(); void setValue(String value); String getValue2(); void setValue2(String value2); String getLink(); void setLink(String link); String getLabel(); FacetItem setLabel(String label); String getTranslatedLabel(); void setTranslatedLabel(String translatedLabel); long getCount(); FacetItem setCount(long count); boolean isHierarchial(); }### Answer: @Test public void getEscapedValue_shouldEscapeValueCorrectly() throws Exception { Assert.assertEquals("\\(foo\\)", FacetItem.getEscapedValue("(foo)")); } @Test public void getEscapedValue_shouldAddQuotationMarksIfValueContainsSpace() throws Exception { Assert.assertEquals("\"foo\\ bar\"", FacetItem.getEscapedValue("foo bar")); } @Test public void getEscapedValue_shouldPreserveLeadingAndTrailingQuotationMarks() throws Exception { Assert.assertEquals("\"IsWithin\\(foobar\\)\\ disErrPct=0\"", FacetItem.getEscapedValue("\"IsWithin(foobar) disErrPct=0\"")); }
### Question: BrowseElement implements Serializable { static String generateDefaultLabel(StructElement se, Locale locale) { String ret = null; if (locale != null) { String englishTitle = null; String germanTitle = null; String anyTitle = null; for (String key : se.getMetadataFields().keySet()) { if (key.equals(SolrConstants.TITLE + "_LANG_" + locale.getLanguage().toUpperCase())) { ret = se.getMetadataValue(key); break; } else if (key.equals(SolrConstants.TITLE + "_LANG_DE")) { germanTitle = se.getMetadataValue(key); } else if (key.equals(SolrConstants.TITLE + "_LANG_EN")) { englishTitle = se.getMetadataValue(key); } else if (key.matches(SolrConstants.TITLE + "_LANG_[A-Z][A-Z]")) { anyTitle = se.getMetadataValue(key); } } if (StringUtils.isBlank(ret)) { if (StringUtils.isNotBlank(englishTitle)) { ret = englishTitle; } else if (StringUtils.isNotBlank(germanTitle)) { ret = germanTitle; } else { ret = anyTitle; } } } if (StringUtils.isEmpty(ret)) { ret = se.getMetadataValue(SolrConstants.LABEL); if (StringUtils.isEmpty(ret)) { ret = se.getMetadataValue(SolrConstants.TITLE); } } if (StringUtils.isEmpty(ret)) { ret = ViewerResourceBundle.getTranslation(se.getDocStructType(), locale); } return ret; } BrowseElement(String pi, int imageNo, String label, String fulltext, Locale locale, String dataRepository, String url); BrowseElement(StructElement structElement, List<Metadata> metadataList, Locale locale, String fulltext, boolean useThumbnail, Map<String, Set<String>> searchTerms, ThumbnailHandler thumbs); IMetadataValue createMultiLanguageLabel(StructElement structElement); String getLabel(); String getLabel(Locale locale); IMetadataValue getLabelAsMetadataValue(); String getLabelShort(); void setLabelShort(IMetadataValue labelShort); String getDocStructType(); long getIddoc(); String getThumbnailUrl(); String getThumbnailUrl(String width, String height); int getImageNo(); List<StructElementStub> getStructElements(); void setFulltext(String fulltext); String getFulltext(); String getFulltextForHtml(); String getVolumeNo(); void setVolumeNo(String volumeNo); boolean isAnchor(); void setAnchor(boolean anchor); boolean isHasImages(); void setHasImages(boolean hasImages); boolean isShowThumbnail(); void setShowThumbnail(boolean showThumbnail); long getNumVolumes(); void setPi(String pi); String getPi(); String getUrl(); String getSidebarPrevUrl(); String getSidebarNextUrl(); List<Metadata> getMetadataList(); List<Metadata> getMetadataListForLocale(Locale locale); List<Metadata> getMetadataListForCurrentLocale(); void setMetadataList(List<Metadata> metadataList); Set<String> getExistingMetadataFields(); MetadataGroupType getMetadataGroupType(); List<Metadata> getMetadataList(String metadataLabel); List<Metadata> getAdditionalMetadataList(); String getDataRepository(); String getContextObject(); List<String> getRecordLanguages(); void setHasMedia(boolean hasMedia); boolean isHasMedia(); String getOriginalFieldName(); PageType determinePageType(); String getLogId(); DocType getDocType(); }### Answer: @Test public void generateDefaultLabel_shouldTranslateDocstructLabel() throws Exception { BrowseElement be = new BrowseElement("PPN123", 1, null, null, Locale.GERMAN, null, null); StructElement se = new StructElement(); se.setDocStructType("Monograph"); String label = BrowseElement.generateDefaultLabel(se, Locale.GERMAN); Assert.assertEquals("Monografie", label); }
### Question: BrowseElement implements Serializable { public String getFulltextForHtml() { if (fulltextForHtml == null) { if (fulltext != null) { fulltextForHtml = StringTools.stripJS(fulltext).replaceAll("\n", " "); } else { fulltextForHtml = ""; } } return fulltextForHtml; } BrowseElement(String pi, int imageNo, String label, String fulltext, Locale locale, String dataRepository, String url); BrowseElement(StructElement structElement, List<Metadata> metadataList, Locale locale, String fulltext, boolean useThumbnail, Map<String, Set<String>> searchTerms, ThumbnailHandler thumbs); IMetadataValue createMultiLanguageLabel(StructElement structElement); String getLabel(); String getLabel(Locale locale); IMetadataValue getLabelAsMetadataValue(); String getLabelShort(); void setLabelShort(IMetadataValue labelShort); String getDocStructType(); long getIddoc(); String getThumbnailUrl(); String getThumbnailUrl(String width, String height); int getImageNo(); List<StructElementStub> getStructElements(); void setFulltext(String fulltext); String getFulltext(); String getFulltextForHtml(); String getVolumeNo(); void setVolumeNo(String volumeNo); boolean isAnchor(); void setAnchor(boolean anchor); boolean isHasImages(); void setHasImages(boolean hasImages); boolean isShowThumbnail(); void setShowThumbnail(boolean showThumbnail); long getNumVolumes(); void setPi(String pi); String getPi(); String getUrl(); String getSidebarPrevUrl(); String getSidebarNextUrl(); List<Metadata> getMetadataList(); List<Metadata> getMetadataListForLocale(Locale locale); List<Metadata> getMetadataListForCurrentLocale(); void setMetadataList(List<Metadata> metadataList); Set<String> getExistingMetadataFields(); MetadataGroupType getMetadataGroupType(); List<Metadata> getMetadataList(String metadataLabel); List<Metadata> getAdditionalMetadataList(); String getDataRepository(); String getContextObject(); List<String> getRecordLanguages(); void setHasMedia(boolean hasMedia); boolean isHasMedia(); String getOriginalFieldName(); PageType determinePageType(); String getLogId(); DocType getDocType(); }### Answer: @Test public void getFulltextForHtml_shouldRemoveAnyLineBreaks() throws Exception { BrowseElement be = new BrowseElement(null, 1, "FROM FOO TO BAR", "foo\nbar", Locale.ENGLISH, null, null); Assert.assertEquals("foo bar", be.getFulltextForHtml()); } @Test public void getFulltextForHtml_shouldRemoveAnyJS() throws Exception { BrowseElement be = new BrowseElement(null, 1, "FROM FOO TO BAR", "foo <script type=\"javascript\">\nfunction f {\n alert();\n}\n</script> bar", Locale.ENGLISH, null, null); Assert.assertEquals("foo bar", be.getFulltextForHtml()); }
### Question: UserTools { public static int deleteUserGroupOwnedByUser(User owner) throws DAOException { List<UserGroup> userGroups = owner.getUserGroupOwnerships(); if (userGroups.isEmpty()) { return 0; } int count = 0; for (UserGroup userGroup : userGroups) { if (!userGroup.getMemberships().isEmpty()) { for (UserRole userRole : userGroup.getMemberships()) { DataManager.getInstance().getDao().deleteUserRole(userRole); } } if (DataManager.getInstance().getDao().deleteUserGroup(userGroup)) { logger.debug("User group '{}' belonging to user {} deleted", userGroup.getName(), owner.getId()); count++; } } return count; } static boolean deleteUser(User user); static int deleteUserGroupOwnedByUser(User owner); static int deleteBookmarkListsForUser(User owner); static int deleteSearchesForUser(User owner); static void deleteUserPublicContributions(User user); static boolean anonymizeUserPublicContributions(User user); static User checkAndCreateAnonymousUser(); }### Answer: @Test public void deleteUserGroupOwnedByUser_shouldDeleteAllUserGroupsOwnedByUser() throws Exception { User user = DataManager.getInstance().getDao().getUser(1); Assert.assertNotNull(user); Assert.assertNotNull(DataManager.getInstance().getDao().getUserGroup(1)); UserTools.deleteUserGroupOwnedByUser(user); Assert.assertNull(DataManager.getInstance().getDao().getUserGroup(1)); }
### Question: UserTools { public static void deleteUserPublicContributions(User user) throws DAOException { if (user == null) { return; } int comments = DataManager.getInstance().getDao().deleteComments(null, user); logger.debug("{} comment(s) of user {} deleted.", comments, user.getId()); int statistics = DataManager.getInstance().getDao().deleteCampaignStatisticsForUser(user); logger.debug("Deleted user from {} campaign statistics statistic(s).", statistics); for (IModule module : DataManager.getInstance().getModules()) { int count = module.deleteUserContributions(user); if (count > 0) { logger.debug("Deleted {} user contribution(s) via the '{}' module.", count, module.getName()); } } } static boolean deleteUser(User user); static int deleteUserGroupOwnedByUser(User owner); static int deleteBookmarkListsForUser(User owner); static int deleteSearchesForUser(User owner); static void deleteUserPublicContributions(User user); static boolean anonymizeUserPublicContributions(User user); static User checkAndCreateAnonymousUser(); }### Answer: @Test public void deleteUserPublicContributions_shouldDeleteAllUserPublicContentCorrectly() throws Exception { User user = DataManager.getInstance().getDao().getUser(2); Assert.assertNotNull(user); UserTools.deleteUserPublicContributions(user); Assert.assertNull(DataManager.getInstance().getDao().getComment(2)); List<CampaignRecordStatistic> statistics = DataManager.getInstance().getDao().getCampaignStatisticsForRecord("PI_1", null); Assert.assertEquals(1, statistics.size()); Assert.assertTrue(statistics.get(0).getReviewers().isEmpty()); Assert.assertFalse(statistics.get(0).getReviewers().contains(user)); }
### Question: UserTools { public static boolean anonymizeUserPublicContributions(User user) throws DAOException { User anon = UserTools.checkAndCreateAnonymousUser(); if (anon == null) { logger.error("Anonymous user could not be found"); return false; } int comments = DataManager.getInstance().getDao().changeCommentsOwner(user, anon); logger.debug("{} comment(s) of user {} anonymized.", comments, user.getId()); int statistics = DataManager.getInstance().getDao().changeCampaignStatisticContributors(user, anon); logger.debug("Anonymized user in {} campaign statistic(s).", statistics); for (IModule module : DataManager.getInstance().getModules()) { int count = module.moveUserContributions(user, anon); if (count > 0) { logger.debug("Anonymized {} user contribution(s) via the '{}' module.", count, module.getName()); } } return true; } static boolean deleteUser(User user); static int deleteUserGroupOwnedByUser(User owner); static int deleteBookmarkListsForUser(User owner); static int deleteSearchesForUser(User owner); static void deleteUserPublicContributions(User user); static boolean anonymizeUserPublicContributions(User user); static User checkAndCreateAnonymousUser(); }### Answer: @Test public void anonymizeUserPublicContributions_shouldAnonymizeAllUserPublicContentCorrectly() throws Exception { User user = DataManager.getInstance().getDao().getUser(2); Assert.assertNotNull(user); Assert.assertTrue(UserTools.anonymizeUserPublicContributions(user)); Comment comment = DataManager.getInstance().getDao().getComment(2); Assert.assertNotNull(comment); Assert.assertNotEquals(user, comment.getOwner()); List<CampaignRecordStatistic> statistics = DataManager.getInstance().getDao().getCampaignStatisticsForRecord("PI_1", null); Assert.assertEquals(1, statistics.size()); Assert.assertEquals(1, statistics.get(0).getReviewers().size()); Assert.assertFalse(statistics.get(0).getReviewers().contains(user)); }
### Question: UserGroup implements ILicensee, Serializable { public long getMemberCount() throws DAOException { return DataManager.getInstance().getDao().getUserRoleCount(this, null, null); } @Override int hashCode(); @Override boolean equals(Object obj); boolean addMember(User user, Role role); boolean changeMemberRole(User user, Role role); boolean removeMember(User user); @Override boolean hasLicense(String licenseName, String privilegeName, String pi); boolean hasUserPrivilege(String privilegeName); @Override boolean addLicense(License license); @Override boolean removeLicense(License license); Long getId(); void setId(Long id); @Override String getName(); void setName(String name); String getDescription(); void setDescription(String description); User getOwner(); void setOwner(User owner); boolean isActive(); void setActive(boolean active); @Override List<License> getLicenses(); void setLicenses(List<License> licenses); List<License> getLicenses(boolean core); boolean isHasMembers(); long getMemberCount(); List<UserRole> getMemberships(); Set<User> getMembers(); Set<User> getMembersAndOwner(); @Override String toString(); }### Answer: @Test public void getMemberCount_shouldCountCorrectly() throws Exception { UserGroup ug = DataManager.getInstance().getDao().getUserGroup(1); Assert.assertNotNull(ug); Assert.assertEquals(1, ug.getMemberCount()); }
### Question: UserGroup implements ILicensee, Serializable { public Set<User> getMembersAndOwner() throws DAOException { Set<User> ret = new HashSet<>(getMembers()); ret.add(getOwner()); return ret; } @Override int hashCode(); @Override boolean equals(Object obj); boolean addMember(User user, Role role); boolean changeMemberRole(User user, Role role); boolean removeMember(User user); @Override boolean hasLicense(String licenseName, String privilegeName, String pi); boolean hasUserPrivilege(String privilegeName); @Override boolean addLicense(License license); @Override boolean removeLicense(License license); Long getId(); void setId(Long id); @Override String getName(); void setName(String name); String getDescription(); void setDescription(String description); User getOwner(); void setOwner(User owner); boolean isActive(); void setActive(boolean active); @Override List<License> getLicenses(); void setLicenses(List<License> licenses); List<License> getLicenses(boolean core); boolean isHasMembers(); long getMemberCount(); List<UserRole> getMemberships(); Set<User> getMembers(); Set<User> getMembersAndOwner(); @Override String toString(); }### Answer: @Test public void getMembersAndOwner_shouldReturnAllMembersAndOwner() throws Exception { UserGroup ug = DataManager.getInstance().getDao().getUserGroup(1); Assert.assertNotNull(ug); Assert.assertEquals(2, ug.getMembersAndOwner().size()); }
### Question: BibliothecaAuthenticationRequest extends UserPasswordAuthenticationRequest { static String normalizeUsername(String username) { if (username == null || username.length() == 11) { return username; } if (username.length() < 11) { StringBuilder sb = new StringBuilder(11); for (int i = username.length(); i < 11; ++i) { sb.append('0'); } sb.append(username); return sb.toString(); } return username; } BibliothecaAuthenticationRequest(String username, String password); @Override String toString(); }### Answer: @Test public void normalizeUsername_shouldNormalizeValueCorrectly() throws Exception { Assert.assertEquals("00001234567", BibliothecaAuthenticationRequest.normalizeUsername("1234567")); }
### Question: BrowseTermComparator implements Comparator<BrowseTerm>, Serializable { public static String normalizeString(String s, String ignoreChars) { if (s == null) { return null; } if (StringUtils.isNotEmpty(ignoreChars)) { while (s.length() > 1 && ignoreChars.contains(s.substring(0, 1))) { s = s.substring(1); } } else { if (s.length() > 1 && !StringUtils.isAlphanumeric(s.substring(0, 1))) { s = s.substring(1); } } return s; } BrowseTermComparator(Locale locale); @Override int compare(BrowseTerm o1, BrowseTerm o2); static String normalizeString(String s, String ignoreChars); }### Answer: @Test public void normalizeString_shouldUseIgnoreCharsIfProvided() throws Exception { Assert.assertEquals("#.foo", BrowseTermComparator.normalizeString("[.]#.foo", ".[]")); } @Test public void normalizeString_shouldRemoveFirstCharIfNonAlphanumIfIgnoreCharsNotProvided() throws Exception { Assert.assertEquals(".]#.foo", BrowseTermComparator.normalizeString("[.]#.foo", null)); }
### Question: DownloadJob implements Serializable { public static String generateDownloadJobId(String... criteria) { StringBuilder sbCriteria = new StringBuilder(criteria.length * 10); for (String criterion : criteria) { if (criterion != null) { sbCriteria.append(criterion); } } return StringTools.generateMD5(sbCriteria.toString()); } abstract void generateDownloadIdentifier(); static String generateDownloadJobId(String... criteria); static DownloadJob checkDownload(String type, final String email, String pi, String logId, String downloadIdentifier, long ttl); static boolean ocrFolderExists(String pi); static int cleanupExpiredDownloads(); boolean isExpired(); @JsonIgnore abstract String getMimeType(); @JsonIgnore abstract String getFileExtension(); @JsonIgnore abstract String getDisplayName(); abstract long getSize(); abstract int getQueuePosition(); @JsonIgnore Path getFile(); boolean notifyObservers(JobStatus status, String message); File getDownloadFile(String pi, final String logId, String type); Long getId(); void setId(Long id); String getType(); String getPi(); void setPi(String pi); String getLogId(); void setLogId(String logId); String getIdentifier(); void setIdentifier(String identifier); @JsonFormat(pattern = DATETIME_FORMAT) Date getLastRequested(); void setLastRequested(Date lastRequested); @JsonIgnore long getTtl(); String getTimeToLive(); void setTtl(long ttl); JobStatus getStatus(); void setStatus(JobStatus status); String getDescription(); void setDescription(String description); @JsonIgnore List<String> getObservers(); void setObservers(List<String> observers); void resetObservers(); String getMessage(); void setMessage(String message); static Response postJobRequest(String url, AbstractTaskManagerRequest body); String getJobStatus(String identifier); void updateStatus(); @Override String toString(); }### Answer: @Test public void generateDownloadJobId_shouldGenerateSameIdFromSameCriteria() throws Exception { String hash = "78acb5991aaf0fee0329b673e985ce82"; String crit1 = "PPN123456789"; String crit2 = "LOG_0000"; Assert.assertEquals(hash, DownloadJob.generateDownloadJobId(crit1, crit2)); Assert.assertEquals(hash, DownloadJob.generateDownloadJobId(crit1, crit2)); Assert.assertEquals(hash, DownloadJob.generateDownloadJobId(crit1, crit2)); }
### Question: LitteraProvider extends HttpAuthenticationProvider { @Override public CompletableFuture<LoginResult> login(String loginName, String password) throws AuthenticationProviderException { try { LitteraAuthenticationResponse response = get(new URI(getUrl()), loginName, password); Optional<User> user = getUser(loginName, response); LoginResult result = new LoginResult(BeanUtils.getRequest(), BeanUtils.getResponse(), user, !response.isAuthenticationSuccessful()); return CompletableFuture.completedFuture(result); } catch (URISyntaxException e) { throw new AuthenticationProviderException("Cannot resolve authentication api url " + getUrl(), e); } catch (IOException e) { throw new AuthenticationProviderException("Error requesting authorisation for user " + loginName, e); } } LitteraProvider(String name, String label, String url, String image, long timeoutMillis); @Override void logout(); @Override CompletableFuture<LoginResult> login(String loginName, String password); @Override boolean allowsPasswordChange(); @Override boolean allowsNicknameChange(); @Override boolean allowsEmailChange(); }### Answer: @Test public void testLogin() throws AuthenticationProviderException, InterruptedException, ExecutionException { Assert.assertFalse(provider.login(user_id, user_pw).get().isRefused()); Assert.assertTrue(provider.login(user_id_invalid, user_pw).get().isRefused()); Assert.assertTrue(provider.login(user_id, user_pw_invalid).get().isRefused()); }
### Question: CrowdsourcingBean implements Serializable { public long getCampaignCount(CampaignVisibility visibility) throws DAOException { Map<String, String> filters = visibility != null ? Collections.singletonMap("visibility", visibility.name()) : null; return DataManager.getInstance().getDao().getCampaignCount(filters); } @PostConstruct void init(); long getCampaignCount(CampaignVisibility visibility); String filterCampaignsAction(CampaignVisibility visibility); static List<Locale> getAllLocales(); String createNewCampaignAction(); String editCampaignAction(Campaign campaign); String deleteCampaignAction(Campaign campaign); String addNewQuestionAction(); String removeQuestionAction(Question question); String resetDurationAction(); List<Campaign> getAllCampaigns(); List<Campaign> getAllCampaigns(CampaignVisibility visibility); List<Campaign> getAllowedCampaigns(User user); boolean isAllowed(User user, Campaign campaign); void saveSelectedCampaign(); String getCampaignsRootUrl(); TableDataProvider<Campaign> getLazyModelCampaigns(); TableDataProvider<PersistentAnnotation> getLazyModelAnnotations(); String deleteAnnotationAction(PersistentAnnotation annotation); Campaign getSelectedCampaign(); void setSelectedCampaign(Campaign selectedCampaign); boolean isEditMode(); void setEditMode(boolean editMode); String getSelectedCampaignId(); void setSelectedCampaignId(String id); Campaign getTargetCampaign(); void setTargetCampaign(Campaign targetCampaign); String getTargetCampaignId(); void setTargetCampaignId(String id); void setRandomIdentifierForAnnotation(); void setRandomIdentifierForReview(); void resetTarget(); String forwardToAnnotationTarget(); String forwardToReviewTarget(); String getTargetIdentifier(); String getTargetIdentifierForUrl(); void setTargetIdentifierForUrl(String pi); void setTargetIdentifier(String targetIdentifier); String forwardToCrowdsourcingAnnotation(Campaign campaign); String forwardToCrowdsourcingReview(Campaign campaign); String forwardToCrowdsourcingAnnotation(Campaign campaign, String pi); String forwardToCrowdsourcingReview(Campaign campaign, String pi); String getRandomItemUrl(Campaign campaign, CampaignRecordStatus status); CampaignRecordStatus getTargetRecordStatus(); String handleInvalidTarget(); List<Campaign> getActiveCampaignsForRecord(String pi); void updateActiveCampaigns(); }### Answer: @Test public void testGetCampaignCount() throws DAOException { long numPublic = bean.getCampaignCount(CampaignVisibility.PUBLIC); long numPrivate = bean.getCampaignCount(CampaignVisibility.PRIVATE); long numRestricted = bean.getCampaignCount(CampaignVisibility.RESTRICTED); Assert.assertEquals(1, numPublic); Assert.assertEquals(1, numPrivate); Assert.assertEquals(0, numRestricted); }
### Question: CrowdsourcingBean implements Serializable { public List<Campaign> getAllCampaigns() throws DAOException { List<Campaign> pages = DataManager.getInstance().getDao().getAllCampaigns(); return pages; } @PostConstruct void init(); long getCampaignCount(CampaignVisibility visibility); String filterCampaignsAction(CampaignVisibility visibility); static List<Locale> getAllLocales(); String createNewCampaignAction(); String editCampaignAction(Campaign campaign); String deleteCampaignAction(Campaign campaign); String addNewQuestionAction(); String removeQuestionAction(Question question); String resetDurationAction(); List<Campaign> getAllCampaigns(); List<Campaign> getAllCampaigns(CampaignVisibility visibility); List<Campaign> getAllowedCampaigns(User user); boolean isAllowed(User user, Campaign campaign); void saveSelectedCampaign(); String getCampaignsRootUrl(); TableDataProvider<Campaign> getLazyModelCampaigns(); TableDataProvider<PersistentAnnotation> getLazyModelAnnotations(); String deleteAnnotationAction(PersistentAnnotation annotation); Campaign getSelectedCampaign(); void setSelectedCampaign(Campaign selectedCampaign); boolean isEditMode(); void setEditMode(boolean editMode); String getSelectedCampaignId(); void setSelectedCampaignId(String id); Campaign getTargetCampaign(); void setTargetCampaign(Campaign targetCampaign); String getTargetCampaignId(); void setTargetCampaignId(String id); void setRandomIdentifierForAnnotation(); void setRandomIdentifierForReview(); void resetTarget(); String forwardToAnnotationTarget(); String forwardToReviewTarget(); String getTargetIdentifier(); String getTargetIdentifierForUrl(); void setTargetIdentifierForUrl(String pi); void setTargetIdentifier(String targetIdentifier); String forwardToCrowdsourcingAnnotation(Campaign campaign); String forwardToCrowdsourcingReview(Campaign campaign); String forwardToCrowdsourcingAnnotation(Campaign campaign, String pi); String forwardToCrowdsourcingReview(Campaign campaign, String pi); String getRandomItemUrl(Campaign campaign, CampaignRecordStatus status); CampaignRecordStatus getTargetRecordStatus(); String handleInvalidTarget(); List<Campaign> getActiveCampaignsForRecord(String pi); void updateActiveCampaigns(); }### Answer: @Test public void testGetAllCampaigns() throws DAOException { List<Campaign> campaigns = bean.getAllCampaigns(); Assert.assertEquals(2, campaigns.size()); }
### Question: CrowdsourcingBean implements Serializable { public void saveSelectedCampaign() throws DAOException, PresentationException, IndexUnreachableException { logger.trace("saveSelectedCampaign"); try { if (userBean == null || !userBean.getUser().isSuperuser()) { return; } if (selectedCampaign == null) { return; } boolean success = false; Date now = new Date(); if (selectedCampaign.getDateCreated() == null) { selectedCampaign.setDateCreated(now); } selectedCampaign.setDateUpdated(now); if (selectedCampaign.getId() != null) { success = DataManager.getInstance().getDao().updateCampaign(selectedCampaign); } else { success = DataManager.getInstance().getDao().addCampaign(selectedCampaign); } if (success) { selectedCampaign.setDirty(false); Messages.info("admin__crowdsourcing_campaign_save_success"); setSelectedCampaign(selectedCampaign); lazyModelCampaigns.update(); updateActiveCampaigns(); } else { Messages.error("admin__crowdsourcing_campaign_save_failure"); } } finally { } } @PostConstruct void init(); long getCampaignCount(CampaignVisibility visibility); String filterCampaignsAction(CampaignVisibility visibility); static List<Locale> getAllLocales(); String createNewCampaignAction(); String editCampaignAction(Campaign campaign); String deleteCampaignAction(Campaign campaign); String addNewQuestionAction(); String removeQuestionAction(Question question); String resetDurationAction(); List<Campaign> getAllCampaigns(); List<Campaign> getAllCampaigns(CampaignVisibility visibility); List<Campaign> getAllowedCampaigns(User user); boolean isAllowed(User user, Campaign campaign); void saveSelectedCampaign(); String getCampaignsRootUrl(); TableDataProvider<Campaign> getLazyModelCampaigns(); TableDataProvider<PersistentAnnotation> getLazyModelAnnotations(); String deleteAnnotationAction(PersistentAnnotation annotation); Campaign getSelectedCampaign(); void setSelectedCampaign(Campaign selectedCampaign); boolean isEditMode(); void setEditMode(boolean editMode); String getSelectedCampaignId(); void setSelectedCampaignId(String id); Campaign getTargetCampaign(); void setTargetCampaign(Campaign targetCampaign); String getTargetCampaignId(); void setTargetCampaignId(String id); void setRandomIdentifierForAnnotation(); void setRandomIdentifierForReview(); void resetTarget(); String forwardToAnnotationTarget(); String forwardToReviewTarget(); String getTargetIdentifier(); String getTargetIdentifierForUrl(); void setTargetIdentifierForUrl(String pi); void setTargetIdentifier(String targetIdentifier); String forwardToCrowdsourcingAnnotation(Campaign campaign); String forwardToCrowdsourcingReview(Campaign campaign); String forwardToCrowdsourcingAnnotation(Campaign campaign, String pi); String forwardToCrowdsourcingReview(Campaign campaign, String pi); String getRandomItemUrl(Campaign campaign, CampaignRecordStatus status); CampaignRecordStatus getTargetRecordStatus(); String handleInvalidTarget(); List<Campaign> getActiveCampaignsForRecord(String pi); void updateActiveCampaigns(); }### Answer: @Test public void testSaveSelectedCampaign() throws DAOException, PresentationException, IndexUnreachableException { bean.setSelectedCampaignId("1"); Assert.assertNotNull(bean.getSelectedCampaign()); Date created = new Date(); bean.getSelectedCampaign().setDateCreated(created); Assert.assertEquals("Date created does not match after setting", created, bean.getSelectedCampaign().getDateCreated()); bean.saveSelectedCampaign(); bean.setSelectedCampaignId("1"); Assert.assertEquals("Date created does not match in database", created, bean.getSelectedCampaign().getDateCreated()); }
### Question: LocalAuthenticationProvider implements IAuthenticationProvider { @Override public CompletableFuture<LoginResult> login(String email, String password) throws AuthenticationProviderException { HttpServletRequest request = BeanUtils.getRequest(); HttpServletResponse response = BeanUtils.getResponse(); if (StringUtils.isNotEmpty(email)) { try { User user = DataManager.getInstance().getDao().getUserByEmail(email); boolean refused = true; if (user != null && StringUtils.isNotBlank(password) && user.getPasswordHash() != null && bcrypt.checkpw(password, user.getPasswordHash())) { refused = false; } return CompletableFuture.completedFuture(new LoginResult(request, response, Optional.ofNullable(user), refused)); } catch (DAOException e) { throw new AuthenticationProviderException(e); } } return CompletableFuture.completedFuture(new LoginResult(request, response, Optional.empty(), true)); } LocalAuthenticationProvider(String name); @Override CompletableFuture<LoginResult> login(String email, String password); @Override void logout(); @Override boolean allowsPasswordChange(); @Override String getName(); @Override String getType(); @Override boolean allowsNicknameChange(); @Override boolean allowsEmailChange(); @Override List<String> getAddUserToGroups(); @Override void setAddUserToGroups(List<String> addUserToGroups); static final String TYPE_LOCAL; }### Answer: @Test public void testLogin_valid() throws AuthenticationProviderException, InterruptedException, ExecutionException { CompletableFuture<LoginResult> future = provider.login(userActive_email, userActive_pwHash); Assert.assertTrue(future.get().getUser().isPresent()); Assert.assertTrue(future.get().getUser().get().isActive()); Assert.assertFalse(future.get().getUser().get().isSuspended()); } @Test public void testLogin_invalid() throws AuthenticationProviderException, InterruptedException, ExecutionException { CompletableFuture<LoginResult> future = provider.login(userActive_email, userSuspended_pwHash); Assert.assertTrue(future.get().getUser().isPresent()); Assert.assertTrue(future.get().isRefused()); } @Test public void testLogin_unknown() throws AuthenticationProviderException, InterruptedException, ExecutionException { CompletableFuture<LoginResult> future = provider.login(userActive_email + "test", userActive_pwHash); Assert.assertFalse(future.get().getUser().isPresent()); } @Test public void testLogin_suspended() throws AuthenticationProviderException, InterruptedException, ExecutionException { CompletableFuture<LoginResult> future = provider.login(userSuspended_email, userSuspended_pwHash); Assert.assertTrue(future.get().getUser().isPresent()); Assert.assertTrue(future.get().getUser().get().isSuspended()); }
### Question: ActiveDocumentBean implements Serializable { public void setPersistentIdentifier(String persistentIdentifier) throws PresentationException, RecordNotFoundException, IndexUnreachableException { synchronized (this) { logger.trace("setPersistentIdentifier: {}", persistentIdentifier); lastReceivedIdentifier = persistentIdentifier; if (!PIValidator.validatePi(persistentIdentifier)) { logger.warn("Invalid identifier '{}'.", persistentIdentifier); reset(); return; } if (!"-".equals(persistentIdentifier) && (viewManager == null || !persistentIdentifier.equals(viewManager.getPi()))) { long id = DataManager.getInstance().getSearchIndex().getIddocFromIdentifier(persistentIdentifier); if (id > 0) { if (topDocumentIddoc != id) { topDocumentIddoc = id; logger.trace("IDDOC found for {}: {}", persistentIdentifier, id); } } else { logger.warn("No IDDOC for identifier '{}' found.", persistentIdentifier); reset(); return; } } } } ActiveDocumentBean(); void setNavigationHelper(NavigationHelper navigationHelper); void setCmsBean(CmsBean cmsBean); void setSearchBean(SearchBean searchBean); void setBookshelfBean(BookmarkBean bookshelfBean); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); void reset(); ViewManager getViewManager(); String reload(String pi); void update(); String open(); String openFulltext(); BrowseElement getPrevHit(); BrowseElement getNextHit(); long getActiveDocumentIddoc(); StructElement getCurrentElement(); void setImageToShow(int imageToShow); int getImageToShow(); List<Metadata> getTitleBarMetadata(); void setLogid(String logid); String getLogid(); boolean isAnchor(); void setAnchor(boolean anchor); boolean isVolume(); boolean isGroup(); String getAction(); void setAction(String action); void setPersistentIdentifier(String persistentIdentifier); String getPersistentIdentifier(); String getThumbPart(); String getLogPart(); String getPageUrl(String pageType, int page); String getPageUrl(int page); String getPageUrl(); String getPageUrl(String pageType); String getFirstPageUrl(); String getLastPageUrl(); String getPreviousPageUrl(int step); String getNextPageUrl(int step); String getPreviousPageUrl(); String getNextPageUrl(); String getImageUrl(); String getFullscreenImageUrl(); String getReadingModeUrl(); String getFulltextUrl(); String getMetadataUrl(); StructElement getTopDocument(); void setChildrenVisible(TOCElement element); void setChildrenInvisible(TOCElement element); String calculateSidebarToc(); TOC getToc(); int getTocCurrentPage(); void setTocCurrentPage(int tocCurrentPage); String getTitleBarLabel(Locale locale); String getTitleBarLabel(); String getTitleBarLabel(String language); String getLabelForJS(); int getImageContainerWidth(); int getNumberOfImages(); long getTopDocumentIddoc(); boolean isRecordLoaded(); boolean hasAnchor(); String reIndexRecordAction(); String deleteRecordAction(boolean keepTraceDocument); int getCurrentThumbnailPage(); void setCurrentThumbnailPage(int currentThumbnailPage); boolean isHasLanguages(); List<String> getRecordLanguages(); void setRecordLanguages(List<String> recordLanguages); String getSelectedRecordLanguage(); void setSelectedRecordLanguage(String selectedRecordLanguage); boolean isAccessPermissionEpub(); boolean isAccessPermissionPdf(); void downloadTOCAction(); List<SearchHit> getRelatedItems(String identifierField); String getRelatedItemsQueryString(String identifierField); String getRelativeUrlTags(); void resetAccess(); Boolean getDeleteRecordKeepTrace(); void setDeleteRecordKeepTrace(Boolean deleteRecordKeepTrace); CMSSidebarElement getMapWidget(); }### Answer: @Test public void setPersistentIdentifier_shouldDetermineCurrentElementIddocCorrectly() throws Exception { ActiveDocumentBean adb = new ActiveDocumentBean(); adb.setPersistentIdentifier(PI_KLEIUNIV); Assert.assertEquals(iddocKleiuniv, adb.topDocumentIddoc); }
### Question: SitelinkBean implements Serializable { public List<String> getAvailableValuesForField(String field, String filterQuery) throws PresentationException, IndexUnreachableException { if (field == null) { throw new IllegalArgumentException("field may not be null"); } if (filterQuery == null) { throw new IllegalArgumentException("filterQuery may not be null"); } filterQuery = SearchHelper.buildFinalQuery(filterQuery, false); QueryResponse qr = DataManager.getInstance().getSearchIndex().searchFacetsAndStatistics(filterQuery, null, Collections.singletonList(field), 1, false); if (qr != null) { FacetField facet = qr.getFacetField(field); if (facet != null) { List<String> ret = new ArrayList<>(facet.getValueCount()); for (Count count : facet.getValues()) { if (count.getName().charAt(0) != 0x01) { ret.add(count.getName()); } } return ret; } } return Collections.emptyList(); } List<String> getAvailableValues(); List<String> getAvailableValuesForField(String field, String filterQuery); String searchAction(); String resetAction(); String getValue(); void setValue(String value); List<StringPair> getHits(); }### Answer: @Test public void getAvailableValuesForField_shouldReturnAllExistingValuesForTheGivenField() throws Exception { SitelinkBean sb = new SitelinkBean(); List<String> values = sb.getAvailableValuesForField("MD_YEARPUBLISH", SolrConstants.ISWORK + ":true"); Assert.assertFalse(values.isEmpty()); }
### Question: BeanUtils { public static String escapeCriticalUrlChracters(String value) { return escapeCriticalUrlChracters(value, false); } static HttpServletRequest getRequest(); static HttpServletRequest getRequest(FacesContext context); static HttpSession getSession(); static String getServletPathWithHostAsUrlFromJsfContext(); static boolean hasJsfContext(); static String getServletImagesPathFromRequest(HttpServletRequest request, String theme); static ServletContext getServletContext(); static Locale getLocale(); static Locale getDefaultLocale(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Object getBeanByName(String name, Class clazz); static NavigationHelper getNavigationHelper(); static ActiveDocumentBean getActiveDocumentBean(); static SearchBean getSearchBean(); static BookmarkBean getBookmarkBean(); static CreateRecordBean getCreateRecordBean(); static CmsCollectionsBean getCMSCollectionsBean(); static MetadataBean getMetadataBean(); static CmsBean getCmsBean(); static CmsMediaBean getCmsMediaBean(); static CalendarBean getCalendarBean(); static UserBean getUserBean(); static ImageDeliveryBean getImageDeliveryBean(); static BrowseBean getBrowseBean(); static UserBean getUserBeanFromRequest(HttpServletRequest request); static User getUserFromRequest(HttpServletRequest request); static String escapeCriticalUrlChracters(String value); static String escapeCriticalUrlChracters(String value, boolean escapePercentCharacters); static String unescapeCriticalUrlChracters(String value); static HttpServletResponse getResponse(); static Object getManagedBeanValue(String expr); static final String SLASH_REPLACEMENT; static final String BACKSLASH_REPLACEMENT; static final String PIPE_REPLACEMENT; static final String QUESTION_MARK_REPLACEMENT; static final String PERCENT_REPLACEMENT; }### Answer: @Test public void escapeCriticalUrlChracters_shouldReplaceCharactersCorrectly() throws Exception { Assert.assertEquals("AU002FU005CU007CU003FZ", BeanUtils.escapeCriticalUrlChracters("A/\\|?Z")); Assert.assertEquals("U007C", BeanUtils.escapeCriticalUrlChracters("%7C")); }
### Question: BeanUtils { public static String unescapeCriticalUrlChracters(String value) { if (value == null) { throw new IllegalArgumentException("value may not be null"); } return value.replace(SLASH_REPLACEMENT, "/") .replace(BACKSLASH_REPLACEMENT, "\\") .replace(PIPE_REPLACEMENT, "|") .replace(QUESTION_MARK_REPLACEMENT, "?") .replace(PERCENT_REPLACEMENT, "%"); } static HttpServletRequest getRequest(); static HttpServletRequest getRequest(FacesContext context); static HttpSession getSession(); static String getServletPathWithHostAsUrlFromJsfContext(); static boolean hasJsfContext(); static String getServletImagesPathFromRequest(HttpServletRequest request, String theme); static ServletContext getServletContext(); static Locale getLocale(); static Locale getDefaultLocale(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Object getBeanByName(String name, Class clazz); static NavigationHelper getNavigationHelper(); static ActiveDocumentBean getActiveDocumentBean(); static SearchBean getSearchBean(); static BookmarkBean getBookmarkBean(); static CreateRecordBean getCreateRecordBean(); static CmsCollectionsBean getCMSCollectionsBean(); static MetadataBean getMetadataBean(); static CmsBean getCmsBean(); static CmsMediaBean getCmsMediaBean(); static CalendarBean getCalendarBean(); static UserBean getUserBean(); static ImageDeliveryBean getImageDeliveryBean(); static BrowseBean getBrowseBean(); static UserBean getUserBeanFromRequest(HttpServletRequest request); static User getUserFromRequest(HttpServletRequest request); static String escapeCriticalUrlChracters(String value); static String escapeCriticalUrlChracters(String value, boolean escapePercentCharacters); static String unescapeCriticalUrlChracters(String value); static HttpServletResponse getResponse(); static Object getManagedBeanValue(String expr); static final String SLASH_REPLACEMENT; static final String BACKSLASH_REPLACEMENT; static final String PIPE_REPLACEMENT; static final String QUESTION_MARK_REPLACEMENT; static final String PERCENT_REPLACEMENT; }### Answer: @Test public void unescapeCriticalUrlChracters_shouldReplaceCharactersCorrectly() throws Exception { Assert.assertEquals("A/\\|?Z", BeanUtils.unescapeCriticalUrlChracters("AU002FU005CU007CU003FZ")); }
### Question: CmsMediaBean implements Serializable { public List<CMSCategory> getAllMediaCategories() throws DAOException { return DataManager.getInstance().getDao().getAllCategories(); } CmsMediaBean(); void resetData(); CMSMediaItem createMediaItem(); List<CMSPage> getMediaOwnerPages(CMSMediaItem item); void deleteMedia(CMSMediaItem item); List<CMSMediaItem> getAllMedia(); TableDataProvider<CategorizableTranslatedSelectable<CMSMediaItem>> getDataProvider(); List<CategorizableTranslatedSelectable<CMSMediaItem>> getMediaItems(); void reloadMediaList(); void reloadMediaList(boolean resetCurrentPage); void deleteSelectedItems(); void saveSelectedItems(); static String getMediaUrl(CMSMediaItem item); static String getMediaUrl(CMSMediaItem item, String width, String height); static String getMediaFileAsString(CMSMediaItem item); static String getMediaPreviewUrl(CMSMediaItem item); boolean isImage(CMSMediaItem item); boolean isText(CMSMediaItem item); void saveSelectedMediaItem(); void saveMedia(CMSMediaItem media, List<Selectable<CMSCategory>> categories); void saveMedia(CMSMediaItem media); static String getFileName(Part filePart); void setSelectedTag(String selectedTag); String getSelectedTag(); List<CMSCategory> getAllMediaCategories(); Collection<CMSMediaItem.DisplaySize> getMediaItemDisplaySizes(); static String getImageFilter(); static String getDocumentFilter(); String getFilter(); void setFilter(String filter); String getFilenameFilter(); void setFilenameFilter(String filter); void setSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); void toggleSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); TranslatedSelectable<CMSMediaItem> getSelectedMediaItem(); void setAllSelected(boolean allSelected); boolean isAllSelected(); boolean needsPaginator(); }### Answer: @Test public void testGetAllMediaCategories() throws DAOException { List<CMSCategory> tags = bean.getAllMediaCategories(); Assert.assertEquals(7, tags.size()); }
### Question: CmsMediaBean implements Serializable { public List<CategorizableTranslatedSelectable<CMSMediaItem>> getMediaItems() throws DAOException { return this.dataProvider.getPaginatorList(); } CmsMediaBean(); void resetData(); CMSMediaItem createMediaItem(); List<CMSPage> getMediaOwnerPages(CMSMediaItem item); void deleteMedia(CMSMediaItem item); List<CMSMediaItem> getAllMedia(); TableDataProvider<CategorizableTranslatedSelectable<CMSMediaItem>> getDataProvider(); List<CategorizableTranslatedSelectable<CMSMediaItem>> getMediaItems(); void reloadMediaList(); void reloadMediaList(boolean resetCurrentPage); void deleteSelectedItems(); void saveSelectedItems(); static String getMediaUrl(CMSMediaItem item); static String getMediaUrl(CMSMediaItem item, String width, String height); static String getMediaFileAsString(CMSMediaItem item); static String getMediaPreviewUrl(CMSMediaItem item); boolean isImage(CMSMediaItem item); boolean isText(CMSMediaItem item); void saveSelectedMediaItem(); void saveMedia(CMSMediaItem media, List<Selectable<CMSCategory>> categories); void saveMedia(CMSMediaItem media); static String getFileName(Part filePart); void setSelectedTag(String selectedTag); String getSelectedTag(); List<CMSCategory> getAllMediaCategories(); Collection<CMSMediaItem.DisplaySize> getMediaItemDisplaySizes(); static String getImageFilter(); static String getDocumentFilter(); String getFilter(); void setFilter(String filter); String getFilenameFilter(); void setFilenameFilter(String filter); void setSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); void toggleSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); TranslatedSelectable<CMSMediaItem> getSelectedMediaItem(); void setAllSelected(boolean allSelected); boolean isAllSelected(); boolean needsPaginator(); }### Answer: @Test public void testGetMediaItems() throws DAOException { bean.setFilter(""); Assert.assertEquals(4, bean.getMediaItems().size()); bean.setFilter("tag1"); Assert.assertEquals(3, bean.getMediaItems().size()); bean.setFilter(""); bean.setFilenameFilter(bean.getImageFilter()); Assert.assertEquals(4, bean.getMediaItems().size()); bean.setFilenameFilter(".*\\.xml"); Assert.assertEquals(0, bean.getMediaItems().size()); }
### Question: CmsMediaBean implements Serializable { public static String getImageFilter() { return "(?i).*\\.(png|jpe?g|gif|tiff?|jp2)"; } CmsMediaBean(); void resetData(); CMSMediaItem createMediaItem(); List<CMSPage> getMediaOwnerPages(CMSMediaItem item); void deleteMedia(CMSMediaItem item); List<CMSMediaItem> getAllMedia(); TableDataProvider<CategorizableTranslatedSelectable<CMSMediaItem>> getDataProvider(); List<CategorizableTranslatedSelectable<CMSMediaItem>> getMediaItems(); void reloadMediaList(); void reloadMediaList(boolean resetCurrentPage); void deleteSelectedItems(); void saveSelectedItems(); static String getMediaUrl(CMSMediaItem item); static String getMediaUrl(CMSMediaItem item, String width, String height); static String getMediaFileAsString(CMSMediaItem item); static String getMediaPreviewUrl(CMSMediaItem item); boolean isImage(CMSMediaItem item); boolean isText(CMSMediaItem item); void saveSelectedMediaItem(); void saveMedia(CMSMediaItem media, List<Selectable<CMSCategory>> categories); void saveMedia(CMSMediaItem media); static String getFileName(Part filePart); void setSelectedTag(String selectedTag); String getSelectedTag(); List<CMSCategory> getAllMediaCategories(); Collection<CMSMediaItem.DisplaySize> getMediaItemDisplaySizes(); static String getImageFilter(); static String getDocumentFilter(); String getFilter(); void setFilter(String filter); String getFilenameFilter(); void setFilenameFilter(String filter); void setSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); void toggleSelectedMediaItem(CategorizableTranslatedSelectable<CMSMediaItem> selectedMediaItem); TranslatedSelectable<CMSMediaItem> getSelectedMediaItem(); void setAllSelected(boolean allSelected); boolean isAllSelected(); boolean needsPaginator(); }### Answer: @Test public void testGetImageFilter() { String file1 = "image.jpg"; String file2 = "image.JPEG"; String file3 = "image.xml"; Assert.assertTrue(file1.matches(bean.getImageFilter())); Assert.assertTrue(file2.matches(bean.getImageFilter())); Assert.assertFalse(file3.matches(bean.getImageFilter())); }
### Question: BrowseBean implements Serializable { public List<String> getBrowsingMenuItems(String language) { if (language != null) { language = language.toUpperCase(); } List<String> ret = new ArrayList<>(); for (BrowsingMenuFieldConfig bmfc : DataManager.getInstance().getConfiguration().getBrowsingMenuFields()) { if (bmfc.getField().contains(SolrConstants._LANG_) && (language == null || !bmfc.getField().contains(SolrConstants._LANG_ + language))) { logger.trace("Skipped {}", bmfc.getField()); continue; } ret.add(bmfc.getField()); } return ret; } BrowseBean(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); void setSearchBean(SearchBean searchBean); void resetTerms(); void resetAllLists(); void resetDcList(); void resetList(String field); List<BrowseDcElement> getDcList(); List<BrowseDcElement> getList(String field); List<BrowseDcElement> getList(String field, int depth); void populateCollection(String field); String getCollectionToExpand(); void setCollectionToExpand(String collectionToExpand); String getTopVisibleCollection(); void setTopVisibleCollection(String topVisibleCollecion); void expandCollection(int levels); void expandCollection(String collectionField, String facetField, int levels); String searchTermsAction(); String searchTerms(); String getBrowsingMenuField(); boolean isBrowsingMenuFieldTranslated(); void setBrowsingMenuField(String browsingMenuField); List<String> getBrowseTermList(); List<String> getBrowseTermListEscaped(); List<Long> getBrowseTermHitCountList(); String getPrevTermUrl(); String getNextTermUrl(); List<String> getAvailableStringFilters(); String getCurrentStringFilter(); void setCurrentStringFilter(String currentStringFilter); String getFilterQuery(); void setFilterQuery(String filterQuery); int getCurrentPage(); void setCurrentPage(int currentPage); int getLastPage(); boolean isBrowsingMenuEnabled(); List<String> getBrowsingMenuItems(String language); String getTargetCollection(); void setTargetCollection(String targetCollection); String openWorkInTargetCollection(); CollectionView getDcCollection(); CollectionView getCollection(String field); void initializeDCCollection(); void initializeCollection(final String collectionField, final String facetField); String getCollectionField(); void setCollectionField(String collectionField); String getCollectionHierarchy(String collectionField, String collectionValue); }### Answer: @Test public void getBrowsingMenuItems_shouldSkipItemsForLanguagespecificFieldsIfNoLanguageWasGiven() throws Exception { BrowseBean bb = new BrowseBean(); List<String> result = bb.getBrowsingMenuItems(null); Assert.assertEquals(2, result.size()); Assert.assertEquals("MD_AUTHOR_UNTOKENIZED", result.get(0)); Assert.assertEquals("MD_SHELFMARK", result.get(1)); } @Test public void getBrowsingMenuItems_shouldSkipItemsForLanguagespecificFieldsIfTheyDontMatchGivenLanguage() throws Exception { BrowseBean bb = new BrowseBean(); List<String> result = bb.getBrowsingMenuItems("en"); Assert.assertEquals(3, result.size()); Assert.assertEquals("MD_AUTHOR_UNTOKENIZED", result.get(0)); Assert.assertEquals("MD_TITLE_LANG_EN_UNTOKENIZED", result.get(1)); Assert.assertEquals("MD_SHELFMARK", result.get(2)); }
### Question: BrowseBean implements Serializable { public String getCollectionHierarchy(String collectionField, String collectionValue) { if (StringUtils.isEmpty(collectionField) || StringUtils.isEmpty(collectionValue)) { return ""; } String separator = DataManager.getInstance().getConfiguration().getCollectionSplittingChar(collectionField); if (separator.equals(".")) { separator = "\\."; } String[] valueSplit = collectionValue.split(separator); if (valueSplit.length == 0) { return ViewerResourceBundle.getTranslation(collectionValue, null); } StringBuilder sb = new StringBuilder(); String collectionName = ""; for (String value : valueSplit) { if (sb.length() > 0) { sb.append(" / "); collectionName += "."; } collectionName += value; sb.append(ViewerResourceBundle.getTranslation(collectionName, null)); } return sb.toString(); } BrowseBean(); void setBreadcrumbBean(BreadcrumbBean breadcrumbBean); void setSearchBean(SearchBean searchBean); void resetTerms(); void resetAllLists(); void resetDcList(); void resetList(String field); List<BrowseDcElement> getDcList(); List<BrowseDcElement> getList(String field); List<BrowseDcElement> getList(String field, int depth); void populateCollection(String field); String getCollectionToExpand(); void setCollectionToExpand(String collectionToExpand); String getTopVisibleCollection(); void setTopVisibleCollection(String topVisibleCollecion); void expandCollection(int levels); void expandCollection(String collectionField, String facetField, int levels); String searchTermsAction(); String searchTerms(); String getBrowsingMenuField(); boolean isBrowsingMenuFieldTranslated(); void setBrowsingMenuField(String browsingMenuField); List<String> getBrowseTermList(); List<String> getBrowseTermListEscaped(); List<Long> getBrowseTermHitCountList(); String getPrevTermUrl(); String getNextTermUrl(); List<String> getAvailableStringFilters(); String getCurrentStringFilter(); void setCurrentStringFilter(String currentStringFilter); String getFilterQuery(); void setFilterQuery(String filterQuery); int getCurrentPage(); void setCurrentPage(int currentPage); int getLastPage(); boolean isBrowsingMenuEnabled(); List<String> getBrowsingMenuItems(String language); String getTargetCollection(); void setTargetCollection(String targetCollection); String openWorkInTargetCollection(); CollectionView getDcCollection(); CollectionView getCollection(String field); void initializeDCCollection(); void initializeCollection(final String collectionField, final String facetField); String getCollectionField(); void setCollectionField(String collectionField); String getCollectionHierarchy(String collectionField, String collectionValue); }### Answer: @Test public void getCollectionHierarchy_shouldReturnHierarchyCorrectly() throws Exception { BrowseBean bb = new BrowseBean(); Assert.assertEquals("foo", bb.getCollectionHierarchy("x", "foo")); Assert.assertEquals("foo / foo.bar", bb.getCollectionHierarchy("x", "foo.bar")); }
### Question: ThumbnailHandler { public String getFullImageUrl(PhysicalElement page) { return getFullImageUrl(page, Scale.MAX); } ThumbnailHandler(IIIFUrlHandler iiifUrlHandler, Configuration configuration, String staticImagesPath); URI getThumbnailPath(String filename); String getThumbnailUrl(PhysicalElement page); String getThumbnailUrl(String pi); String getThumbnailUrl(String pi, int width, int height); String getSquareThumbnailUrl(String pi); String getSquareThumbnailUrl(String pi, int size); String getThumbnailUrl(int order, String pi); String getThumbnailUrl(int order, String pi, int width, int height); String getSquareThumbnailUrl(int order, String pi); String getSquareThumbnailUrl(int order, String pi, int size); PhysicalElement getPage(String pi, int order); String getThumbnailUrl(PhysicalElement page, int width, int height); String getThumbnailUrl(PhysicalElement page, Scale scale); String getSquareThumbnailUrl(PhysicalElement page); String getSquareThumbnailUrl(PhysicalElement page, int size); String getThumbnailUrl(StructElement doc); String getThumbnailUrl(StructElement doc, String pi); String getThumbnailUrl(SolrDocument doc); String getSquareThumbnailUrl(SolrDocument doc); String getThumbnailUrl(SolrDocument doc, int width, int height); String getSquareThumbnailUrl(SolrDocument doc, int size); String getThumbnailUrl(StructElement se, int width, int height); String getThumbnailUrl(StructElement doc, String pi, int width, int height); String getFullImageUrl(PhysicalElement page); String getFullImageUrl(PhysicalElement page, Scale scale); String getSquareThumbnailUrl(StructElement se); String getSquareThumbnailUrl(StructElement se, int size); String getThumbnailUrl(Optional<CMSMediaItem> item); String getThumbnailUrl(CMSMediaItem item); String getThumbnailUrl(Optional<CMSMediaItem> optional, int width, int height); String getThumbnailUrl(Path imagePath); String getSquareThumbnailUrl(Path imagePath); String getThumbnailUrl(Path imagePath, int width, int height); String getSquareThumbnailUrl(Path imagePath, int width); String getThumbnailUrl(CMSMediaItem media, int width, int height); String getSquareThumbnailUrl(Optional<CMSMediaItem> optional, int size); String getSquareThumbnailUrl(CMSMediaItem media, int size); String getSquareThumbnailUrl(Optional<CMSMediaItem> item); String getSquareThumbnailUrl(CMSMediaItem item); boolean isStaticImageResource(String thumbnailUrl); static final String[] REQUIRED_SOLR_FIELDS; }### Answer: @Test public void testGetFullImageUrl() { String fileUrl = "00000001.tif"; PhysicalElement page = new PhysicalElement("PHYS_0001", fileUrl, 1, "Seite 1", "urn:234235:3423", "http: String urlMax = handler.getFullImageUrl(page, Scale.MAX); Assert.assertEquals("/api/v1/records/1234/files/images/00000001.tif/full/max/0/default.tif", urlMax); String urlBox = handler.getFullImageUrl(page, new Scale.ScaleToBox(1500, 1500)); Assert.assertEquals("/api/v1/records/1234/files/images/00000001.tif/full/!1500,1500/0/default.tif", urlBox); String urlFraction = handler.getFullImageUrl(page, new Scale.ScaleToFraction(0.5)); Assert.assertEquals("/api/v1/records/1234/files/images/00000001.tif/full/pct%3A50/0/default.tif", urlFraction); }
### Question: ImageHandler { public String getImageUrl(PhysicalElement page, PageType pageType) { if (page == null) { throw new IllegalArgumentException("Cannot get image url: PhysicalElement is null"); } if (pageType == null) { throw new IllegalArgumentException("Cannot get image url: PageType is null"); } String pi = page.getPi(); String filepath = page.getFilepath(); String filename = page.getFileName(); return getImageUrl(pageType, pi, filepath, filename); } ImageHandler(); ImageHandler(AbstractApiUrlManager contentUrlManager); String getImageUrl(PhysicalElement page, PageType pageType); String getImageUrl(PageType pageType, String pi, String filepath); String getImageUrl(PageType pageType, String pi, String filepath, String filename); String getImageUrl(PhysicalElement page); ImageInformation getImageInformation(PhysicalElement page); ImageInformation getImageInformation(String url); static boolean isRestrictedUrl(String path); }### Answer: @Test public void testGetImageUrlLocal() { PhysicalElement page = new PhysicalElement("PHYS_0001", "00000001.tif", 1, "Seite 1", "urn:234235:3423", "http: String url = handler.getImageUrl(page); Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "api/v1/image/1234/00000001.tif/info.json", url); } @Test public void testGetImageUrlExternal() { PhysicalElement page = new PhysicalElement("PHYS_0001", "http: "http: String url = handler.getImageUrl(page); Assert.assertEquals("http: } @Test public void testGetImageUrlInternal() { PhysicalElement page = new PhysicalElement("PHYS_0001", "http: "http: String url = handler.getImageUrl(page); Assert.assertEquals( ConfigurationTest.APPLICATION_ROOT_URL + "api/v1/image/-/http:U002FU002FexteralU002FrestrictedU002FimagesU002F00000001.tif/info.json", url); }
### Question: MediaHandler { public String getMediaUrl(String type, String format, String pi, String filename) throws IllegalRequestException { if(urls != null) { if(type.equalsIgnoreCase("audio")) { return urls.path(ApiUrls.RECORDS_FILES, ApiUrls.RECORDS_FILES_AUDIO).params(pi, format, filename).build(); } else if(type.equalsIgnoreCase("video")){ return urls.path(ApiUrls.RECORDS_FILES, ApiUrls.RECORDS_FILES_VIDEO).params(pi, format, filename).build(); } else { throw new IllegalRequestException("Unknown media type " + type); } } else { return DataManager.getInstance().getConfiguration().getIIIFApiUrl() + URL_TEMPLATE.replace("{mimeType}", type + "/" + format).replace("{identifier}", pi).replace("{filename}", filename); } } MediaHandler(); MediaHandler(AbstractApiUrlManager urls); String getMediaUrl(String type, String format, String pi, String filename); }### Answer: @Test public void testGetMediaUrl() throws IllegalRequestException { String mediaUrl = handler.getMediaUrl("audio","ogg", "1234", "audio.ogg"); Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "api/v1/records/1234/files/audio/ogg/audio.ogg", mediaUrl); }
### Question: IIIFUrlHandler { public String getIIIFImageUrl(String fileUrl, String docStructIdentifier, String region, String size, String rotation, String quality, String format) { String apiUrl = this.urls == null ? DataManager.getInstance().getConfiguration().getIIIFApiUrl() : this.urls.getApiUrl() + "/"; return getIIIFImageUrl(apiUrl, fileUrl, docStructIdentifier, region, size, rotation, quality, format); } IIIFUrlHandler(AbstractApiUrlManager urls); IIIFUrlHandler(); String getIIIFImageUrl(String fileUrl, String docStructIdentifier, String region, String size, String rotation, String quality, String format); String getIIIFImageUrl(String apiUrl, String fileUrl, String docStructIdentifier, String region, String size, String rotation, String quality, String format); String getIIIFImageUrl(String baseUrl, RegionRequest region, Scale size, Rotation rotation, Colortype quality, ImageFileFormat format); String getModifiedIIIFFUrl(String url, RegionRequest region, Scale size, Rotation rotation, Colortype quality, ImageFileFormat format); AbstractApiUrlManager getUrlManager(); }### Answer: @Test public void testUrlFromFile() { String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("/api/v1/records/1234/files/images/filename.tif/full/max/0/default.jpg", url); } @Test public void testUrlFromLocalUrl() { fileUrl = "http: String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("/api/v1/image/-/http:U002FU002FlocalhostU002FimageU002Ffilename.tif/full/max/0/default.jpg", url); } @Test public void testUrlFromExternalImageUrl() { fileUrl = "http: String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("http: } @Test public void testUrlFromLocalFileUrl() { fileUrl = "file: String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("/api/v1/image/-/file:U002FU002FU002FimageU002Ffilename.tif/full/max/0/default.jpg", url); } @Test public void testUrlFromLocalFileUrlWithSpace() { fileUrl = "file: String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("/api/v1/image/-/file:U002FU002FU002FimageU002Ffilename%2001.tif/full/max/0/default.jpg", url); } @Test public void testUrlFromWindowsFileUrl() { fileUrl = "file: String url = handler.getIIIFImageUrl(fileUrl, pi, region, size, rotation, quality, format); Assert.assertEquals("/api/v1/image/-/file:U002FU002FU002FC:U002FoptU002FdigiversoU002FviewerU002Fcms_mediaU002Ffilename.tif/full/max/0/default.jpg", url); }
### Question: ViewerResourceBundle extends ResourceBundle { public static List<Locale> getAllLocales() { if (allLocales == null) { checkAndLoadResourceBundles(); Set<Locale> locales = new HashSet<>(); locales.addAll(defaultBundles.keySet()); locales.addAll(localBundles.keySet()); allLocales = new ArrayList<>(locales); synchronized (allLocales) { Path configPath = Paths.get(DataManager.getInstance().getConfiguration().getConfigLocalPath()); try (Stream<Path> messageFiles = Files.list(configPath).filter(path -> path.getFileName().toString().matches("messages_[a-z]{1,3}.properties"))) { allLocales.addAll(messageFiles .map(path -> StringTools.findFirstMatch(path.getFileName().toString(), "(?:messages_)([a-z]{1,3})(?:.properties)", 1) .orElse(null)) .filter(lang -> lang != null) .sorted((l1, l2) -> { if (l1.equals(l2)) { return 0; } switch (l1) { case "en": return -1; case "de": return l2.equals("en") ? 1 : -1; default: switch (l2) { case "en": case "de": return 1; } } return l1.compareTo(l2); }) .map(language -> Locale.forLanguageTag(language)) .collect(Collectors.toList())); allLocales = allLocales.stream().distinct().collect(Collectors.toList()); } catch (IOException e) { logger.warn("Error reading config directory; {}", configPath); } if (allLocales.isEmpty()) { allLocales.add(Locale.ENGLISH); } } } return allLocales; } ViewerResourceBundle(); static Locale getDefaultLocale(); static String getTranslation(final String key, Locale locale); static String getTranslationWithParameters(final String key, final Locale locale, final String... params); static String getTranslation(final String key, Locale locale, boolean useFallback); static String cleanUpTranslation(String value); static List<String> getMessagesValues(Locale locale, String keyPrefix); @Override Enumeration<String> getKeys(); static List<Locale> getAllLocales(); static List<Locale> getFacesLocales(); static IMetadataValue getTranslations(String key); static IMetadataValue getTranslations(String key, boolean allowKeyAsTranslation); static List<Locale> getLocalesFromFacesConfig(); static List<Locale> getLocalesFromFile(Path facesConfigPath); static Thread backgroundThread; }### Answer: @Test public void getAllLocales_shouldReturnEnglishIfNoOtherLocalesFound() throws Exception { List<Locale> locales = ViewerResourceBundle.getAllLocales(); Assert.assertEquals(1, locales.size()); Assert.assertEquals(Locale.ENGLISH, locales.get(0)); }
### Question: PdfHandler { public String getPdfUrl(StructElement doc, PhysicalElement page) { return getPdfUrl(doc, new PhysicalElement[] { page }); } PdfHandler(WatermarkHandler watermarkHandler, Configuration configuration); PdfHandler(WatermarkHandler watermarkHandler, AbstractApiUrlManager urls); String getPdfUrl(StructElement doc, PhysicalElement page); String getPdfUrl(StructElement doc, PhysicalElement[] pages); String getPdfUrl(String pi, String filename); String getPdfUrl(StructElement doc, String label); String getPdfUrl(StructElement doc, String pi, String label); String getPdfUrl(String pi, Optional<String> divId, Optional<String> watermarkId, Optional<String> watermarkText, Optional<String> label); }### Answer: @Test public void test() { String pi = "1234"; Optional<String> divId = Optional.ofNullable("LOG_0003"); Optional<String> watermarkId = Optional.ofNullable("footerId"); Optional<String> watermarkText = Optional.ofNullable("watermark text"); Optional<String> label = Optional.ofNullable("output-filename.pdf"); String url = handler.getPdfUrl(pi, divId, watermarkId, watermarkText, label); Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "api/v1/records/1234/sections/LOG_0003/pdf/?watermarkText=watermark+text&watermarkId=footerId", url); }
### Question: IIIFPresentationAPIHandler { public String getManifestUrl(String pi) throws URISyntaxException { return builder.getManifestURI(pi).toString(); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetManifestUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/records/PI-SAMPLE/manifest/", handler.getManifestUrl("PI-SAMPLE")); }
### Question: IIIFPresentationAPIHandler { public String getCollectionUrl() throws URISyntaxException { return getCollectionUrl(SolrConstants.DC); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetCollectionUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/collections/DC/", handler.getCollectionUrl()); } @Test public void testGetCollectionUrlString() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/collections/DC/", handler.getCollectionUrl("DC")); } @Test public void testGetCollectionUrlStringString() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/collections/DC/sonstige.ocr", handler.getCollectionUrl("DC", "sonstige.ocr")); }
### Question: IIIFPresentationAPIHandler { public String getLayerUrl(String pi, String annotationType) throws URISyntaxException { AnnotationType type = AnnotationType.valueOf(annotationType.toUpperCase()); if (type == null) { throw new IllegalArgumentException(annotationType + " is not valid annotation type"); } return builder.getLayerURI(pi, type).toString(); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetLayerUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/records/PI-SAMPLE/layers/FULLTEXT/", handler.getLayerUrl("PI-SAMPLE", "fulltext")); }
### Question: IIIFPresentationAPIHandler { public String getAnnotationsUrl(String pi, int pageOrder, String annotationType) throws URISyntaxException { AnnotationType type = AnnotationType.valueOf(annotationType.toUpperCase()); if (type == null) { throw new IllegalArgumentException(annotationType + " is not valid annotation type"); } return builder.getAnnotationListURI(pi, pageOrder, type).toString(); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetAnnotationsUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/records/PI-SAMPLE/pages/12/annotations/?type=PDF", handler.getAnnotationsUrl("PI-SAMPLE", 12, "pdf")); }
### Question: IIIFPresentationAPIHandler { public String getCanvasUrl(String pi, int pageOrder) throws URISyntaxException { return builder.getCanvasURI(pi, pageOrder).toString(); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetCanvasUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/records/PI-SAMPLE/pages/12/canvas/", handler.getCanvasUrl("PI-SAMPLE", 12)); }
### Question: IIIFPresentationAPIHandler { public String getRangeUrl(String pi, String logId) throws URISyntaxException { return builder.getRangeURI(pi, logId).toString(); } IIIFPresentationAPIHandler(AbstractApiUrlManager urls, Configuration configuration); String getManifestUrl(String pi); String getCollectionUrl(); String getCollectionUrl(String field); String getCollectionUrl(String field, String collection); String getLayerUrl(String pi, String annotationType); String getAnnotationsUrl(String pi, int pageOrder, String annotationType); String getCanvasUrl(String pi, int pageOrder); String getRangeUrl(String pi, String logId); }### Answer: @Test public void testGetRangeUrl() throws URISyntaxException { Assert.assertEquals(ConfigurationTest.APPLICATION_ROOT_URL + "rest/records/PI-SAMPLE/sections/LOG_0007/range/", handler.getRangeUrl("PI-SAMPLE", "LOG_0007")); }
### Question: XmlTools { public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException { if (encoding == null) { encoding = StringTools.DEFAULT_ENCODING; } byte[] byteArray = null; try { byteArray = string.getBytes(encoding); } catch (UnsupportedEncodingException e) { } ByteArrayInputStream baos = new ByteArrayInputStream(byteArray); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(baos); return document; } static Document readXmlFile(String filePath); static Document readXmlFile(URL url); static Document readXmlFile(Path path); static File writeXmlFile(Document doc, String filePath); static Document getDocumentFromString(String string, String encoding); static String getStringFromElement(Object element, String encoding); static List<Element> evaluateToElements(String expr, Element element, List<Namespace> namespaces); @SuppressWarnings({ "rawtypes", "unchecked" }) static List<Object> evaluate(String expr, Object parent, Filter filter, List<Namespace> namespaces); static String determineFileFormat(String xml, String encoding); static String determineFileFormat(Document doc); static Document transformViaXSLT(Document doc, String stylesheetPath, Map<String, String> params); }### Answer: @Test public void getDocumentFromString_shouldBuildDocumentCorrectly() throws Exception { String xml = "<root><child>child1</child><child>child2</child></root>"; Document doc = XmlTools.getDocumentFromString(xml, null); Assert.assertNotNull(doc); Assert.assertNotNull(doc.getRootElement()); Assert.assertEquals("root", doc.getRootElement().getName()); Assert.assertNotNull(doc.getRootElement().getChildren("child")); Assert.assertEquals(2, doc.getRootElement().getChildren("child").size()); }
### Question: XmlTools { public static String getStringFromElement(Object element, String encoding) { if (element == null) { throw new IllegalArgumentException("element may not be null"); } if (encoding == null) { encoding = StringTools.DEFAULT_ENCODING; } Format format = Format.getRawFormat(); XMLOutputter outputter = new XMLOutputter(format); Format xmlFormat = outputter.getFormat(); if (StringUtils.isNotEmpty(encoding)) { xmlFormat.setEncoding(encoding); } xmlFormat.setExpandEmptyElements(true); outputter.setFormat(xmlFormat); String docString = null; if (element instanceof Document) { docString = outputter.outputString((Document) element); } else if (element instanceof Element) { docString = outputter.outputString((Element) element); } return docString; } static Document readXmlFile(String filePath); static Document readXmlFile(URL url); static Document readXmlFile(Path path); static File writeXmlFile(Document doc, String filePath); static Document getDocumentFromString(String string, String encoding); static String getStringFromElement(Object element, String encoding); static List<Element> evaluateToElements(String expr, Element element, List<Namespace> namespaces); @SuppressWarnings({ "rawtypes", "unchecked" }) static List<Object> evaluate(String expr, Object parent, Filter filter, List<Namespace> namespaces); static String determineFileFormat(String xml, String encoding); static String determineFileFormat(Document doc); static Document transformViaXSLT(Document doc, String stylesheetPath, Map<String, String> params); }### Answer: @Test public void getStringFromElement_shouldReturnXMLStringCorrectlyForDocuments() throws Exception { Document doc = new Document(); doc.setRootElement(new Element("root")); String xml = XmlTools.getStringFromElement(doc, null); Assert.assertNotNull(xml); Assert.assertTrue(xml.contains("<root></root>")); } @Test public void getStringFromElement_shouldReturnXMLStringCorrectlyForElements() throws Exception { String xml = XmlTools.getStringFromElement(new Element("root"), null); Assert.assertNotNull(xml); Assert.assertTrue(xml.contains("<root></root>")); }
### Question: XmlTools { public static File writeXmlFile(Document doc, String filePath) throws FileNotFoundException, IOException { return FileTools.getFileFromString(getStringFromElement(doc, StringTools.DEFAULT_ENCODING), filePath, StringTools.DEFAULT_ENCODING, false); } static Document readXmlFile(String filePath); static Document readXmlFile(URL url); static Document readXmlFile(Path path); static File writeXmlFile(Document doc, String filePath); static Document getDocumentFromString(String string, String encoding); static String getStringFromElement(Object element, String encoding); static List<Element> evaluateToElements(String expr, Element element, List<Namespace> namespaces); @SuppressWarnings({ "rawtypes", "unchecked" }) static List<Object> evaluate(String expr, Object parent, Filter filter, List<Namespace> namespaces); static String determineFileFormat(String xml, String encoding); static String determineFileFormat(Document doc); static Document transformViaXSLT(Document doc, String stylesheetPath, Map<String, String> params); }### Answer: @Test(expected = FileNotFoundException.class) public void writeXmlFile_shouldThrowFileNotFoundExceptionIfFileIsDirectory() throws Exception { Document doc = new Document(); doc.setRootElement(new Element("root")); XmlTools.writeXmlFile(doc, "target"); }
### Question: XmlTools { public static Document readXmlFile(String filePath) throws FileNotFoundException, IOException, JDOMException { try (FileInputStream fis = new FileInputStream(new File(filePath))) { return new SAXBuilder().build(fis); } } static Document readXmlFile(String filePath); static Document readXmlFile(URL url); static Document readXmlFile(Path path); static File writeXmlFile(Document doc, String filePath); static Document getDocumentFromString(String string, String encoding); static String getStringFromElement(Object element, String encoding); static List<Element> evaluateToElements(String expr, Element element, List<Namespace> namespaces); @SuppressWarnings({ "rawtypes", "unchecked" }) static List<Object> evaluate(String expr, Object parent, Filter filter, List<Namespace> namespaces); static String determineFileFormat(String xml, String encoding); static String determineFileFormat(Document doc); static Document transformViaXSLT(Document doc, String stylesheetPath, Map<String, String> params); }### Answer: @Test public void readXmlFile_shouldBuildDocumentFromPathCorrectly() throws Exception { Document doc = XmlTools.readXmlFile(Paths.get("src/test/resources/config_viewer.test.xml")); Assert.assertNotNull(doc); Assert.assertNotNull(doc.getRootElement()); } @Test public void readXmlFile_shouldBuildDocumentFromStringCorrectly() throws Exception { Document doc = XmlTools.readXmlFile("src/test/resources/config_viewer.test.xml"); Assert.assertNotNull(doc); Assert.assertNotNull(doc.getRootElement()); } @Test public void readXmlFile_shouldBuildDocumentFromUrlCorrectly() throws Exception { Document doc = XmlTools.readXmlFile(Paths.get("src/test/resources/config_viewer.test.xml").toUri().toURL()); Assert.assertNotNull(doc); Assert.assertNotNull(doc.getRootElement()); } @Test(expected = FileNotFoundException.class) public void readXmlFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { XmlTools.readXmlFile("notfound.xml"); }
### Question: ViewerResourceBundle extends ResourceBundle { public static List<Locale> getLocalesFromFile(Path facesConfigPath) throws FileNotFoundException, IOException, JDOMException { Document doc = XmlTools.readXmlFile(facesConfigPath); Namespace xsi = Namespace.getNamespace("xsi", "http: Namespace javaee = Namespace.getNamespace("ee", "http: List<Namespace> namespaces = Arrays.asList(xsi, javaee); List<Element> localeElements = XmlTools.evaluateToElements(" return localeElements.stream().map(ele -> ele.getText()).map(Locale::forLanguageTag).collect(Collectors.toList()); } ViewerResourceBundle(); static Locale getDefaultLocale(); static String getTranslation(final String key, Locale locale); static String getTranslationWithParameters(final String key, final Locale locale, final String... params); static String getTranslation(final String key, Locale locale, boolean useFallback); static String cleanUpTranslation(String value); static List<String> getMessagesValues(Locale locale, String keyPrefix); @Override Enumeration<String> getKeys(); static List<Locale> getAllLocales(); static List<Locale> getFacesLocales(); static IMetadataValue getTranslations(String key); static IMetadataValue getTranslations(String key, boolean allowKeyAsTranslation); static List<Locale> getLocalesFromFacesConfig(); static List<Locale> getLocalesFromFile(Path facesConfigPath); static Thread backgroundThread; }### Answer: @Test public void testGetLocalesFromFile() throws FileNotFoundException, IOException, JDOMException { Path configPath = Paths.get("src/test/resources/localConfig/faces-config.xml"); assumeTrue(Files.isRegularFile(configPath)); List<Locale> locales = ViewerResourceBundle.getLocalesFromFile(configPath); assertEquals(6, locales.size()); assertEquals(Locale.ENGLISH, locales.get(1)); assertEquals(Locale.FRENCH, locales.get(3)); }
### Question: AccessConditionUtils { public static boolean isConcurrentViewsLimitEnabledForAnyAccessCondition(List<String> accessConditions) throws DAOException { if (accessConditions == null || accessConditions.isEmpty()) { return false; } List<LicenseType> licenseTypes = DataManager.getInstance().getDao().getLicenseTypes(accessConditions); if (licenseTypes.isEmpty()) { return false; } for (LicenseType licenseType : licenseTypes) { if (licenseType.isConcurrentViewsLimit()) { return true; } } return false; } static boolean checkAccess(HttpServletRequest request, String action, String pi, String contentFileName, boolean isThumbnail); static boolean checkAccessPermissionByIdentifierAndLogId(String identifier, String logId, String privilegeName, HttpServletRequest request); @SuppressWarnings("unchecked") static Map<String, Boolean> checkAccessPermissionByIdentiferForAllLogids(String identifier, String privilegeName, HttpServletRequest request); @SuppressWarnings("unchecked") static Map<String, Boolean> checkContentFileAccessPermission(String identifier, HttpServletRequest request, List<Path> files); static boolean checkAccessPermissionByImageUrn(String imageUrn, String privilegeName, HttpServletRequest request); static boolean checkAccessPermission(Set<String> requiredAccessConditions, String privilegeName, String query, HttpServletRequest request); static boolean checkAccessPermissionForImage(HttpServletRequest request, String pi, String contentFileName); static boolean checkAccessPermissionForThumbnail(HttpServletRequest request, String pi, String contentFileName); static boolean checkAccessPermissionForPagePdf(HttpServletRequest request, PhysicalElement page); static boolean checkAccessPermissionByIdentifierAndFilePathWithSessionMap(HttpServletRequest request, String filePath, String privilegeType); @SuppressWarnings("unchecked") static boolean checkAccessPermissionByIdentifierAndFileNameWithSessionMap(HttpServletRequest request, String pi, String contentFileName, String privilegeType); static boolean checkAccessPermission(List<LicenseType> allLicenseTypes, Set<String> requiredAccessConditions, String privilegeName, User user, String remoteAddress, String query); static boolean isFreeOpenAccess(Set<String> requiredAccessConditions, Collection<LicenseType> allLicenseTypes); static int getPdfDownloadQuotaForRecord(String pi); static boolean isConcurrentViewsLimitEnabledForAnyAccessCondition(List<String> accessConditions); }### Answer: @Test public void isConcurrentViewsLimitEnabledForAnyAccessCondition_shouldReturnFalseIfAccessConditionsNullOrEmpty() throws Exception { Assert.assertFalse(AccessConditionUtils.isConcurrentViewsLimitEnabledForAnyAccessCondition(null)); Assert.assertFalse(AccessConditionUtils.isConcurrentViewsLimitEnabledForAnyAccessCondition(Collections.emptyList())); } @Test public void isConcurrentViewsLimitEnabledForAnyAccessCondition_shouldReturnTrueIfAnyLicenseTypeHasLimitEnabled() throws Exception { String[] licenseTypes = new String[] { "license type 1 name", "license type 4 name" }; Assert.assertTrue(AccessConditionUtils.isConcurrentViewsLimitEnabledForAnyAccessCondition(Arrays.asList(licenseTypes))); }
### Question: SecurityQuestion { public boolean isAnswerCorrect(String answer) { answered = true; if (StringUtils.isBlank(answer)) { return false; } return correctAnswers.contains(answer.toLowerCase()); } SecurityQuestion(String questionKey, Set<String> correctAnswers); boolean isAnswerCorrect(String answer); String getQuestionKey(); Set<String> getCorrectAnswers(); boolean isAnswered(); }### Answer: @Test public void isAnswerCorrect_shouldReturnTrueOnCorrectAnswer() throws Exception { SecurityQuestion q = new SecurityQuestion("foo", Collections.singleton("answer")); Assert.assertTrue(q.isAnswerCorrect("answer")); } @Test public void isAnswerCorrect_shouldReturnTrueOnCorrectAnswerAndIgnoreCase() throws Exception { SecurityQuestion q = new SecurityQuestion("foo", Collections.singleton("answer")); Assert.assertTrue(q.isAnswerCorrect("ANSWER")); } @Test public void isAnswerCorrect_shouldReturnFalseOnIncorrectAnswer() throws Exception { SecurityQuestion q = new SecurityQuestion("foo", Collections.singleton("answer")); Assert.assertFalse(q.isAnswerCorrect("wronganswer")); } @Test public void isAnswerCorrect_shouldReturnFalseEmptyAnswer() throws Exception { SecurityQuestion q = new SecurityQuestion("foo", Collections.singleton("answer")); Assert.assertFalse(q.isAnswerCorrect(null)); Assert.assertFalse(q.isAnswerCorrect("")); Assert.assertFalse(q.isAnswerCorrect(" ")); }
### Question: DCRecordWriter { public void write(Path path) throws IOException { Path filePath = path; if(Files.isDirectory(path)) { if(StringUtils.isNotBlank(getMetadataValue("identifier"))) { filePath = path.resolve(getMetadataValue("identifier") + ".xml"); } else if(StringUtils.isNotBlank(getMetadataValue("title"))) { filePath = path.resolve(getMetadataValue("title") + ".xml"); } else { filePath = path.resolve(System.currentTimeMillis() + ".xml"); } } else if(!Files.exists(path.getParent())) { throw new IOException("Parent directory of output destination " + path + " must exist to create file"); } XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); try(OutputStream out = Files.newOutputStream(filePath)) { xmlOutput.output(doc, out); } } DCRecordWriter(); void addDCMetadata(String name, String value); String getMetadataValue(String name); Document getDocument(); void write(Path path); String getAsString(); static final Namespace namespaceDC; }### Answer: @Test public void testWrite() { DCRecordWriter writer = new DCRecordWriter(); writer.addDCMetadata("title", "Titel"); writer.addDCMetadata("identifier", "ID"); String xml = writer.getAsString().replaceAll("[\n\r]+", "").replaceAll("\\s+", " "); Assert.assertEquals(RECORD_REFERENCE, xml); }
### Question: RecordLock { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecordLock other = (RecordLock) obj; if (pi == null) { if (other.pi != null) return false; } else if (!pi.equals(other.pi)) return false; if (sessionId == null) { if (other.sessionId != null) return false; } else if (!sessionId.equals(other.sessionId)) return false; return true; } RecordLock(String pi, String sessionId); @Override int hashCode(); @Override boolean equals(Object obj); String getPi(); String getSessionId(); long getTimeCreated(); @Override String toString(); }### Answer: @Test public void equals_shouldReturnTrueIfPiAndSessionIdSame() throws Exception { RecordLock lock = new RecordLock("PPN123", "sid123"); Assert.assertTrue(lock.equals(new RecordLock("PPN123", "sid123"))); }
### Question: RecordLockManager { public synchronized void lockRecord(String pi, String sessionId, Integer limit) throws RecordLimitExceededException { logger.trace("lockRecord: {}", pi); if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } if (sessionId == null) { logger.warn("No sessionId given"); return; } if (limit == null) { return; } Set<RecordLock> recordLocks = loadedRecordMap.get(pi); if (recordLocks == null) { recordLocks = new HashSet<>(limit); loadedRecordMap.put(pi, recordLocks); } RecordLock newLock = new RecordLock(pi, sessionId); logger.trace("{} is currently locked {} times", pi, recordLocks.size()); if (recordLocks.size() == limit) { if (recordLocks.contains(newLock)) { return; } throw new RecordLimitExceededException(pi + ":" + limit); } recordLocks.add(newLock); logger.trace("Added lock: {}", newLock); } synchronized void lockRecord(String pi, String sessionId, Integer limit); synchronized int removeLocksForSessionId(String sessionId, List<String> skipPiList); synchronized boolean removeLockForPiAndSessionId(String pi, String sessionId); synchronized int removeOldLocks(long maxAge); }### Answer: @Test(expected = RecordLimitExceededException.class) public void lockRecord_shouldThrowRecordLimitExceededExceptionIfLimitExceeded() throws Exception { DataManager.getInstance().getRecordLockManager().lockRecord("PPN123", "SID123", 1); DataManager.getInstance().getRecordLockManager().lockRecord("PPN123", "SID789", 1); }
### Question: Bookmark implements Serializable { @JsonIgnore public MetadataElement getMetadataElement() throws IndexUnreachableException { SolrDocument doc = retrieveSolrDocument(); Long iddoc = Long.parseLong((String)doc.getFirstValue(SolrConstants.IDDOC)); StructElement se = new StructElement(iddoc, doc); Locale sessionLocale = BeanUtils.getLocale(); String selectedRecordLanguage = sessionLocale.getLanguage(); try { MetadataElement md = new MetadataElement(se, sessionLocale, selectedRecordLanguage); return md; } catch(DAOException | PresentationException e) { throw new IndexUnreachableException(e.getMessage()); } } Bookmark(); Bookmark(String pi, String mainTitle, String name); Bookmark(String pi, String logId, Integer order); Bookmark(String pi, String logId, Integer order, boolean ignoreMissingSolrDoc); @Override int hashCode(); @Override boolean equals(Object obj); boolean bothEqualOrNull(Object o1, Object o2); boolean bothEqualOrBlank(String o1, String o2); String getUrl(); String getRepresentativeImageUrl(); String getRepresentativeImageUrl(int width, int height); @JsonIgnore String getDocumentTitle(); Long getId(); void setId(Long id); BookmarkList getBookmarkList(); void setBookmarkList(BookmarkList bookmarkList); String getPi(); void setPi(String pi); String getLogId(); void setLogId(String logId); String getUrn(); void setUrn(String urn); @JsonIgnore String getMainTitleUnescaped(); String getName(); void setName(String name); String getDescription(); void setDescription(String description); Date getDateAdded(); void setDateAdded(Date dateAdded); Integer getOrder(); void setOrder(Integer order); @Deprecated String getMainTitle(); @Deprecated void setMainTitle(String mainTitle); @JsonIgnore MetadataElement getMetadataElement(); @JsonIgnore String getSolrQueryForDocument(); @JsonIgnore BrowseElement getBrowseElement(); @JsonIgnore boolean isHasImages(); }### Answer: @Test public void testGetMetadataElement() throws IndexUnreachableException, PresentationException { Bookmark bookmarkWork = new Bookmark(PI, null, TITLE); Bookmark bookmarkChapter = new Bookmark(PI, LOGID, TITLE); Bookmark bookmarkPage = new Bookmark(PI, null, PAGE); MetadataElement mdWork = bookmarkWork.getMetadataElement(); Assert.assertNotNull(mdWork); MetadataElement mdChapter = bookmarkChapter.getMetadataElement(); Assert.assertNotNull(mdChapter); MetadataElement mdPage = bookmarkPage.getMetadataElement(); Assert.assertNotNull(mdPage); }
### Question: MetadataTools { public static String applyReplaceRules(String value, List<MetadataReplaceRule> replaceRules, String pi) throws IndexUnreachableException, PresentationException { if (value == null) { return null; } if (replaceRules == null) { return value; } String ret = value; for (MetadataReplaceRule replaceRule : replaceRules) { if (StringUtils.isNotEmpty(replaceRule.getConditions()) && StringUtils.isNotEmpty(pi)) { String conditions = SolrSearchIndex.getProcessedConditions(replaceRule.getConditions()); String query = "+" + SolrConstants.PI_TOPSTRUCT + ":" + pi + " +(" + conditions + ")"; long count = DataManager.getInstance().getSearchIndex().getHitCount(query); if (count == 0) { continue; } } switch (replaceRule.getType()) { case CHAR: StringBuffer sb = new StringBuffer(); sb.append(replaceRule.getKey()); ret = ret.replace(sb.toString(), replaceRule.getReplacement()); break; case STRING: ret = ret.replace((String) replaceRule.getKey(), replaceRule.getReplacement()); break; case REGEX: ret = ret.replaceAll(((String) replaceRule.getKey()), replaceRule.getReplacement()); break; default: logger.error("Unknown replacement key type of '{}: {}", replaceRule.getKey(), replaceRule.getKey().getClass().getName()); break; } } return ret; } static String generateDublinCoreMetaTags(StructElement structElement); static String generateHighwirePressMetaTags(StructElement structElement, List<PhysicalElement> pages); static String generateRIS(StructElement structElement); static String convertLanguageToIso2(String language); static String applyReplaceRules(String value, List<MetadataReplaceRule> replaceRules, String pi); static String findMetadataGroupType(String gndspec); static SolrDocumentList getGroupedMetadata(String iddoc, String subQuery); }### Answer: @Test public void applyReplaceRules_shouldApplyRulesCorrectly() throws Exception { List<MetadataReplaceRule> replaceRules = new ArrayList<>(3); replaceRules.add(new MetadataReplaceRule('<', "", MetadataReplaceRuleType.CHAR)); replaceRules.add(new MetadataReplaceRule(">", "s", MetadataReplaceRuleType.STRING)); replaceRules.add(new MetadataReplaceRule("[ ]*100[ ]*", "", MetadataReplaceRuleType.REGEX)); Assert.assertEquals("vase", MetadataTools.applyReplaceRules(" 100 v<a>e", replaceRules, null)); } @Test public void applyReplaceRules_shouldApplyConditionalRulesCorrectly() throws Exception { List<MetadataReplaceRule> replaceRules = Collections.singletonList( new MetadataReplaceRule("remove me", "", SolrConstants.PI_TOPSTRUCT + ":PPN517154005", MetadataReplaceRuleType.STRING)); Assert.assertEquals(SolrConstants.PI_TOPSTRUCT + ":PPN517154005", replaceRules.get(0).getConditions()); Assert.assertEquals(" please", MetadataTools.applyReplaceRules("remove me please", replaceRules, "PPN517154005")); Assert.assertEquals("remove me please", MetadataTools.applyReplaceRules("remove me please", replaceRules, "PPN123")); Assert.assertEquals(" please", MetadataTools.applyReplaceRules("remove me please", replaceRules, null)); }
### Question: MetadataTools { public static String findMetadataGroupType(String gndspec) { if (gndspec == null) { return null; } if (gndspec.length() == 3) { String ret = null; switch (gndspec.substring(0, 2)) { case "gi": ret = MetadataGroupType.LOCATION.name(); break; case "ki": ret = MetadataGroupType.CORPORATION.name(); break; case "pi": ret = MetadataGroupType.PERSON.name(); break; case "sa": ret = MetadataGroupType.SUBJECT.name(); break; case "vi": ret = MetadataGroupType.CONFERENCE.name(); break; case "wi": ret = MetadataGroupType.RECORD.name(); break; } if (ret != null) { logger.trace("Authority data type determined from 075$b (gndspec): {}", ret); return ret; } } logger.trace("Authority data type could not be determined for '{}'.", gndspec); return null; } static String generateDublinCoreMetaTags(StructElement structElement); static String generateHighwirePressMetaTags(StructElement structElement, List<PhysicalElement> pages); static String generateRIS(StructElement structElement); static String convertLanguageToIso2(String language); static String applyReplaceRules(String value, List<MetadataReplaceRule> replaceRules, String pi); static String findMetadataGroupType(String gndspec); static SolrDocumentList getGroupedMetadata(String iddoc, String subQuery); }### Answer: @Test public void findMetadataGroupType_shouldMapValuesCorrectly() throws Exception { Assert.assertEquals(MetadataGroupType.CORPORATION.name(), MetadataTools.findMetadataGroupType("kiz")); Assert.assertEquals(MetadataGroupType.PERSON.name(), MetadataTools.findMetadataGroupType("piz")); Assert.assertEquals(MetadataGroupType.SUBJECT.name(), MetadataTools.findMetadataGroupType("saa")); Assert.assertEquals(MetadataGroupType.CONFERENCE.name(), MetadataTools.findMetadataGroupType("viz")); Assert.assertEquals(MetadataGroupType.RECORD.name(), MetadataTools.findMetadataGroupType("wiz")); }
### Question: MetadataTools { public static String convertLanguageToIso2(String language) { if (language == null) { return null; } if (language.length() == 3) { Language lang = null; try { lang = DataManager.getInstance().getLanguageHelper().getLanguage(language); } catch (IllegalArgumentException e) { logger.warn("No language found for " + lang); } if (lang != null) { return lang.getIsoCodeOld(); } } switch (language.toLowerCase()) { case "english": return "en"; case "deutsch": case "deu": case "ger": return "de"; case "französisch": case "franz.": case "fra": case "fre": return "fr"; } return language; } static String generateDublinCoreMetaTags(StructElement structElement); static String generateHighwirePressMetaTags(StructElement structElement, List<PhysicalElement> pages); static String generateRIS(StructElement structElement); static String convertLanguageToIso2(String language); static String applyReplaceRules(String value, List<MetadataReplaceRule> replaceRules, String pi); static String findMetadataGroupType(String gndspec); static SolrDocumentList getGroupedMetadata(String iddoc, String subQuery); }### Answer: @Test public void convertLanguageToIso2_shouldReturnOriginalValueIfLanguageNotFound() throws Exception { Assert.assertEquals("###", MetadataTools.convertLanguageToIso2("###")); }