method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ShadowResources { @NonNull public int[] getIntArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<Integer>> intArrayMap = getResourceIntArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (intArrayMap.containsKey(name)) { List<Integer> intList = intArrayMap.get(name); int[] intArray = new int[intList.size()]; for (int i = 0; i < intList.size(); i++) { intArray[i] = intList.get(i); } return intArray; } } return new int[0]; } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }### Answer:
@Test public void getIntArray() { int[] intArray = resources.getIntArray(R.array.intArray); Assert.assertEquals(0, intArray[0]); Assert.assertEquals(1, intArray[1]); int[] intArrayNoItem = resources.getIntArray(R.array.intArrayNoItem); Assert.assertEquals(0, intArrayNoItem.length); } |
### Question:
ShadowResources { public String getPackageName() { if (!TextUtils.isEmpty(mPackageName)) { return mPackageName; } String manifestPath = "build/intermediates/bundles/debug/AndroidManifest.xml"; if (!new File(manifestPath).exists()) { manifestPath = "build/intermediates/bundles/release/AndroidManifest.xml"; } FileReader reader = new FileReader(); if (new File(manifestPath).exists()) { String manifest = reader.readString(manifestPath); Element body = Jsoup.parse(manifest).body(); String packageName = body.childNode(0).attr("package"); return mPackageName = packageName; } else { manifestPath = "build/intermediates/manifest/androidTest/debug/AndroidManifest.xml"; String manifest = reader.readString(manifestPath); Element body = Jsoup.parse(manifest).body(); String packageName = body.childNode(0).attr("package"); packageName = packageName.substring(0, packageName.length() - ".test".length()); return mPackageName = packageName; } } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }### Answer:
@Test public void getPackageName() throws Exception { Assert.assertEquals("net.kb.test.library", resources.getPackageName()); } |
### Question:
KbSqlParserManager { public Statement parse(String sql) throws JSQLParserException { sql = sql.trim(); boolean isInsertOrReplace = false; if (sql.toUpperCase().startsWith("INSERT OR REPLACE")) { isInsertOrReplace = true; String[] sqlParts = new String[2]; sqlParts[0] = sql.substring(0, "INSERT OR REPLACE".length()); sqlParts[1] = sql.substring("INSERT OR REPLACE".length(), sql.length()); sqlParts[0] = sqlParts[0].toUpperCase().replace("INSERT OR REPLACE", "INSERT"); sql = sqlParts[0] + sqlParts[1]; } CCJSqlParser parser = new CCJSqlParser(new StringReader(sql)); try { Statement statement = parser.Statement(); if (isInsertOrReplace && statement instanceof Insert) { statement = new InsertOrReplaceProxy().getInstance(Insert.class, (Insert) statement); } return statement; } catch (Exception ex) { throw new JSQLParserException(ex); } } Statement parse(String sql); }### Answer:
@Test public void parse() throws Exception { String sql = "INSERT or replace INTO person (id, name) VALUES (?, ?)"; Insert insert = (Insert) new KbSqlParserManager().parse(sql); Assert.assertEquals("INSERT OR REPLACE INTO person (id, name) VALUES (?, ?)", insert.toString()); } |
### Question:
KbSqlParser { protected static int getBindArgsCount(String sql) { Set<Expression> expressionSet = findBindArgsExpressions(sql); int count = 0; for (Expression expression : expressionSet) { count += getBindArgsCount(expression); } return count; } static String bindArgs(String sql, @Nullable Object[] bindArgs); static Object[] replaceBoolean(Object[] bindArgs); }### Answer:
@Test public void getBindArgsCount() throws Exception { String sql0 = "select * from person where id=? and (uid BETWEEN ? and ?) and test LIKE ? order by id"; String sql1 = "INSERT INTO person (id, name) VALUES (?, ?)"; String sql2 = "DELETE FROM person WHERE id in (?,?)"; String sql3 = "UPDATE person SET name = ? WHERE id = ?"; Assert.assertEquals(4, KbSqlParser.getBindArgsCount(sql0)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql1)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql2)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql3)); } |
### Question:
KbSqlParser { protected static Set<Expression> findBindArgsExpressions(String sql) { if (sql == null || sql.startsWith("PRAGMA") || !sql.contains("?")) { return new LinkedHashSet<>(); } KbSqlParserManager pm = new KbSqlParserManager(); try { Statement statement = pm.parse(sql); Set<Expression> expressionSet = findBindArgsExpressions(statement); return expressionSet; } catch (JSQLParserException e) { e.printStackTrace(); } return new LinkedHashSet<>(); } static String bindArgs(String sql, @Nullable Object[] bindArgs); static Object[] replaceBoolean(Object[] bindArgs); }### Answer:
@Test public void findJdbcParamExpressions() throws Exception { String sql = "DELETE FROM person WHERE id = ?"; Set<Expression> expressionSet = KbSqlParser.findBindArgsExpressions(sql); System.out.println(); } |
### Question:
ShadowContext implements Shadow { public static void deleteAllTempDir() { FileUtils.deletePath(DB_PATH); FileUtils.deletePath(DATA_DIR); FileUtils.deletePath(EXT_DIR); } ShadowContext(Resources resources); @NonNull final String getString(@StringRes int resId); Resources getResources(); SharedPreferences getSharedPreferences(String name, int mode); Context getApplicationContext(); AssetManager getAssets(); File getDatabasePath(String name); String[] databaseList(); static String getDbDir(); File getDataDir(); File getFilesDir(); File getFileStreamPath(String name); File getCacheDir(); File getCodeCacheDir(); File getNoBackupFilesDir(); File getExtDir(); File getExternalCacheDir(); @Nullable File getExternalFilesDir(@Nullable String type); String[] fileList(); String getPackageResourcePath(); String getPackageCodePath(); static void deleteAllTempDir(); void putSQLiteDatabase(String name, SQLiteDatabase db); SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory); @TargetApi(Build.VERSION_CODES.JELLY_BEAN) SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler); boolean deleteDatabase(String name); Map<String, SQLiteDatabase> getDbMap(); @Override String toString(); @Override void setProxyObject(Object proxyObject); static final String DB_PATH; }### Answer:
@Test public void deleteAllTempDir() throws Exception { ShadowContext.deleteAllTempDir(); } |
### Question:
NoOpWorkflowImpl implements NoOpWorkflow { @Override public void run() { System.out.println("Run called"); run(0); } @Override void run(); }### Answer:
@Test public void testRun() { context.checking( new Expectations() { { exactly(3).of(control).createDatabaseName("test"); will(returnValue("bbb")); } }); new NoOpWorkflowClientFactoryImpl().getClient("test").run(); } |
### Question:
UriBuilderImpl extends UriBuilder { @Override public UriBuilder replaceQueryParam(String name, Object... values) { checkSsp(); if (queryParams == null) { queryParams = UriComponent.decodeQuery(query.toString(), false); query.setLength(0); } name = encode(name, UriComponent.Type.QUERY_PARAM); queryParams.remove(name); if (values == null) { return this; } for (Object value : values) { if (value == null) { throw new IllegalArgumentException("One or more of query value parameters are null"); } queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM)); } return this; } UriBuilderImpl(); private UriBuilderImpl(UriBuilderImpl that); @Override UriBuilder clone(); @Override UriBuilder uri(URI uri); @Override UriBuilder scheme(String scheme); @Override UriBuilder schemeSpecificPart(String ssp); @Override UriBuilder userInfo(String ui); @Override UriBuilder host(String host); @Override UriBuilder port(int port); @Override UriBuilder replacePath(String path); @Override UriBuilder path(String path); @Override UriBuilder path(Class resource); @Override UriBuilder path(Class resource, String methodName); @Override UriBuilder path(Method method); @Override UriBuilder segment(String... segments); @Override UriBuilder replaceMatrix(String matrix); @Override UriBuilder matrixParam(String name, Object... values); @Override UriBuilder replaceMatrixParam(String name, Object... values); @Override UriBuilder replaceQuery(String query); @Override UriBuilder queryParam(String name, Object... values); @Override UriBuilder replaceQueryParam(String name, Object... values); @Override UriBuilder fragment(String fragment); @Override URI buildFromMap(Map<String, ? extends Object> values); @Override URI buildFromEncodedMap(Map<String, ? extends Object> values); @Override URI build(Object... values); @Override URI buildFromEncoded(Object... values); }### Answer:
@Test public void testReplaceQueryParam() { URI uri = new UriBuilderImpl().path("http: assertEquals("http: } |
### Question:
DemoAO { public void hello(String name) throws FileNotFoundException { System.out.println(demoService.sayHello(name)); } void hello(String name); }### Answer:
@Test public void testHello() throws FileNotFoundException { demoAO.hello("抠逼阵儿"); } |
### Question:
ClipboardModule extends ContextBaseJavaModule { @SuppressLint("DeprecatedMethod") @ReactMethod public void setString(String text) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ClipData clipdata = ClipData.newPlainText(null, text); ClipboardManager clipboard = getClipboardService(); clipboard.setPrimaryClip(clipdata); } else { ClipboardManager clipboard = getClipboardService(); clipboard.setText(text); } } ClipboardModule(Context context); @Override String getName(); @ReactMethod void getString(Promise promise); @SuppressLint("DeprecatedMethod") @ReactMethod void setString(String text); }### Answer:
@Test public void testSetString() { mClipboardModule.setString(TEST_CONTENT); assertTrue(mClipboardManager.getText().equals(TEST_CONTENT)); mClipboardModule.setString(null); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(""); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(" "); assertTrue(mClipboardManager.hasText()); } |
### Question:
PdfParser { static List<String> extractTextLinesFromPdf(InputStream pdfStream) { PdfReader pdfReader = null; try { pdfReader = new PdfReader(pdfStream); List<String> textLines = new ArrayList<>(); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { String textFromPage = PdfTextExtractor.getTextFromPage(pdfReader, page); String[] linesFromPage = textFromPage.split("\n"); for (String lineFromPage : linesFromPage) { lineFromPage = lineFromPage.trim(); int previousLength; do { previousLength = lineFromPage.length(); lineFromPage = lineFromPage.replaceAll(" ", " "); } while (previousLength != lineFromPage.length()); if (isTextLinePdfParsingJunk(lineFromPage)) continue; textLines.add(lineFromPage); } } return textLines; } catch (IOException e) { throw new UncheckedIOException(e); } finally { if (pdfReader != null) pdfReader.close(); } } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }### Answer:
@Test public void extractTextLinesFromPdf_ffsClaims() throws IOException { try (InputStream codebookPdfStream = SupportedCodebook.FFS_CLAIMS.getCodebookPdfInputStream();) { List<String> codebookTextLines = PdfParser.extractTextLinesFromPdf(codebookPdfStream); Assert.assertNotNull(codebookTextLines); Assert.assertTrue(codebookTextLines.size() > 100); } } |
### Question:
PdfParser { static String parseLabel(List<String> variableSection) { List<String> fieldText = extractFieldContent(variableSection, FIELD_NAME_LABEL, FIELD_NAME_LABEL_ALT1); List<String> fieldParagraphs = extractParagraphs(fieldText); if (fieldParagraphs.size() != 1) throw new IllegalStateException( String.format("Invalid '%s' field in variable section: %s", FIELD_NAME_LABEL, variableSection)); return fieldParagraphs.get(0); } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }### Answer:
@Test public void parseLabel_multiline() { String[] variableSection = new String[] { "CLM_NEXT_GNRTN_ACO_IND_CD1", "LABEL: Claim Next Generation (NG) Accountable Care Organization (ACO) Indicator Code –", "Population-Based Payment (PBP)", "DESCRIPTION: The field identifies the claims that qualify for specific claims processing edits" + " related to", }; String parsedLabel = PdfParser.parseLabel(Arrays.asList(variableSection)); Assert.assertEquals( "Claim Next Generation (NG) Accountable Care Organization (ACO) Indicator Code – Population-Based" + " Payment (PBP)", parsedLabel); } |
### Question:
DatabaseSchemaManager { public static void createOrUpdateSchema(DataSource dataSource) { LOGGER.info("Schema create/upgrade: running..."); Flyway flyway = new Flyway(); flyway.setCleanDisabled(true); flyway.setDataSource(dataSource); flyway.setPlaceholders(createScriptPlaceholdersMap(dataSource)); flyway.migrate(); LOGGER.info("Schema create/upgrade: complete."); } static void createOrUpdateSchema(DataSource dataSource); static void dropIndexes(DataSource dataSource); }### Answer:
@Test public void createOrUpdateSchemaOnHsql() { JDBCDataSource hsqlDataSource = new JDBCDataSource(); hsqlDataSource.setUrl("jdbc:hsqldb:mem:test"); DatabaseSchemaManager.createOrUpdateSchema(hsqlDataSource); } |
### Question:
CommandContext { public boolean hasFlag(char ch) { return booleanFlags.contains(ch) || valueFlags.containsKey(ch); } 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 testFlagsAnywhere() { try { CommandContext context = new CommandContext("r hello -f"); assertTrue(context.hasFlag('f')); CommandContext context2 = new CommandContext("r hello -f world"); assertTrue(context2.hasFlag('f')); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } } |
### Question:
Location { public Location setY(double y) { return new Location(extent, position.withY(y), 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 testSetY() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setY(TEST_VALUE); assertEquals(0, location1.getY(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getY(), EPSILON); assertEquals(0, location2.getZ(), EPSILON); } |
### Question:
Location { public double getZ() { return position.getZ(); } 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 testGetZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getZ(), EPSILON); } |
### Question:
Location { public int getBlockZ() { return (int) Math.floor(position.getZ()); } 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 testGetBlockZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getBlockZ()); } |
### Question:
Location { public Location setZ(double z) { return new Location(extent, position.withZ(z), 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 testSetZ() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setZ(TEST_VALUE); assertEquals(0, location1.getZ(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(0, location2.getY(), EPSILON); assertEquals(TEST_VALUE, location2.getZ(), EPSILON); } |
### Question:
MorePaths { public static Stream<Path> iterPaths(Path path) { Deque<Path> parents = new ArrayDeque<>(path.getNameCount()); Path next = path; while (next != null) { parents.addFirst(next); next = next.getParent(); } return ImmutableList.copyOf(parents).stream(); } private MorePaths(); static Comparator<Path> oldestFirst(); static Comparator<Path> newestFirst(); static Stream<Path> iterPaths(Path path); static Spliterator<Path> optimizedSpliterator(Path path); }### Answer:
@Test void testRelative() { assertEquals( paths("a", "a/b", "a/b/c"), MorePaths.iterPaths(Paths.get("a/b/c")).collect(toList()) ); }
@Test void testAbsolute() { assertEquals( paths("/", "/a", "/a/b", "/a/b/c"), MorePaths.iterPaths(Paths.get("/a/b/c")).collect(toList()) ); }
@Test void testEmpty() { assertEquals( paths(""), MorePaths.iterPaths(Paths.get("")).collect(toList()) ); }
@Test void testJustFile() { assertEquals( paths("a"), MorePaths.iterPaths(Paths.get("a")).collect(toList()) ); } |
### 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:
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 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:
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:
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 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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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("###")); } |
### Question:
Comment implements Comparable<Comment> { public boolean mayEdit(User user) { return owner.getId() != null && user != null && owner.getId() == user.getId(); } Comment(); Comment(String pi, int page, User owner, String text, Comment parent); @Override int compareTo(Comment o); static boolean sendEmailNotifications(Comment comment, String oldText, Locale locale); boolean mayEdit(User user); String getDisplayDate(Date date); void checkAndCleanScripts(); Long getId(); void setId(Long id); String getPi(); void setPi(String pi); Integer getPage(); void setPage(Integer page); User getOwner(); void setOwner(User owner); void setText(String text); String getText(); String getDisplayText(); String getOldText(); Date getDateCreated(); void setDateCreated(Date dateCreated); Date getDateUpdated(); void setDateUpdated(Date dateUpdated); }### Answer:
@Test public void mayEdit_shouldReturnFalseIfOwnerIdIsNull() throws Exception { User owner = new User(); Comment comment = new Comment("PPN123", 1, owner, "comment text", null); Assert.assertFalse(comment.mayEdit(owner)); }
@Test public void mayEdit_shouldReturnFalseIfUserIsNull() throws Exception { User owner = new User(); Comment comment = new Comment("PPN123", 1, owner, "comment text", null); Assert.assertFalse(comment.mayEdit(null)); } |
### Question:
TEITools { public static String getTeiFulltext(String tei) throws JDOMException, IOException { if (tei == null) { return null; } Document doc = XmlTools.getDocumentFromString(tei, StringTools.DEFAULT_ENCODING); if (doc == null) { return null; } if (doc.getRootElement() != null) { Element eleText = doc.getRootElement().getChild("text", null); if (eleText != null && eleText.getChild("body", null) != null) { String language = eleText.getAttributeValue("lang", Namespace.getNamespace("xml", "http: Element eleBody = eleText.getChild("body", null); Element eleNewRoot = new Element("tempRoot"); for (Element ele : eleBody.getChildren()) { eleNewRoot.addContent(ele.clone()); } String ret = XmlTools.getStringFromElement(eleNewRoot, null).replace("<tempRoot>", "").replace("</tempRoot>", "").trim(); ret = ret.replaceAll("<note>[\\s\\S]*?<\\/note>", ""); return ret; } } return null; } static String getTeiFulltext(String tei); static String convertTeiToHtml(String tei); }### Answer:
@Test public void getTeiFulltext_shouldExtractFulltextCorrectly() throws Exception { Path path = Paths.get("src/test/resources/data/viewer/tei/DE_2013_Riedel_PolitikUndCo_241__248/DE_2013_Riedel_PolitikUndCo_241__248_eng.xml"); Assert.assertTrue(Files.isRegularFile(path)); String tei = FileTools.getStringFromFile(path.toFile(), StringTools.DEFAULT_ENCODING); Assert.assertFalse(StringUtils.isEmpty(tei)); Assert.assertTrue(tei.contains("<note>")); String text = TEITools.getTeiFulltext(tei); Assert.assertFalse(StringUtils.isEmpty(text)); Assert.assertFalse(text.contains("<note>")); } |
### Question:
ALTOTools { public static String getFulltext(Path path, String encoding) throws IOException { String altoString = FileTools.getStringFromFile(path.toFile(), encoding); return getFullText(altoString, false, null); } static String getFulltext(Path path, String encoding); static String getFullText(String alto, boolean mergeLineBreakWords, HttpServletRequest request); static List<TagCount> getNERTags(String alto, NERTag.Type type); static List<String> getWordCoords(String altoString, Set<String> searchTerms); static String getRotatedCoordinates(String coords, int rotation, Dimension pageSize); static List<String> getWordCoords(String altoString, Set<String> searchTerms, int rotation); static int getMatchALTOWord(Word eleWord, String[] words); static String getALTOCoords(GeometricData element); static final String TAG_LABEL_IGNORE_REGEX; }### Answer:
@Test public void getFullText_shouldExtractFulltextCorrectly() throws Exception { File file = new File("src/test/resources/data/viewer/data/1/alto/00000010.xml"); Assert.assertTrue(file.isFile()); String text = ALTOTools.getFulltext(file.toPath(), "utf-8"); Assert.assertNotNull(text); Assert.assertTrue(text.length() > 100); } |
### Question:
CMSSidebarElement { protected static String cleanupHtmlTag(String tag) { Matcher m2 = patternHtmlAttribute.matcher(tag); while (m2.find()) { String attribute = m2.group(); tag = tag.replace(attribute, ""); } tag = tag.replace("</", "<").replace("/>", ">").replace(" ", ""); return tag; } CMSSidebarElement(); CMSSidebarElement(CMSSidebarElement original, CMSPage owner); static CMSSidebarElement copy(CMSSidebarElement original, CMSPage ownerPage); int compareTo(Object o); @Override int hashCode(); @Override boolean equals(Object o); String getHtml(); void setHtml(String html); Long getId(); void setId(Long id); CMSPage getOwnerPage(); void setOwnerPage(CMSPage ownerPage); String getType(); void setType(String type); String getValue(); void setValue(String value); int getOrder(); void setOrder(int order); String getContent(); boolean hasHtml(); WidgetMode getWidgetMode(); void setWidgetMode(WidgetMode widgetMode); String getCssClass(); void setCssClass(String className); boolean isValid(); SidebarElementType.Category getCategory(); @Override String toString(); int getSortingId(); PageList getLinkedPages(); void setLinkedPages(PageList linkedPages); String getLinkedPagesString(); void setLinkedPagesString(String linkedPagesList); void serialize(); void deSerialize(); Long getGeoMapId(); void setGeoMapId(Long geoMapId); void setGeoMap(GeoMap geoMap); synchronized GeoMap getGeoMap(); String getWidgetTitle(); void setWidgetTitle(String widgetTitle); boolean isHasWidgetTitle(); boolean isHasLinkedPages(); String getWidgetType(); }### Answer:
@Test public void cleanupHtmlTag_shouldRemoveAttributesCorrectly() throws Exception { Assert.assertEquals("<tag>", CMSSidebarElement.cleanupHtmlTag("<tag attribute=\"value\" attribute=\"value\" >")); }
@Test public void cleanupHtmlTag_shouldRemoveClosingTagCorrectly() throws Exception { Assert.assertEquals("<tag>", CMSSidebarElement.cleanupHtmlTag("<tag />")); } |
### Question:
FileTools { public static String getStringFromFile(File file, String encoding) throws FileNotFoundException, IOException { return getStringFromFile(file, encoding, null); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getStringFromFile_shouldReadTextFileCorrectly() throws Exception { File file = new File("src/test/resources/stopwords.txt"); Assert.assertTrue(file.isFile()); String contents = FileTools.getStringFromFile(file, null); Assert.assertTrue(StringUtils.isNotBlank(contents)); }
@Test(expected = FileNotFoundException.class) public void getStringFromFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.getStringFromFile(file, null); } |
### Question:
FileTools { public static String getStringFromFilePath(String filePath) throws FileNotFoundException, IOException { return getStringFromFile(new File(filePath), null); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getStringFromFilePath_shouldReadTextFileCorrectly() throws Exception { String contents = FileTools.getStringFromFilePath("src/test/resources/stopwords.txt"); Assert.assertTrue(StringUtils.isNotBlank(contents)); }
@Test(expected = FileNotFoundException.class) public void getStringFromFilePath_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.getStringFromFilePath(file.getPath()); } |
### Question:
FileTools { public static void compressGzipFile(File file, File gzipFile) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(gzipFile); GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) { byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { gzipOS.write(buffer, 0, len); } } } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test(expected = FileNotFoundException.class) public void compressGzipFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File file = new File("notfound.txt"); Assert.assertFalse(file.exists()); FileTools.compressGzipFile(file, new File("target/test.tar.gz")); } |
### Question:
FileTools { public static void decompressGzipFile(File gzipFile, File newFile) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(gzipFile); GZIPInputStream gis = new GZIPInputStream(fis); FileOutputStream fos = new FileOutputStream(newFile)) { byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test(expected = FileNotFoundException.class) public void decompressGzipFile_shouldThrowFileNotFoundExceptionIfFileNotFound() throws Exception { File gzipFile = new File("notfound.tar.gz"); Assert.assertFalse(gzipFile.exists()); FileTools.decompressGzipFile(gzipFile, new File("target/target.bla")); } |
### Question:
FileTools { public static File getFileFromString(String string, String filePath, String encoding, boolean append) throws IOException { if (string == null) { throw new IllegalArgumentException("string may not be null"); } if (encoding == null) { encoding = StringTools.DEFAULT_ENCODING; } File file = new File(filePath); try (FileWriterWithEncoding writer = new FileWriterWithEncoding(file, encoding, append)) { writer.write(string); } return file; } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getFileFromString_shouldWriteFileCorrectly() throws Exception { Assert.assertTrue(tempDir.mkdirs()); File file = new File(tempDir, "temp.txt"); String text = "Lorem ipsum dolor sit amet"; FileTools.getFileFromString(text, file.getAbsolutePath(), null, false); Assert.assertTrue(file.isFile()); } |
### Question:
FileTools { public static String getCharset(InputStream input) throws IOException { CharsetDetector cd = new CharsetDetector(); try (BufferedInputStream bis = new BufferedInputStream(input)) { cd.setText(bis); CharsetMatch cm = cd.detect(); if (cm != null) { return cm.getName(); } } return null; } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getCharset_shouldDetectCharsetCorrectly() throws Exception { File file = new File("src/test/resources/stopwords.txt"); try (FileInputStream fis = new FileInputStream(file)) { Assert.assertEquals("UTF-8", FileTools.getCharset(fis)); } } |
### Question:
FileTools { public static String getBottomFolderFromPathString(String pathString) { if (StringUtils.isBlank(pathString)) { return ""; } Path path = Paths.get(pathString); return path.getParent() != null ? path.getParent().getFileName().toString() : ""; } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getBottomFolderFromPathString_shouldReturnFolderNameCorrectly() throws Exception { Assert.assertEquals("PPN123", FileTools.getBottomFolderFromPathString("data/1/alto/PPN123/00000001.xml")); }
@Test public void getBottomFolderFromPathString_shouldReturnEmptyStringIfNoFolderInPath() throws Exception { Assert.assertEquals("", FileTools.getBottomFolderFromPathString("00000001.xml")); } |
### Question:
FileTools { public static String getFilenameFromPathString(String pathString) { if (StringUtils.isBlank(pathString)) { return ""; } Path path = getPathFromUrlString(pathString); return path.getFileName().toString(); } static String getStringFromFilePath(String filePath); static String getStringFromFile(File file, String encoding); static String getStringFromFile(File file, String encoding, String convertToEncoding); static String getCharset(InputStream input); static String getCharset(String input); static String getStringFromByteArray(byte[] bytes, String encoding); static File getFileFromString(String string, String filePath, String encoding, boolean append); static void decompressGzipFile(File gzipFile, File newFile); static void compressGzipFile(File file, File gzipFile); static void compressZipFile(List<File> files, File zipFile, Integer level); static void compressZipFile(Map<Path, String> contentMap, File zipFile, Integer level); static boolean checkPathExistance(Path path, boolean create); static void copyStream(OutputStream output, InputStream input); static boolean isFolderEmpty(final Path folder); static String adaptPathForWindows(String path); static String probeContentType(URI uri); static String probeContentType(String content); static String getCharset(Path file); static String getBottomFolderFromPathString(String pathString); static String getFilenameFromPathString(String pathString); static Path getPathFromUrlString(String urlString); static FilenameFilter filenameFilterXML; }### Answer:
@Test public void getFilenameFromPathString_shouldReturnFileNameCorrectly() throws Exception { Assert.assertEquals("00000001.xml", FileTools.getFilenameFromPathString("data/1/alto/PPN123/00000001.xml")); } |
### Question:
LanguageHelper { public Language getLanguage(String isoCode) { SubnodeConfiguration languageConfig = null; try { if (isoCode.length() == 3) { List<HierarchicalConfiguration> nodes = config.configurationsAt("language[iso_639-2=\"" + isoCode + "\"]"); if (nodes.isEmpty()) { nodes = config.configurationsAt("language[iso_639-2T=\"" + isoCode + "\"]"); } if (nodes.isEmpty()) { nodes = config.configurationsAt("language[iso_639-2B=\"" + isoCode + "\"]"); } languageConfig = (SubnodeConfiguration) nodes.get(0); } else if (isoCode.length() == 2) { languageConfig = (SubnodeConfiguration) config.configurationsAt("language[iso_639-1=\"" + isoCode + "\"]").get(0); } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("No matching language found for " + isoCode); } catch (Throwable e) { throw new IllegalArgumentException(e); } if (languageConfig == null) { throw new IllegalArgumentException("No matching language found for " + isoCode); } Language language = createLanguage(languageConfig); return language; } LanguageHelper(String configFilePath); List<Language> getAllLanguages(); List<Language> getMajorLanguages(); Language getLanguage(String isoCode); Language createLanguage(HierarchicalConfiguration languageConfig); }### Answer:
@Test public void test() { LanguageHelper helper = new LanguageHelper("languages.xml"); Assert.assertNotNull(helper.getLanguage("fra")); Assert.assertNotNull(helper.getLanguage("fre")); Assert.assertNotNull(helper.getLanguage("fr")); } |
### Question:
DataFileTools { static String getDataRepositoryPath(String dataRepositoryPath) { if (StringUtils.isBlank(dataRepositoryPath)) { return DataManager.getInstance().getConfiguration().getViewerHome(); } if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryPath)).isAbsolute()) { return dataRepositoryPath + '/'; } return DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + dataRepositoryPath + '/'; } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForEmptyDataRepository() throws Exception { Assert.assertEquals(DataManager.getInstance().getConfiguration().getViewerHome(), DataFileTools.getDataRepositoryPath(null)); }
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForDataRepositoryName() throws Exception { Assert.assertEquals(DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + "1/", DataFileTools.getDataRepositoryPath("1")); }
@Test public void getDataRepositoryPath_shouldReturnCorrectPathForAbsoluteDataRepositoryPath() throws Exception { Assert.assertEquals("/opt/digiverso/viewer/1/", DataFileTools.getDataRepositoryPath("/opt/digiverso/viewer/1")); } |
### Question:
DataFileTools { static String sanitizeFileName(String fileName) { if (StringUtils.isBlank(fileName)) { return fileName; } return Paths.get(fileName).getFileName().toString(); } static String getDataRepositoryPathForRecord(String pi); static Path getMediaFolder(String pi); static Map<String, Path> getDataFolders(String pi, String... dataFolderNames); static Path getDataFolder(String pi, String dataFolderName); static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder); static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName); static Path getDataFilePath(String pi, String relativeFilePath); static String getSourceFilePath(String fileName, String format); static String getSourceFilePath(String fileName, String dataRepository, String format); static String getTextFilePath(String pi, String fileName, String format); static Path getTextFilePath(String pi, String relativeFilePath); static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords,
HttpServletRequest request); static String loadAlto(String altoFilePath); static String loadTei(String pi, String language); }### Answer:
@Test public void sanitizeFileName_shouldRemoveEverythingButTheFileNameFromGivenPath() throws Exception { Assert.assertEquals("foo.bar", DataFileTools.sanitizeFileName("/opt/digiverso/foo.bar")); Assert.assertEquals("foo.bar", DataFileTools.sanitizeFileName("../../foo.bar")); Assert.assertEquals("foo.bar", DataFileTools.sanitizeFileName("/foo.bar")); } |
### Question:
CMSStaticPage { public String getPageName() { return pageName; } CMSStaticPage(); CMSStaticPage(String name); @SuppressWarnings("deprecation") CMSStaticPage(CMSPage cmsPage); Optional<CMSPage> getCmsPageOptional(); CMSPage getCmsPage(); void setCmsPage(CMSPage cmsPage); Long getId(); String getPageName(); boolean isLanguageComplete(Locale locale); boolean isHasCmsPage(); Optional<Long> getCmsPageId(); void setCmsPageId(Long cmsPageId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetPageName() { Assert.assertEquals("test", page.getPageName()); } |
### Question:
NetTools { protected static String parseMultipleIpAddresses(String address) { if (address == null) { throw new IllegalArgumentException("address may not be null"); } if (address.contains(",")) { String[] addressSplit = address.split(","); if (addressSplit.length > 0) { address = addressSplit[addressSplit.length - 1].trim(); } } return address; } static String[] callUrlGET(String url); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@Test public void parseMultipleIpAddresses_shouldFilterMultipleAddressesCorrectly() throws Exception { Assert.assertEquals("3.3.3.3", NetTools.parseMultipleIpAddresses("1.1.1.1, 2.2.2.2, 3.3.3.3")); } |
### Question:
NetTools { public static String scrambleEmailAddress(String email) { if (StringUtils.isEmpty(email)) { return email; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < email.length(); ++i) { if (i > 2 && i < email.length() - 3) { sb.append('*'); } else { sb.append(email.charAt(i)); } } return sb.toString(); } static String[] callUrlGET(String url); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@Test public void scrambleEmailAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("foo*****com", NetTools.scrambleEmailAddress("[email protected]")); } |
### Question:
NetTools { public static String scrambleIpAddress(String address) { if (StringUtils.isEmpty(address)) { return address; } String[] addressSplit = address.split("[.]"); if (addressSplit.length == 4) { return addressSplit[0] + "." + addressSplit[1] + ".X.X"; } return address; } static String[] callUrlGET(String url); static String getWebContentGET(String urlString); static String getWebContentPOST(String url, Map<String, String> params, Map<String, String> cookies); static boolean postMail(List<String> recipients, String subject, String body); static String getIpAddress(HttpServletRequest request); static String scrambleEmailAddress(String email); static String scrambleIpAddress(String address); static boolean isIpAddressLocalhost(String address); static final String ADDRESS_LOCALHOST_IPV4; static final String ADDRESS_LOCALHOST_IPV6; }### Answer:
@Test public void scrambleIpAddress_shouldModifyStringCorrectly() throws Exception { Assert.assertEquals("192.168.X.X", NetTools.scrambleIpAddress("192.168.0.1")); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.