method2testcases
stringlengths
118
6.63k
### Question: OptionImpl implements Option { public String toString() { StringBuffer result = new StringBuffer(getName() + " [ "); getAttributeNames().forEach(key -> result.append(key + "=\"" + getString(key) + "\" ")); result.append("]"); return result.toString(); } OptionImpl(String name); OptionImpl(String name, Map<String, String> map); String getName(); OptionImpl addMap(Map<String, String> map); OptionImpl addAttribute(String name, String value); boolean containsAttribute(String name); String getAttribute(String name); int getAttributeAsInteger(String name); Set<String> getAttributeNames(); Map<String, String> getAttributeMap(); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); E getEnum(String name, Class<E> type); String toString(); }### Answer: @Test public void testToString() { option = new OptionImpl("option"); option.addAttribute("key", "value"); Assert.assertEquals("option [ key=\"value\" ]", option.toString()); }
### Question: OptionImpl implements Option { public int getAttributeAsInteger(String name) { return Integer.valueOf(attributeMap.get(name)); } OptionImpl(String name); OptionImpl(String name, Map<String, String> map); String getName(); OptionImpl addMap(Map<String, String> map); OptionImpl addAttribute(String name, String value); boolean containsAttribute(String name); String getAttribute(String name); int getAttributeAsInteger(String name); Set<String> getAttributeNames(); Map<String, String> getAttributeMap(); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); E getEnum(String name, Class<E> type); String toString(); }### Answer: @Test public void testGetAttributeAsInteger() { option = new OptionImpl("option"); option.addAttribute("key", "1"); Assert.assertEquals(1, option.getAttributeAsInteger("key")); }
### Question: OptionImpl implements Option { public boolean containsAttribute(String name) { return attributeMap.containsKey(name); } OptionImpl(String name); OptionImpl(String name, Map<String, String> map); String getName(); OptionImpl addMap(Map<String, String> map); OptionImpl addAttribute(String name, String value); boolean containsAttribute(String name); String getAttribute(String name); int getAttributeAsInteger(String name); Set<String> getAttributeNames(); Map<String, String> getAttributeMap(); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); E getEnum(String name, Class<E> type); String toString(); }### Answer: @Test public void testContainsAttribute() { option.getAttributeMap().clear(); option.addMap(OptionData.getAttributesMap()); Assert.assertEquals(true, option.containsAttribute("attribute-1")); }
### Question: OptionsImpl implements Options { public void addOption(Option option) { optionsMap.put(option.getName(), option); } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testAddOption() { options.addOption(getOption()); Assert.assertEquals(getOption().getName(), options.getOption("testOption").getName()); }
### Question: XHTML { public static String getAttr(String tag, String attr) { String value = ""; Pattern p = Pattern.compile(getAttributeExpression(attr)); Matcher m = p.matcher(tag); if (m.find()) { value = m.group(1); } return value; } static String removeAttr(String tag, String attr); static String setAttr(String tag, String attr, String value); static String getBody(String tag, String content); static String setBody(String tag, String value); static String getAttr(String tag, String attr); static String getTag(String tag); }### Answer: @Test public void testGetAttr() { String content = "<a href=\"http: String attr = "href"; String expResult = "http: String result = XHTML.getAttr(content, attr); assertEquals(expResult, result); content = "<a href=\"http: attr = "name"; expResult = ""; result = XHTML.getAttr(content, attr); assertEquals(expResult, result); } @Test public void testGetAttr2() { String result = XHTML.getAttr("<input data-type=\"foobar\" type=\"checkbox\" />", "type"); assertEquals("checkbox", result); }
### Question: OptionsImpl implements Options { public String getOptionValue(String optionName, String attributeName) { Option option = getOption(optionName); return (null == option) ? null : option.getString(attributeName); } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testGetOptionValue() { options.optionsMap.putAll(OptionData.getOptionsMap()); String optionValue = options.getOptionValue("options-4", "attribute-4"); Assert.assertEquals("value-4", optionValue); } @Test public void testGetOptionValueNull() { options.optionsMap.putAll(OptionData.getOptionsMap()); String optionValue = options.getOptionValue("not-exists", "attribute-4"); Assert.assertEquals(null, optionValue); }
### Question: OptionsImpl implements Options { public Integer getInteger(String name, String attribute) { return hasOption(name) ? getOption(name).getInteger(attribute) : null; } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testGetInteger() { options.optionsMap.putAll(OptionData.getOptionsMap()); Assert.assertEquals(Integer.valueOf(6), options.getInteger("options-6", "integer-6")); Assert.assertEquals(Integer.valueOf(-7), options.getInteger("options-7", "integer-7")); Assert.assertNull(options.getInteger("options-4", "attribute-4")); Assert.assertNull(options.getInteger("options-7","not-exists")); }
### Question: OptionsImpl implements Options { public Boolean getBoolean(String name, String attribute) { return hasOption(name) ? getOption(name).getBoolean(attribute) : null; } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testGetBoolean() { options.optionsMap.putAll(OptionData.getOptionsMap()); Assert.assertEquals(Boolean.TRUE, options.getBoolean("options-9", "bool-9")); Assert.assertEquals(Boolean.FALSE, options.getBoolean("options-7", "integer-7")); }
### Question: OptionsImpl implements Options { public <E extends Enum<E>> E getEnum(String name, String attribute, Class<E> type) { return hasOption(name) ? getOption(name).getEnum(attribute, type) : null; } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testGetEnum() { options.optionsMap.putAll(OptionData.getOptionsMap()); Assert.assertEquals(FieldType.TEXT, options.getEnum("options-8", "enum-8", FieldType.class)); Assert.assertNull(options.getEnum("options-7", "integer-7", FieldType.class)); }
### Question: OptionsImpl implements Options { public Set<String> getOptionNames() { return optionsMap.keySet(); } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testGetOptionNames() { options.optionsMap.putAll(OptionData.getOptionsMap()); Set<String> optionsKeys = options.getOptionNames(); Assert.assertEquals(9, optionsKeys.size()); Assert.assertEquals(OptionData.getOptionsMap().keySet(), optionsKeys); }
### Question: OptionsImpl implements Options { public String toString() { StringBuffer result = new StringBuffer(); result.append(optionsMap.values()); return result.toString(); } void addOption(Option option); Option getOption(String name); boolean hasOption(String name); Set<String> getOptionNames(); String getOptionValue(String optionName, String attributeName); String toString(); String getString(String name, String attribute); Integer getInteger(String name, String attribute); Boolean getBoolean(String name, String attribute); E getEnum(String name, String attribute, Class<E> type); }### Answer: @Test public void testToString() { options.optionsMap.clear(); options.optionsMap.put("key", new OptionImpl("value").addAttribute("attr", "attr-value")); String actual = options.toString(); Assert.assertEquals("[value [ attr=\"attr-value\" ]]", actual); }
### Question: MessageSourceChain implements MessageSource { public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { check(); String message = null; for (int i = 0; i < messageSources.length && message == null; i++) { message = messageSources[i].getMessage(code, args, defaultMessage, locale); } return message; } MessageSourceChain(); MessageSourceChain(MessageSource... messageSources); String getMessage(String code, Object[] args, String defaultMessage, Locale locale); String getMessage(String code, Object[] args, Locale locale); String getMessage(MessageSourceResolvable resolvable, Locale locale); MessageSource[] getMessageSources(); void setMessageSources(MessageSource[] messageSources); }### Answer: @Test public void testGetMessage() { Assert.assertEquals(VALUE1, ms.getMessage(KEY1, args, locale)); Assert.assertEquals(VALUE2, ms.getMessage(KEY2, args, locale)); Assert.assertEquals(VALUE3, ms.getMessage(KEY3, args, locale)); } @Test(expected = NoSuchMessageException.class) public void testGetMessageException() { ms.getMessage(KEY4, args, locale); } @Test public void testGetMessageWithDefault() { Assert.assertEquals(VALUE1, ms.getMessage(KEY1, args, defaultMessage, locale)); Assert.assertEquals(VALUE2, ms.getMessage(KEY2, args, defaultMessage, locale)); Assert.assertEquals(VALUE3, ms.getMessage(KEY3, args, defaultMessage, locale)); Assert.assertEquals(VALUE_DEFAULT, ms.getMessage(KEY4, args, defaultMessage, locale)); Assert.assertNull(ms.getMessage(KEY4, args, null, locale)); } @Test public void testGetMessageFromMessageSourceResolvable() { MessageSourceResolvable r1 = getResolvable(KEY1, null); Assert.assertEquals(VALUE1, ms.getMessage(r1, locale)); MessageSourceResolvable r2 = getResolvable(KEY2, null); Assert.assertEquals(VALUE2, ms.getMessage(r2, locale)); MessageSourceResolvable r3 = getResolvable(KEY3, null); Assert.assertEquals(VALUE3, ms.getMessage(r3, locale)); MessageSourceResolvable r4 = getResolvable(KEY4, defaultMessage); Assert.assertEquals(VALUE_DEFAULT, ms.getMessage(r4, locale)); } @Test(expected = NoSuchMessageException.class) public void testGetMessageFromMessageSourceResolvableWithException() { ms.getMessage(getResolvable(KEY4, null), locale); } @Test(expected = UnsupportedOperationException.class) public void testNoMessageSources() { new MessageSourceChain().getMessage(KEY1, args, locale); }
### Question: SortParamSupport { Pageable getPageable(String string) { if (MODE_RESET.equals(string) || StringUtils.endsWith(string, MODE_RESET)) { reset = true; } String key = getSessionKey(); String currentOrder = sessionMap.get(key); Pageable currentParams = parseParamsToPageable(currentOrder, false); Pageable parseParams = parseParamsToPageable(string, true); Pageable mergeOrderParams = mergeOrderParams(currentParams, parseParams); String sortString = getSortString(mergeOrderParams); sessionMap.put(key, sortString); return mergeOrderParams; } SortParamSupport(final Map<String, String> applicationSessionParams, String pageId, String dsId, Integer defaultPageSize); }### Answer: @Test public void testClear() { Mockito.when(sessionMap.get(SESS_PARAM_ID)).thenReturn("lastname:asc;name:desc;id:desc"); Pageable sortParams = sortParamSupport.getPageable("lastname:;name:;id:"); Assert.assertNull(sortParams.getSort()); }
### Question: XSSUtil { public String stripXss(String parameter) { if (null == parameter) { return parameter; } return Jsoup.clean(encoder.canonicalize(parameter), whitelist); } XSSUtil(Encoder encoder); XSSUtil(Encoder encoder, Whitelist whitelist, String... exceptions); String stripXss(String parameter); String[] stripXss(String[] values); boolean doProcess(HttpServletRequest request); boolean doProcess(HttpServletRequest request, String... exceptions); void setProcessed(HttpServletRequest request, boolean processed); }### Answer: @Test public void test(){ XSSUtil xssUtil = new XSSUtil(ESAPI.encoder(), new Whitelist()); Assert.assertEquals("", xssUtil.stripXss("<script>alert('XSS!')<%2Fscript>")); Assert.assertEquals("", xssUtil.stripXss("<meta http-equiv%3D\"refresh\" content%3D\"0; url%3Dhttps:%2F%2Fwww.aiticon.com%2F\">")); }
### Question: ExpressionEvaluator { @SuppressWarnings("unchecked") public final <T> T evaluate(String expression, Class<T> targetType) { ValueExpression ve = ef.createValueExpression(ctx, expression, targetType); Object value = ve.getValue(ctx); T result = (T) value; if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(expression + " = " + result + " ["); sb.append(variableMapper.toString()); sb.append("]"); LOGGER.debug(sb.toString()); } return result; } ExpressionEvaluator(Map<String, ?> variables); ExpressionEvaluator(javax.el.VariableMapper variableMapper); @SuppressWarnings("unchecked") final T evaluate(String expression, Class<T> targetType); final boolean evaluate(String expression); final void addFunction(String prefix, String name, Method method); final void addFunction(String name, Method method); final void setVariable(String name, Object value); final void setVariables(Map<String, ?> variables); boolean isExpression(String value); String getString(String expression); Boolean getBoolean(String expression); }### Answer: @Test public void testNestedMap() { Assert.assertTrue(evaluator.evaluate("${SESSION.foo eq 5}")); Assert.assertTrue(evaluator.evaluate("${SESSION['foo'] eq 5}")); Assert.assertTrue(evaluator.evaluate("${SESSION.foo ne null}")); Assert.assertFalse(evaluator.evaluate("${SESSION['bar'] eq 5}")); Assert.assertTrue(evaluator.evaluate("${SESSION.bar eq null}")); } @Test public void testParamIsNull() { Assert.assertTrue(evaluator.evaluate("${uizuihm eq null}")); } @Test public void testDash() { parameters.put("site-id", ""); evaluator = new ExpressionEvaluator(parameters); Object result = evaluator.evaluate("${site-id eq ''}", boolean.class); System.out.println(result); result = evaluator.evaluate("${site-id}", int.class); System.out.println(result); } @Test public void testTernary() { evaluator = new ExpressionEvaluator(parameters); String result = evaluator.evaluate("${a eq 5 ? 'is five' : 'is not five'}", String.class); Assert.assertEquals("is five", result); result = evaluator.evaluate("${b eq 5 ? 'is five' : 'is not five'}", String.class); Assert.assertEquals("is not five", result); result = evaluator.evaluate("${a eq null ? 'is null': 'is not null'}", String.class); Assert.assertEquals("is not null", result); result = evaluator.evaluate("${c eq null ? 'is null': 'is not null'}", String.class); Assert.assertEquals("is null", result); } @Test public void testNameConventions() { parameters.put("a", "1"); parameters.put("a_", "2"); parameters.put("A", "3"); parameters.put("A_", "4"); parameters.put("ab", "5"); parameters.put("aB", "6"); parameters.put("a_b", "7"); parameters.put("aB_", "8"); evaluator = new ExpressionEvaluator(parameters); Assert.assertEquals(Integer.valueOf(1), evaluator.evaluate("${a}", Integer.class)); Assert.assertEquals(Integer.valueOf(2), evaluator.evaluate("${a_}", Integer.class)); Assert.assertEquals(Integer.valueOf(3), evaluator.evaluate("${A}", Integer.class)); Assert.assertEquals(Integer.valueOf(4), evaluator.evaluate("${A_}", Integer.class)); Assert.assertEquals(Integer.valueOf(5), evaluator.evaluate("${ab}", Integer.class)); Assert.assertEquals(Integer.valueOf(6), evaluator.evaluate("${aB}", Integer.class)); Assert.assertEquals(Integer.valueOf(7), evaluator.evaluate("${a_b}", Integer.class)); Assert.assertEquals(Integer.valueOf(8), evaluator.evaluate("${aB_}", Integer.class)); } @Test public void testNotDefinedInteger() throws Exception { boolean result = evaluator.evaluate("${c eq null}"); System.out.println(result); }
### Question: ExpressionEvaluator { public boolean isExpression(String value) { return null != value && value.matches("\\$\\{.*\\}"); } ExpressionEvaluator(Map<String, ?> variables); ExpressionEvaluator(javax.el.VariableMapper variableMapper); @SuppressWarnings("unchecked") final T evaluate(String expression, Class<T> targetType); final boolean evaluate(String expression); final void addFunction(String prefix, String name, Method method); final void addFunction(String name, Method method); final void setVariable(String name, Object value); final void setVariables(Map<String, ?> variables); boolean isExpression(String value); String getString(String expression); Boolean getBoolean(String expression); }### Answer: @Test public void testIsExpression() { Assert.assertTrue(evaluator.isExpression("${c eq null}")); Assert.assertTrue(evaluator.isExpression("${sdsdfsdf}")); Assert.assertFalse(evaluator.isExpression("#{sdsdfsdf}")); Assert.assertFalse(evaluator.isExpression("$sdsdfsdf}")); Assert.assertFalse(evaluator.isExpression("{sdsdfsdf}")); Assert.assertFalse(evaluator.isExpression("${sdsdfsdf")); }
### Question: XHTML { public static String getTag(String tag) { String value = ""; Pattern p = Pattern.compile("<(\\w+?)\\s"); Matcher m = p.matcher(tag); if (m.find()) { value = m.group(1); } return value; } static String removeAttr(String tag, String attr); static String setAttr(String tag, String attr, String value); static String getBody(String tag, String content); static String setBody(String tag, String value); static String getAttr(String tag, String attr); static String getTag(String tag); }### Answer: @Test public void testGetTag() { String content = "<body id=\"top\" background=\"blue\">"; String expResult = "body"; String result = XHTML.getTag(content); assertEquals(expResult, result); }
### Question: RepositoryUtils { public static boolean isSnapshot(String name) { return name.contains(SNAPSHOT); } private RepositoryUtils(); static String getContextPath(); static boolean isNewer(PackageVersion versionA, PackageVersion versionB); static boolean isNewer(PackageInfo packageA, PackageInfo packageB); static Comparator<PackageInfo> getVersionComparator(); static Date getDate(PackageInfo packageInfo); static boolean isSnapshot(String name); static PackageArchive getPackage(Repository repo, File file, String archiveName); static final String SNAPSHOT; }### Answer: @Test public void testIsSnapshot() { Assert.assertFalse(RepositoryUtils.isSnapshot("snapshot")); Assert.assertFalse(RepositoryUtils.isSnapshot("SNAPSHOT")); Assert.assertFalse(RepositoryUtils.isSnapshot("sNaPsHoT")); Assert.assertTrue(RepositoryUtils.isSnapshot(RepositoryUtils.SNAPSHOT)); }
### Question: RepositoryUtils { public static Date getDate(PackageInfo packageInfo) { try { return FDF.parse(packageInfo.getTimestamp()); } catch (ParseException e) { return new Date(0L); } } private RepositoryUtils(); static String getContextPath(); static boolean isNewer(PackageVersion versionA, PackageVersion versionB); static boolean isNewer(PackageInfo packageA, PackageInfo packageB); static Comparator<PackageInfo> getVersionComparator(); static Date getDate(PackageInfo packageInfo); static boolean isSnapshot(String name); static PackageArchive getPackage(Repository repo, File file, String archiveName); static final String SNAPSHOT; }### Answer: @Test public void testGetDate() { ApplicationInfo app = new ApplicationInfo(); app.setTimestamp("19700101-0100"); Date date = RepositoryUtils.getDate(app); Assert.assertEquals(0, date.getTime()); }
### Question: RepositoryUtils { public static Comparator<PackageInfo> getVersionComparator() { return (p1, p2) -> { int compared = 0; if (Version.isValidVersion(p1.getVersion()) && Version.isValidVersion(p2.getVersion())) { compared = Version.parseVersion(p1.getVersion(), true) .compareTo(Version.parseVersion(p2.getVersion(), true)); } if (compared == 0) { compared = StringUtils.compare(p1.getVersion(), p2.getVersion()); } if (compared == 0) { compared = getDate(p1).compareTo(getDate(p2)); } return compared * -1; }; } private RepositoryUtils(); static String getContextPath(); static boolean isNewer(PackageVersion versionA, PackageVersion versionB); static boolean isNewer(PackageInfo packageA, PackageInfo packageB); static Comparator<PackageInfo> getVersionComparator(); static Date getDate(PackageInfo packageInfo); static boolean isSnapshot(String name); static PackageArchive getPackage(Repository repo, File file, String archiveName); static final String SNAPSHOT; }### Answer: @Test public void testSemverSort() { ApplicationInfo a = new ApplicationInfo(); a.setVersion("1.14.1-SNAPSHOT"); a.setTimestamp("20190826-1159"); ApplicationInfo b = new ApplicationInfo(); b.setVersion("1.14.0-SNAPSHOT"); b.setTimestamp("20190826-1203"); ApplicationInfo c = new ApplicationInfo(); c.setVersion("1.14.0-SNAPSHOT"); c.setTimestamp("20190826-1157"); List<ApplicationInfo> arrayList = new ArrayList<>(Arrays.asList(c, b, a)); Collections.sort(arrayList, RepositoryUtils.getVersionComparator()); Assert.assertEquals(a.getTimestamp(), arrayList.get(0).getTimestamp()); Assert.assertEquals(b.getTimestamp(), arrayList.get(1).getTimestamp()); Assert.assertEquals(c.getTimestamp(), arrayList.get(2).getTimestamp()); }
### Question: StringNormalizer { public static String removeNonPrintableCharacters(final String value) { return replaceNonPrintableCharacters(value, StringUtils.EMPTY); } static final String normalize(final String input); static String removeNonPrintableCharacters(final String value); static String replaceNonPrintableCharacters(final String value, final String replacement); static final Pattern NON_PRINTABLE_CHARACTER; }### Answer: @Test public void testStripNonPrintableCharacter() { for (int c = 0; c < 32; c++) { if (c != 9 && c != 10 && c != 13) { String s = Character.toString((char) c); Assert.assertEquals("", StringNormalizer.removeNonPrintableCharacters(s)); } } int[] allowedCtrlChar = { 9, 10, 13 }; for (int c : allowedCtrlChar) { String s = Character.toString((char) c); Assert.assertEquals(s, StringNormalizer.removeNonPrintableCharacters(s)); } for (int c = 32; c < 127; c++) { String s = Character.toString((char) c); Assert.assertEquals(s, StringNormalizer.removeNonPrintableCharacters(s)); } for (int c = 127; c < 160; c++) { String s = Character.toString((char) c); Assert.assertEquals(StringUtils.EMPTY, StringNormalizer.removeNonPrintableCharacters(s)); } for (int c = 160; c < 65535; c++) { String s = Character.toString((char) c); Assert.assertEquals(s, StringNormalizer.removeNonPrintableCharacters(s)); } }
### Question: CacheProvider { protected File getCache() { return mkdir(cache); } CacheProvider(Properties platformConfig); CacheProvider(Properties platformConfig, boolean changeOwner); void clearCache(Site site); void clearCache(Site site, String application); File getPlatformCache(Nameable site, Nameable application); String getRelativePlatformCache(Nameable site, Nameable application); File getImageCache(Nameable site, Nameable application); }### Answer: @Test public void testgetCache() { File cache = cacheProvider.getCache(); Assert.assertEquals(cacheRoot, cache); }
### Question: CacheProvider { public void clearCache(Site site) { clear(getPlatformCache(site)); clear(getApplicationCache(site)); } CacheProvider(Properties platformConfig); CacheProvider(Properties platformConfig, boolean changeOwner); void clearCache(Site site); void clearCache(Site site, String application); File getPlatformCache(Nameable site, Nameable application); String getRelativePlatformCache(Nameable site, Nameable application); File getImageCache(Nameable site, Nameable application); }### Answer: @Test public void testClearCache() { File platformSite = new File("target/WEB-INF/cache/platform/" + sitename); File appSite = new File("target/WEB-INF/cache/application/" + sitename); Assert.assertTrue(platformSite.exists()); Assert.assertTrue(appSite.exists()); cacheProvider.clearCache(site); Assert.assertFalse(platformSite.exists()); Assert.assertFalse(appSite.exists()); } @Test public void testClearApplicationCache() { Assert.assertTrue(platformCache.exists()); Assert.assertTrue(applicationCache.exists()); cacheProvider.clearCache(site, applicationName); Assert.assertTrue(applicationRoot.exists()); Assert.assertTrue(platformRoot.exists()); Assert.assertFalse(platformCache.exists()); Assert.assertFalse(applicationCache.exists()); }
### Question: CacheProvider { protected File getPlatformCache() { return mkdir(platform); } CacheProvider(Properties platformConfig); CacheProvider(Properties platformConfig, boolean changeOwner); void clearCache(Site site); void clearCache(Site site, String application); File getPlatformCache(Nameable site, Nameable application); String getRelativePlatformCache(Nameable site, Nameable application); File getImageCache(Nameable site, Nameable application); }### Answer: @Test public void testgetPlatformCache() { FileUtils.deleteQuietly(platformCache); File cache = cacheProvider.getPlatformCache(sitename, applicationName).getAbsoluteFile(); Assert.assertEquals(platformCache, cache); }
### Question: CacheProvider { public String getRelativePlatformCache(Nameable site, Nameable application) { String applicationCache = getPlatformCache(site.getName(), application.getName()).getAbsolutePath(); return applicationCache.substring(prefixLength); } CacheProvider(Properties platformConfig); CacheProvider(Properties platformConfig, boolean changeOwner); void clearCache(Site site); void clearCache(Site site, String application); File getPlatformCache(Nameable site, Nameable application); String getRelativePlatformCache(Nameable site, Nameable application); File getImageCache(Nameable site, Nameable application); }### Answer: @Test public void testGetRelativePlatformCache() { String cache = cacheProvider.getRelativePlatformCache(site, application); Assert.assertEquals(new File("/WEB-INF/cache/platform/appNG/foobar").getPath(), cache); }
### Question: CacheProvider { public File getImageCache(Nameable site, Nameable application) { return mkdir(getImageCache(site.getName(), application.getName())); } CacheProvider(Properties platformConfig); CacheProvider(Properties platformConfig, boolean changeOwner); void clearCache(Site site); void clearCache(Site site, String application); File getPlatformCache(Nameable site, Nameable application); String getRelativePlatformCache(Nameable site, Nameable application); File getImageCache(Nameable site, Nameable application); }### Answer: @Test public void testGetImageCache() { File cache = cacheProvider.getImageCache(site, application).getAbsoluteFile(); Assert.assertEquals(new File(applicationCache, "images"), cache); }
### Question: PageParameterProcessor { boolean processPageParams(List<String> applicationUrlParameters, UrlSchema urlSchema) { processPostParams(urlSchema.getPostParams()); processGetParams(urlSchema.getGetParams()); boolean urlParamsAdded = processUrlParams(applicationUrlParameters, urlSchema.getUrlParams()); processSessionParams(); return urlParamsAdded; } PageParameterProcessor(String sessionParamKey, Set<String> sessionParamNames, Environment env, Request request); }### Answer: @Test public void testApplicationUrlParameter() throws Exception { Mockito.when(request.getParameter(ACTION)).thenReturn(null); Mockito.when(request.getParameter(PARAM2)).thenReturn("asasd"); Mockito.when(request.isGet()).thenReturn(true); applicationUrlParameter.add("actionFromUrl"); UrlSchema urlSchema = getUrlSchema(); Param user = new Param(); user.setName("user"); urlSchema.getGetParams().getParamList().add(user); Param hash = new Param(); hash.setName(HASH); urlSchema.getGetParams().getParamList().add(hash); sessionParams.put(HASH, ""); sessionParamNames.add(HASH); boolean urlParamAdded = ppp.processPageParams(applicationUrlParameter, urlSchema); Mockito.verify(env, Mockito.atLeast(1)).getAttribute(SESSION, "key"); Assert.assertFalse(urlParamAdded); validateXml(urlSchema, getClass().getSimpleName() + "-"); } @Test public void testApplicationUrlParameterFromSession() throws Exception { Mockito.when(request.getParameter(ACTION)).thenReturn(null); Mockito.when(request.getParameter(PARAM2)).thenReturn("47"); Mockito.when(request.isGet()).thenReturn(true); UrlSchema urlSchema = getUrlSchema(); Param user = new Param(); user.setName("user"); urlSchema.getGetParams().getParamList().add(user); Param hash = new Param(); hash.setName(HASH); urlSchema.getUrlParams().getParamList().add(hash); sessionParams.put(HASH, "hashFromSession"); sessionParamNames.add(HASH); boolean urlParamAdded = ppp.processPageParams(applicationUrlParameter, urlSchema); Mockito.verify(env, Mockito.atLeast(1)).getAttribute(SESSION, "key"); Assert.assertTrue(urlParamAdded); validateXml(urlSchema, getClass().getSimpleName() + "-"); } @Test public void testGetBeforeUrl() throws Exception { Mockito.when(request.isGet()).thenReturn(true); UrlSchema urlSchema = getUrlSchema(); Param user = new Param(); user.setName("user"); urlSchema.getGetParams().getParamList().add(user); Param hash = new Param(); hash.setName(HASH); urlSchema.getGetParams().getParamList().add(hash); sessionParams.put(HASH, ""); sessionParamNames.add(HASH); boolean urlParamAdded = ppp.processPageParams(applicationUrlParameter, urlSchema); Mockito.verify(env, Mockito.atLeast(1)).getAttribute(SESSION, "key"); Assert.assertFalse(urlParamAdded); validateXml(urlSchema, getClass().getSimpleName() + "-"); } @Test public void testPostOverGet() throws Exception { Mockito.when(request.isPost()).thenReturn(true); UrlSchema urlSchema = getUrlSchema(); boolean urlParamAdded = ppp.processPageParams(applicationUrlParameter, urlSchema); Mockito.verify(env, Mockito.atLeast(1)).getAttribute(SESSION, "key"); Assert.assertFalse(urlParamAdded); validateXml(urlSchema, getClass().getSimpleName() + "-"); } @Test public void testSession() throws Exception { sessionParams.put(ACTION, "fooAction"); sessionParamNames.add(ACTION); Mockito.when(request.getParameter(ACTION)).thenReturn(null); Mockito.when(request.isGet()).thenReturn(true); UrlSchema urlSchema = getUrlSchema(); boolean urlParamAdded = ppp.processPageParams(applicationUrlParameter, urlSchema); Mockito.verify(env, Mockito.atLeast(1)).getAttribute(SESSION, "key"); Assert.assertFalse(urlParamAdded); validateXml(urlSchema, getClass().getSimpleName() + "-"); }
### Question: PropertyConstantCreator { public static void main(String[] args) throws IOException { if (args.length < 3) { throw new IllegalArgumentException( "at least 3 parameters needed: filePath* targetClass* outFolder* [charset]"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String charSet = StandardCharsets.UTF_8.name(); if (args.length == 4) { charSet = args[3]; } if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } Properties props = new Properties(); props.load(new InputStreamReader(new FileInputStream(filePath), charSet)); int pckg = targetClass.lastIndexOf("."); String lineBreak = System.lineSeparator(); StringBuilder sb = new StringBuilder(); if (pckg > 0) { sb.append("package " + targetClass.substring(0, pckg) + ";"); sb.append(lineBreak); sb.append(lineBreak); } sb.append("public class " + targetClass.substring(pckg + 1) + " {"); sb.append(lineBreak); sb.append(lineBreak); Set<Object> keySet = new TreeSet<>(props.keySet()); for (Object object : keySet) { String key = (String) object; sb.append("\t", "*&#47;") + " */" + lineBreak); sb.append("\tpublic static final String "); String constantName = key.replace('-', '_').replace('.', '_'); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(constantName); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (!"_".equals(s)) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + key + "\";"); sb.append(lineBreak); } sb.append(lineBreak); sb.append("}"); String fileName = targetClass.replace('.', '/') + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); } } static void main(String[] args); }### Answer: @Test public void test() throws IOException { String className = "org.appng.tools.file.Constants"; String path = className.replace('.', '/') + ".java"; String target = "target/constants/"; PropertyConstantCreator.main(new String[] { "src/test/resources/props.properties", className, target }); List<String> expected = Files.readAllLines(new File("src/test/resources/" + path.substring(path.lastIndexOf('/'))).toPath()); List<String> actual = Files.readAllLines(new File(target + path).toPath()); Assert.assertEquals(expected, actual); }
### Question: TemplateService { public org.appng.xml.application.Template getTemplate(String templateDir) throws IOException, JAXBException { return validateResource(MarshallService.getApplicationMarshallService(), TEMPLATE_XML, new FileInputStream(new File(templateDir, TEMPLATE_XML)), org.appng.xml.application.Template.class); } ZipFileProcessor<Template> getTemplateExtractor(); static ZipFileProcessor<org.appng.xml.application.Template> getTemplateInfo(final String originalFilename); List<Identifier> getInstalledTemplates(); static void materializeTemplate(Template template, Properties platformConfig, Properties siteProps); static void copyTemplate(Properties platformConfig, Properties siteProps, String templateRealPath); Template installTemplate(PackageArchive packageArchive); Template getTemplateByDisplayName(String name); Template getTemplateByName(String name); Integer deleteTemplate(Template template); static File getTemplateRepoFolder(Properties platformConfig, Properties siteProps); org.appng.xml.application.Template getTemplate(String templateDir); static final String PLATFORM_XML; }### Answer: @Test public void testGetTemplate() throws Exception { Template template = service.getTemplate("target/test-classes/template/appng"); Assert.assertEquals(TemplateType.XSL, template.getType()); Assert.assertEquals("appng-template", template.getName()); Assert.assertEquals("0.8.0", template.getVersion()); Assert.assertEquals("appNG Template", template.getDisplayName()); Assert.assertEquals("0.13.0", template.getAppngVersion()); }
### Question: TemplateService { public ZipFileProcessor<Template> getTemplateExtractor() { ZipFileProcessor<Template> templateExtractor = new ZipFileProcessor<Template>() { public Template process(ZipFile zipFile) throws IOException { org.appng.xml.application.Template templateXml = null; List<TemplateResource> resources = new ArrayList<>(); try { Enumeration<ZipArchiveEntry> entries = zipFile.getEntriesInPhysicalOrder(); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String path = entry.getName(); path = path.substring(path.indexOf('/') + 1); if (!entry.isDirectory()) { try ( InputStream in = zipFile.getInputStream(entry); ByteArrayOutputStream out = new ByteArrayOutputStream()) { try { IOUtils.copy(in, out); TemplateResource templateResource = new TemplateResource(); templateResource.setName(path); templateResource.setFileVersion(entry.getLastModifiedDate()); templateResource.setResourceType(ResourceType.RESOURCE); templateResource.setBytes(out.toByteArray()); templateResource.calculateChecksum(); resources.add(templateResource); if (path.equals(TEMPLATE_XML)) { templateXml = applicationMarshallService.unmarshall( new ByteArrayInputStream(templateResource.getBytes()), org.appng.xml.application.Template.class); } } catch (IOException ioe) { throw ioe; } } LOGGER.info("added resource {}", path); } } } catch (JAXBException e) { throw new IOException(e); } ZipFile.closeQuietly(zipFile); Template template = new Template(templateXml); for (TemplateResource templateResource : resources) { templateResource.setTemplate(template); template.getResources().add(templateResource); } return template; } }; return templateExtractor; } ZipFileProcessor<Template> getTemplateExtractor(); static ZipFileProcessor<org.appng.xml.application.Template> getTemplateInfo(final String originalFilename); List<Identifier> getInstalledTemplates(); static void materializeTemplate(Template template, Properties platformConfig, Properties siteProps); static void copyTemplate(Properties platformConfig, Properties siteProps, String templateRealPath); Template installTemplate(PackageArchive packageArchive); Template getTemplateByDisplayName(String name); Template getTemplateByName(String name); Integer deleteTemplate(Template template); static File getTemplateRepoFolder(Properties platformConfig, Properties siteProps); org.appng.xml.application.Template getTemplate(String templateDir); static final String PLATFORM_XML; }### Answer: @Test public void testTemplateExtractor() throws Exception { ZipFileProcessor<org.appng.core.domain.Template> templateExtractor = service.getTemplateExtractor(); org.appng.core.domain.Template processed = templateExtractor.process(new ZipFile(templateZip)); verifyTemplate(processed); }
### Question: TemplateService { public Template installTemplate(PackageArchive packageArchive) throws BusinessException { try { ZipFileProcessor<Template> templateExtractor = getTemplateExtractor(); Template template = packageArchive.processZipFile(templateExtractor); Template existing = templateRepository.findByName(template.getName()); if (null == existing) { templateRepository.save(template); } else { List<TemplateResource> resources = existing.getResources(); templateResourceRepository.delete(resources); resources.clear(); existing.update(template); template = existing; } return template; } catch (IOException e) { throw new BusinessException("error while provisioning " + packageArchive.toString(), e); } } ZipFileProcessor<Template> getTemplateExtractor(); static ZipFileProcessor<org.appng.xml.application.Template> getTemplateInfo(final String originalFilename); List<Identifier> getInstalledTemplates(); static void materializeTemplate(Template template, Properties platformConfig, Properties siteProps); static void copyTemplate(Properties platformConfig, Properties siteProps, String templateRealPath); Template installTemplate(PackageArchive packageArchive); Template getTemplateByDisplayName(String name); Template getTemplateByName(String name); Integer deleteTemplate(Template template); static File getTemplateRepoFolder(Properties platformConfig, Properties siteProps); org.appng.xml.application.Template getTemplate(String templateDir); static final String PLATFORM_XML; }### Answer: @Test public void testInstall() throws Exception { org.appng.core.domain.Template installed = service.installTemplate(new PackageArchiveImpl(templateZip, true)); verifyTemplate(installed); Assert.assertNotNull(installed.getVersion()); }
### Question: InitializerService { @Transactional public void initPlatform(PlatformProperties platformConfig, Environment env, DatabaseConnection rootConnection, ServletContext ctx, ExecutorService executor) throws InvalidConfigurationException { logEnvironment(); loadPlatform(platformConfig, env, null, null, executor); addJarInfo(env, ctx); databaseService.setActiveConnection(rootConnection, false); coreService.createEvent(Type.INFO, "Started platform"); } InitializerService(); @Transactional void initPlatform(PlatformProperties platformConfig, Environment env, DatabaseConnection rootConnection, ServletContext ctx, ExecutorService executor); void reloadPlatform(java.util.Properties config, Environment env, String siteName, String target, ExecutorService executor); void loadPlatform(PlatformProperties platformConfig, Environment env, String siteName, String target, ExecutorService executor); PlatformProperties loadPlatformProperties(java.util.Properties defaultOverrides, Environment env); @Transactional synchronized void loadSite(Environment env, SiteImpl siteToLoad, FieldProcessor fp); @Transactional synchronized void loadSite(Environment env, SiteImpl siteToLoad, boolean sendReloadEvent, FieldProcessor fp); synchronized void loadSite(SiteImpl siteToLoad, ServletContext servletContext, FieldProcessor fp); synchronized void loadSite(SiteImpl siteToLoad, Environment env, boolean sendReloadEvent, FieldProcessor fp); void shutdownPlatform(ServletContext ctx); void shutDownSite(Environment env, Site site, boolean removeFromSiteMap); CoreService getCoreService(); void setCoreService(CoreService coreService); static final String APPNG_USER; static final String APPNG_GROUP; }### Answer: @Test public void testInitPlatform() throws Exception { PropertyHolder propertyHolder = new PropertyHolder(PropertySupport.PREFIX_PLATFORM, Collections.emptyList()); for (String prop : platformProperties.getPropertyNames()) { String key = prop.substring(PropertySupport.PREFIX_PLATFORM.length()); String value = platformProperties.getString(prop); String defaultValue = value == null ? StringUtils.EMPTY : value; propertyHolder.addProperty(key, defaultValue, StringUtils.EMPTY, Type.forString(defaultValue)); } propertyHolder.setFinal(); platformMap.put(Platform.Environment.PLATFORM_CONFIG, propertyHolder); File templateRoot = new File("target/test-classes/repository/site-1/www/template/"); FileUtils.deleteQuietly(templateRoot); Mockito.when(ctx.getRealPath("/uploads")).thenReturn("target/uploads"); Mockito.when(env.getAttribute(Scope.PLATFORM, Platform.Environment.SITES)).thenReturn(new HashMap<>()); Mockito.when(env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG)) .thenReturn(platformProperties); PlatformProperties platformProperties = service.loadPlatformProperties(new Properties(), env); service.loadPlatform(platformProperties, env, null, null, null); Mockito.verify(ctx, Mockito.atLeastOnce()).getRealPath(Mockito.anyString()); Mockito.verify(env, VerificationModeFactory.atLeast(1)).setAttribute(Mockito.eq(Scope.PLATFORM), Mockito.anyString(), Mockito.any()); Assert.assertTrue(new File(templateRoot, "assets/favicon.ico").exists()); Assert.assertTrue(new File(templateRoot, "resources/dummy.txt").exists()); Assert.assertFalse(new File(templateRoot, "xsl").exists()); Assert.assertFalse(new File(templateRoot, "conf").exists()); Assert.assertFalse(new File(templateRoot, "template.xml").exists()); }
### Question: InitializerService { @Transactional public synchronized void loadSite(Environment env, SiteImpl siteToLoad, FieldProcessor fp) throws InvalidConfigurationException { loadSite(env, siteToLoad, true, fp); } InitializerService(); @Transactional void initPlatform(PlatformProperties platformConfig, Environment env, DatabaseConnection rootConnection, ServletContext ctx, ExecutorService executor); void reloadPlatform(java.util.Properties config, Environment env, String siteName, String target, ExecutorService executor); void loadPlatform(PlatformProperties platformConfig, Environment env, String siteName, String target, ExecutorService executor); PlatformProperties loadPlatformProperties(java.util.Properties defaultOverrides, Environment env); @Transactional synchronized void loadSite(Environment env, SiteImpl siteToLoad, FieldProcessor fp); @Transactional synchronized void loadSite(Environment env, SiteImpl siteToLoad, boolean sendReloadEvent, FieldProcessor fp); synchronized void loadSite(SiteImpl siteToLoad, ServletContext servletContext, FieldProcessor fp); synchronized void loadSite(SiteImpl siteToLoad, Environment env, boolean sendReloadEvent, FieldProcessor fp); void shutdownPlatform(ServletContext ctx); void shutDownSite(Environment env, Site site, boolean removeFromSiteMap); CoreService getCoreService(); void setCoreService(CoreService coreService); static final String APPNG_USER; static final String APPNG_GROUP; }### Answer: @Test @Ignore("causes CoreServiceTest to fail") public void testLoadSite() throws InvalidConfigurationException, IOException { FileUtils.copyDirectory(new File("src/test/resources/applications/application1"), new File("target/root/applications/application1")); Site siteToLoad = siteMap.remove("manager"); service.loadSite((SiteImpl) siteToLoad, ctx, new FieldProcessorImpl("testLoadSite")); Application application = siteToLoad.getApplication("application1"); TestService testservice = application.getBean(TestService.class); TestEntity entity = new TestEntity(null, "name", 2, 3.4d, true); testservice.createEntity(entity); Assert.assertEquals(Integer.valueOf(1), entity.getId()); service.shutDownSite(env, siteToLoad, true); }
### Question: PropertySupport { public void initPlatformConfig(String rootPath, Boolean devMode) { initPlatformConfig(rootPath, devMode, new java.util.Properties(), true); } PropertySupport(PropertyHolder propertyHolder); static java.util.Properties getProperties(Properties platFormConfig, Site site, Application application, boolean addPlatformScope); static String getPropertyName(Site site, Application application, String name); static String getPropertyPrefix(Site site, Application application); static String getSitePrefix(Site site); void initSiteProperties(SiteImpl site, Properties platformConfig); void initPlatformConfig(String rootPath, Boolean devMode); void initPlatformConfig(String rootPath, Boolean devMode, java.util.Properties immutableOverrides, boolean finalize); static final String PREFIX_PLATFORM; static final String PROP_PATTERN; }### Answer: @Test public void testInitPlatformConfig() { Properties defaultOverrides = new Properties(); defaultOverrides.put(PropertySupport.PREFIX_PLATFORM + "a", "1"); defaultOverrides.put(PropertySupport.PREFIX_PLATFORM + "b", "foo"); defaultOverrides.put(PropertySupport.PREFIX_PLATFORM + "c", "foo\nbar"); defaultOverrides.put("dummy", "foo"); defaultOverrides.put(PropertySupport.PREFIX_PLATFORM + Platform.Property.FILEBASED_DEPLOYMENT, "false"); defaultOverrides.put(PropertySupport.PREFIX_PLATFORM + Platform.Property.MAIL_DISABLED, "false"); PropertyHolder platformProps = getPlatformConfig(defaultOverrides); Assert.assertFalse(platformProps.getBoolean(Platform.Property.FILEBASED_DEPLOYMENT)); Assert.assertFalse(platformProps.getBoolean(Platform.Property.MAIL_DISABLED)); Assert.assertTrue(platformProps.getBoolean(Platform.Property.DEV_MODE)); Assert.assertEquals(Integer.valueOf(1), platformProps.getInteger("a")); Assert.assertEquals("foo", platformProps.getString("b")); Assert.assertEquals("foo\nbar", platformProps.getClob("c")); Assert.assertNull(platformProps.getString("dummy")); }
### Question: RuleValidation { public static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize) { return isValidFileUpload(fUpload, minSize, false) && isValidFileUpload(fUpload, maxSize, true); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testFileSize() { assertTrue("fileSize(upload,'500KB','2.5MB')"); assertFalse("fileSize(upload,'600KB','1.1MB')"); assertFalse("fileSize(upload,'500KB','0.1MB')"); }
### Question: RuleValidation { public static boolean fileType(List<FormUpload> fUpload, String types) { List<String> fileTypes = Arrays.asList(types.split(COMMA)); if (fUpload != null) { for (FormUpload fileName : fUpload) { if (!fileTypes.contains(fileName.getContentType())) { return false; } } } return true; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testFileType() { assertTrue("fileType(upload,'jpg,gif,png')"); assertFalse("fileType(upload,'tif,pdf')"); }
### Question: ImageProcessor { public ImageProcessor rotate(int degrees) { op.rotate((double) degrees); return this; } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath, boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight, int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); }### Answer: @Test public void testRotate() throws IOException { File targetFile = new File(targetFolder, "desert-rotated.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToWidth(150).rotate(-45); ip.getImage(); }
### Question: RuleValidation { public static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount) { return fileCountMin(fUpload, minCount) && fileCountMax(fUpload, maxCount); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testFileCount() { assertTrue("fileCount(upload, 1, 2)"); assertFalse("fileCount(upload, 1, 0)"); assertFalse("fileCount(upload, 3, 2)"); }
### Question: RuleValidation { public static boolean fileCountMin(List<FormUpload> fUpload, int count) { return getNumberOfFiles(fUpload) >= count; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testFileCountMin() { assertTrue("fileCountMin(upload, 1)"); assertFalse("fileCountMin(upload, 5)"); assertFalse("fileCountMin(upload, 3)"); }
### Question: RuleValidation { public static boolean fileCountMax(List<FormUpload> fUpload, int count) { return getNumberOfFiles(fUpload) <= count; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testFileCountMax() { assertTrue("fileCountMax(upload, 3)"); assertFalse("fileCountMax(upload, 1)"); assertFalse("fileCountMax(upload, 0)"); }
### Question: DatabaseService extends MigrationService { @Transactional public DatabaseConnection initDatabase(java.util.Properties config, boolean managed, boolean setActive) { DatabaseConnection platformConnection = initDatabase(config); MigrationInfoService statusComplete = platformConnection.getMigrationInfoService(); if (setActive && statusComplete != null && null != statusComplete.current()) { platformConnection.setManaged(managed); platformConnection = setActiveConnection(platformConnection, true); platformConnection.setMigrationInfoService(statusComplete); } return platformConnection; } void resetApplicationConnection(SiteApplication siteApplication, String databasePrefix); @Transactional DatabaseConnection initDatabase(java.util.Properties config, boolean managed, boolean setActive); @Transactional DatabaseConnection setActiveConnection(DatabaseConnection rootConnection, boolean changeManagedState); DatabaseConnection getRootConnectionOfType(DatabaseType type); @Transactional MigrationStatus manageApplicationConnection(SiteApplication siteApplication, File sqlFolder, String databasePrefix); @Transactional void save(DatabaseConnection databaseConnection); }### Answer: @Test public void testInitDatabase() throws Exception { String jdbcUrl = "jdbc:hsqldb:mem:testInitDatabase"; Properties platformProperties = getProperties(DatabaseType.HSQL, jdbcUrl, "sa", "", JDBCDriver.class.getName()); DatabaseConnection platformConnection = databaseService.initDatabase(platformProperties); StringBuilder dbInfo = new StringBuilder(); Assert.assertTrue(platformConnection.testConnection(dbInfo, true)); Assert.assertTrue(dbInfo.toString().startsWith("HSQL Database Engine")); String rootName = "appNG Root Database"; Assert.assertEquals(rootName, platformConnection.getDescription()); Assert.assertEquals(DatabaseType.HSQL, platformConnection.getType()); validateSchemaVersion(platformConnection, "4.2.1"); DatabaseConnection mssql = new DatabaseConnection(DatabaseType.MSSQL, rootName, "", "".getBytes()); mssql.setName(rootName); mssql.setActive(false); databaseConnectionRepository.save(mssql); databaseService.setActiveConnection(platformConnection, false); List<DatabaseConnection> connections = databaseConnectionRepository.findAll(); Assert.assertEquals(4, connections.size()); for (DatabaseConnection connection : connections) { switch (connection.getType()) { case HSQL: Assert.assertTrue(connection.isActive()); break; default: Assert.assertFalse(connection.isActive()); break; } } }
### Question: RuleValidation { public static boolean string(String string) { return regExp(string, EXP_STRING); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testString() { assertTrue("string(foo)"); assertTrue("string(bar)"); assertFalse("string(foobar)"); assertTrue("string('foobar')"); }
### Question: DatabaseService extends MigrationService { protected String getUserName(Site site, Application application) { return "site" + site.getId() + "app" + application.getId(); } void resetApplicationConnection(SiteApplication siteApplication, String databasePrefix); @Transactional DatabaseConnection initDatabase(java.util.Properties config, boolean managed, boolean setActive); @Transactional DatabaseConnection setActiveConnection(DatabaseConnection rootConnection, boolean changeManagedState); DatabaseConnection getRootConnectionOfType(DatabaseType type); @Transactional MigrationStatus manageApplicationConnection(SiteApplication siteApplication, File sqlFolder, String databasePrefix); @Transactional void save(DatabaseConnection databaseConnection); }### Answer: @Test public void testUserName() { Application app = Mockito.mock(Application.class); Site site = Mockito.mock(Site.class); Mockito.when(site.getId()).thenReturn(1234); Mockito.when(app.getId()).thenReturn(1234); String userName = databaseService.getUserName(site, app); Assert.assertTrue(userName.length() <= 16); }
### Question: LdapService { public List<SubjectImpl> getMembersOfGroup(Site site, String groupName) { List<SubjectImpl> subjects = new ArrayList<>(); String serviceUser = site.getProperties().getString(LDAP_USER); char[] servicePassword = site.getProperties().getString(LDAP_PASSWORD).toCharArray(); LdapCredentials ldapCredentials = new LdapCredentials(site, serviceUser, servicePassword, true); String groupBaseDn = site.getProperties().getString(LDAP_GROUP_BASE_DN); String idAttribute = site.getProperties().getString(LDAP_ID_ATTRIBUTE); String groupDn = getGroupDn(groupName, groupBaseDn); TlsAwareLdapContext ctx = null; try { ctx = new TlsAwareLdapContext(ldapCredentials); for (String member : getGroupMembers(ctx.delegate, groupDn)) { Attributes userAttrs = getUserAttributes(ctx.delegate, member, idAttribute); SubjectImpl ldapSubject = fillSubjectFromAttributes(new SubjectImpl(), idAttribute, userAttrs); subjects.add(ldapSubject); } } catch (IOException | NamingException ex) { logException(ldapCredentials.ldapHost, ldapCredentials.principal, ex); } finally { closeContext(ctx); } LOGGER.info("Found {} member(s) for group '{}'", subjects.size(), groupDn); return subjects; } void setLdapCtxFactory(String ldapCtxFactory); boolean loginUser(Site site, String username, char[] password); List<String> loginGroup(Site site, String username, char[] password, SubjectImpl subject, List<String> groupNames); List<SubjectImpl> getMembersOfGroup(Site site, String groupName); static final String LDAP_DOMAIN; static final String LDAP_GROUP_BASE_DN; static final String LDAP_HOST; static final String LDAP_ID_ATTRIBUTE; static final String LDAP_PASSWORD; static final String LDAP_PRINCIPAL_SCHEME; static final String LDAP_START_TLS; static final String LDAP_USER; static final String LDAP_USER_BASE_DN; }### Answer: @Test public void testUsersOfGroup() throws NamingException, IOException { List<SubjectImpl> resultSubjects; String[] expectSubjNames = new String[] { "aziz", "aziz' brother" }; String[] expectSubjRealNames = new String[] { "Dummy", "Dummy" }; sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "UPN"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); sitePropertyMocks.put(LdapService.LDAP_USER, "mondoshawan"); sitePropertyMocks.put(LdapService.LDAP_PASSWORD, "stones"); sitePropertyMocks.put(LdapService.LDAP_USER_BASE_DN, "ou=users,l=egypt"); sitePropertyMocks.put(LdapService.LDAP_GROUP_BASE_DN, "ou=groups,l=egypt"); setup("aziz@egypt", "light", "mondoshawan@egypt", "stones"); resultSubjects = ldapService.getMembersOfGroup(mockedSite, LdapContextMock.MOCKED_GROUP_NAME); Assert.assertEquals(resultSubjects.size(), 2); for (int idx = 0; idx < 2; idx++) { Assert.assertEquals(resultSubjects.get(idx).getName(), expectSubjNames[idx]); Assert.assertEquals(resultSubjects.get(idx).getRealname(), expectSubjRealNames[idx]); Assert.assertFalse(resultSubjects.get(idx).isAuthenticated()); } }
### Question: Signer { public static SignatureWrapper signRepo(Path repoPath, SignerConfig config) throws SigningException { String missingKey = config.hasMissingKey(); if (missingKey != null) throw new SigningException(ErrorType.SIGN, String.format("Missing configuration key '%s' in SignerConfig.", missingKey)); LOGGER.info("Signing repository '{}'", repoPath); try { Path[] pkgPaths = fileGlob(repoPath, "*.{jar,zip}"); Path releaseFilePath = repoPath.resolve("index"); LOGGER.info("Writing release file '{}'", releaseFilePath); try ( BufferedWriter releaseFileOut = Files.newBufferedWriter(releaseFilePath, config.getCharset(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { LOGGER.info("..adding repository attributes"); for (String key : BaseConfig.validRepoAttributes) { releaseFileOut.append(String.format("%s: %s\n", key, config.repoAttributes.get(key))); } releaseFileOut.append(String.format("%s\n", SignerConfig.RELEASE_FILE_DIGEST_SEPARATOR)); for (Path pkgPath : pkgPaths) { LOGGER.info("..adding message digest of package '{}'", pkgPath.getFileName()); byte[] hashRaw = config.getDigest().digest(Files.readAllBytes(pkgPath)); releaseFileOut .append(String.format("%s: %s\n", pkgPath.getFileName(), Hex.encodeHexString(hashRaw))); } releaseFileOut.close(); Signature sig = config.getSignature(); sig.update(Files.readAllBytes(releaseFilePath)); byte[] signed = sig.sign(); SignatureWrapper signatureWrapper = new SignatureWrapper(); signatureWrapper.setSignature(signed); signatureWrapper.setIndex(Files.readAllBytes(releaseFilePath)); return signatureWrapper; } } catch (IOException ioe) { throw new SigningException(ErrorType.SIGN, "IOException during repo signing. Please check the configured paths and masks.", ioe); } catch (SignatureException se) { throw new SigningException(ErrorType.SIGN, String.format( "SignatureException during repo signing. There is no plausible reason in this part of the code. You probably found a bug!"), se); } } private Signer(ValidatorConfig config); static Signer getRepoValidator(ValidatorConfig config, byte[] indexFileData, byte[] signatureData); static Signer getRepoValidator(ValidatorConfig config, byte[] indexFileData, byte[] signatureData, Collection<X509Certificate> trustedCerts); boolean validatePackage(byte[] bytes, String packageName); static SignatureWrapper signRepo(Path repoPath, SignerConfig config); }### Answer: @Test public void testSign() throws IOException { byte[] cert = FileUtils.readFileToByteArray(certFile); byte[] key = FileUtils.readFileToByteArray(getFile("cert/appng-dev.pem")); Path repoPath = getFile("zip").toPath(); SignatureWrapper signRepo = Signer.signRepo(repoPath, new SignerConfig("Local", "a local test repository", "", key, cert, SigningAlgorithm.SHA512withRSA, PrivateKeyFormat.PEM)); StringWriter output = new StringWriter(); IOUtils.write(signRepo.getIndex(), output, StandardCharsets.UTF_8); String expected = FileUtils.readFileToString(indexFile, StandardCharsets.UTF_8); Assert.assertEquals(expected, output.toString()); byte[] expectedSig = FileUtils.readFileToByteArray(signatureFile); Assert.assertArrayEquals(expectedSig, signRepo.getSignature()); }
### Question: RuleValidation { public static boolean captcha(String value, String result) { return StringUtils.equals(value, result); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testCaptcha() { assertFalse("captcha(bar, SESSION.foobar)"); assertFalse("captcha(bar, SESSION['foobar'])"); assertTrue("captcha(5, SESSION.foobar)"); assertTrue("captcha(5, SESSION['foobar'])"); }
### Question: Signer { public static Signer getRepoValidator(ValidatorConfig config, byte[] indexFileData, byte[] signatureData) throws SigningException { return getRepoValidator(config, indexFileData, signatureData, null); } private Signer(ValidatorConfig config); static Signer getRepoValidator(ValidatorConfig config, byte[] indexFileData, byte[] signatureData); static Signer getRepoValidator(ValidatorConfig config, byte[] indexFileData, byte[] signatureData, Collection<X509Certificate> trustedCerts); boolean validatePackage(byte[] bytes, String packageName); static SignatureWrapper signRepo(Path repoPath, SignerConfig config); }### Answer: @Test(expected = SigningException.class) public void testVerfiyInvalidSignature() throws IOException { ValidatorConfig config = new ValidatorConfig(); config.setSigningCert(FileUtils.readFileToByteArray(certFile), SigningAlgorithm.SHA512withRSA); Signer.getRepoValidator(config, FileUtils.readFileToByteArray(indexFile), FileUtils.readFileToByteArray(indexFile)); }
### Question: BCryptPasswordHandler implements PasswordHandler { public boolean isValidPassword(String password) { boolean isValid = BCrypt.checkpw(password, authSubject.getDigest()); return isValid; } BCryptPasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); static String getPrefix(); }### Answer: @Test public void testValidPassword() { subject.setDigest(BCRYPT_DIGEST); PasswordHandler handler = new BCryptPasswordHandler(subject); assertTrue(handler.isValidPassword(PASSWORD)); } @Test public void testInvalidPassword() { subject.setDigest(BCRYPT_DIGEST.substring(0, BCRYPT_DIGEST.length() - 1)); PasswordHandler handler = new BCryptPasswordHandler(subject); assertFalse(handler.isValidPassword(PASSWORD)); }
### Question: BCryptPasswordHandler implements PasswordHandler { public boolean isValidPasswordResetDigest(String digest) { String expectedDigest = new SaltedDigestSha1().getDigest(authSubject.getEmail(), authSubject.getSalt()); return expectedDigest.equals(digest); } BCryptPasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); static String getPrefix(); }### Answer: @Test public void testIsValidPasswordResetDigest() { testIsValidPasswordResetDigest(new BCryptPasswordHandler(subject)); }
### Question: DigestValidator { public boolean validate(String sharedSecret) { if (!errors && setClientDate() && validateTimestamp() && validateHashedPart(sharedSecret)) { LOGGER.info("Digest successfully validated."); return true; } LOGGER.error("Digest validation failed."); return false; } DigestValidator(String digest); DigestValidator(String digest, int maxOffsetMinutes); boolean validate(String sharedSecret); String getUsername(); String getTimestamp(); String getUtcOffset(); }### Answer: @Test public void test() { String digest = DigestUtil.getDigest(username, sharedSecret); boolean isValid = new DigestValidator(digest,60).validate(sharedSecret); Assert.assertTrue("digest must be valid", isValid); } @Test public void testInvalid() { String digest = DigestUtil.getDigest(username, sharedSecret); boolean isValid = new DigestValidator(digest).validate("jinfizz"); Assert.assertFalse("digest must invalid", isValid); }
### Question: DefaultPasswordPolicy implements PasswordPolicy { public String generatePassword() { return random(6, LOWERCASE + UPPERCASE) + random(1, NUMBER) + random(1, PUNCT); } @Deprecated DefaultPasswordPolicy(); @Deprecated DefaultPasswordPolicy(String regEx, String errorMessageKey); @Override void configure(Properties platformConfig); boolean isValidPassword(char[] password); @Override ValidationResult validatePassword(String username, char[] currentPassword, char[] password); String getErrorMessageKey(); Pattern getPattern(); String generatePassword(); static final String REGEX; static final String ERROR_MSSG_KEY; }### Answer: @Test public void testGenerate() { for (int i = 0; i < 1000; i++) { String password = passwordPolicy.generatePassword(); assertValid(password); } }
### Question: DefaultPasswordPolicy implements PasswordPolicy { public boolean isValidPassword(char[] password) { return pattern.matcher(new String(password)).matches(); } @Deprecated DefaultPasswordPolicy(); @Deprecated DefaultPasswordPolicy(String regEx, String errorMessageKey); @Override void configure(Properties platformConfig); boolean isValidPassword(char[] password); @Override ValidationResult validatePassword(String username, char[] currentPassword, char[] password); String getErrorMessageKey(); Pattern getPattern(); String generatePassword(); static final String REGEX; static final String ERROR_MSSG_KEY; }### Answer: @Test public void testComplexRegex() { String expression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)" + "(?=.*[" + "\\x21-\\x2f" + "\\x3A-\\x40" + "\\x5b-\\x60" + "\\x7b-\\x7e" + "])" + "[\\x21-\\x7e]" + "{8,}$"; PasswordPolicy policy = new DefaultPasswordPolicy(expression, "dummy"); Assert.assertFalse(policy.isValidPassword("testtest".toCharArray())); Assert.assertFalse(policy.isValidPassword("TESTTEST".toCharArray())); Assert.assertFalse(policy.isValidPassword("12345678".toCharArray())); Assert.assertFalse(policy.isValidPassword("!!!!!!!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("testTEST".toCharArray())); Assert.assertFalse(policy.isValidPassword("test1234".toCharArray())); Assert.assertFalse(policy.isValidPassword("test!!!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("TEST1234".toCharArray())); Assert.assertFalse(policy.isValidPassword("TEST!!!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("1234!!!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("testTEST12".toCharArray())); Assert.assertFalse(policy.isValidPassword("testTEST!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("test1234!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("TEST1234!!".toCharArray())); Assert.assertFalse(policy.isValidPassword("Test!12".toCharArray())); Assert.assertFalse(policy.isValidPassword("Test12!".toCharArray())); Assert.assertFalse(policy.isValidPassword("12Test!".toCharArray())); Assert.assertFalse(policy.isValidPassword("12!Test".toCharArray())); Assert.assertFalse(policy.isValidPassword("!Test12".toCharArray())); Assert.assertFalse(policy.isValidPassword("!12Test".toCharArray())); Assert.assertTrue(policy.isValidPassword("teST12!!".toCharArray())); Assert.assertTrue(policy.isValidPassword("teST!!12".toCharArray())); Assert.assertTrue(policy.isValidPassword("TEst!!12".toCharArray())); Assert.assertTrue(policy.isValidPassword("TEst12!!".toCharArray())); Assert.assertTrue(policy.isValidPassword("12!!teST".toCharArray())); Assert.assertTrue(policy.isValidPassword("12!!TEst".toCharArray())); Assert.assertTrue(policy.isValidPassword("!!12teST".toCharArray())); Assert.assertTrue(policy.isValidPassword("!!12TEst".toCharArray())); }
### Question: Sha1PasswordHandler implements PasswordHandler { public void applyPassword(String password) { String salt = saltedDigest.getSalt(); String digest = saltedDigest.getDigest(password, salt); authSubject.setSalt(salt); authSubject.setDigest(digest); authSubject.setPasswordLastChanged(new Date()); } Sha1PasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); }### Answer: @Test public void testSavePassword() { PasswordHandler handler = new Sha1PasswordHandler(subject); handler.applyPassword(PASSWORD); Assert.assertNotNull(subject.getDigest()); Assert.assertTrue(!subject.getDigest().startsWith(BCryptPasswordHandler.getPrefix())); Assert.assertNotNull(subject.getSalt()); }
### Question: Sha1PasswordHandler implements PasswordHandler { public boolean isValidPassword(String password) { String digest = saltedDigest.getDigest(password, authSubject.getSalt()); return digest.equals(authSubject.getDigest()); } Sha1PasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); }### Answer: @Test public void testValidPassword() { subject.setDigest(SHA1_DIGEST); subject.setSalt(SHA1_SALT); PasswordHandler handler = new Sha1PasswordHandler(subject); assertTrue(handler.isValidPassword(PASSWORD)); } @Test public void testInvalidPassword() { subject.setDigest(SHA1_DIGEST.substring(1)); subject.setSalt(SHA1_SALT); PasswordHandler handler = new Sha1PasswordHandler(subject); assertFalse(handler.isValidPassword(PASSWORD)); }
### Question: RuleValidation { public static boolean email(String string) { return regExp(string, EMAIL_PATTERN); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testEmail() { assertTrue("email('[email protected]')"); assertTrue("email('[email protected]')"); assertFalse("email('mm@aiticon')"); assertFalse("email('@aiticon.de')"); }
### Question: Sha1PasswordHandler implements PasswordHandler { public String calculatePasswordResetDigest() { return saltedDigest.getDigest(authSubject.getEmail(), authSubject.getSalt()); } Sha1PasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); }### Answer: @Test public void testGetPasswordResetDigest() { subject.setSalt(SHA1_SALT); subject.setEmail(EMAIL); PasswordHandler handler = new Sha1PasswordHandler(subject); String digest = handler.calculatePasswordResetDigest(); Assert.assertEquals(SHA1_SALT, subject.getSalt()); Assert.assertEquals(SHA1_PW_RESET_DIGEST, digest); }
### Question: Sha1PasswordHandler implements PasswordHandler { public boolean isValidPasswordResetDigest(String digest) { return calculatePasswordResetDigest().equals(digest); } Sha1PasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); }### Answer: @Test public void testIsValidPasswordResetDigest() { testIsValidPasswordResetDigest(new Sha1PasswordHandler(subject)); }
### Question: SessionListener implements ServletContextListener, HttpSessionListener, ServletRequestListener { public void sessionCreated(HttpSessionEvent event) { createSession(event.getSession()); } void contextInitialized(ServletContextEvent sce); void contextDestroyed(ServletContextEvent sce); void sessionCreated(HttpSessionEvent event); void sessionDestroyed(HttpSessionEvent event); void requestInitialized(ServletRequestEvent sre); void requestDestroyed(ServletRequestEvent sre); static final String SESSION_MANAGER; static final String META_DATA; }### Answer: @Test public void testSessionCreated() { sessionListener.sessionCreated(new HttpSessionEvent(session1)); addRequest(session1); addRequest(session1); Assert.assertEquals(2, ((Session) session1.getAttribute(SessionListener.META_DATA)).getRequests()); }
### Question: SessionListener implements ServletContextListener, HttpSessionListener, ServletRequestListener { public void sessionDestroyed(HttpSessionEvent event) { HttpSession httpSession = event.getSession(); Environment env = DefaultEnvironment.get(httpSession); if (env.isSubjectAuthenticated()) { ApplicationContext ctx = env.getAttribute(Scope.PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT); ctx.getBean(CoreService.class).createEvent(Type.INFO, "session expired", httpSession); } Session session = getSession(httpSession); if (null != session) { LOGGER.info("Session destroyed: {} (created: {}, accessed: {}, requests: {}, domain: {}, user-agent: {})", session.getId(), DATE_PATTERN.format(session.getCreationTime()), DATE_PATTERN.format(session.getLastAccessedTime()), session.getRequests(), session.getDomain(), session.getUserAgent()); httpSession.removeAttribute(META_DATA); } else { LOGGER.info("Session destroyed: {} (created: {}, accessed: {})", httpSession.getId(), DATE_PATTERN.format(httpSession.getCreationTime()), DATE_PATTERN.format(httpSession.getLastAccessedTime())); } } void contextInitialized(ServletContextEvent sce); void contextDestroyed(ServletContextEvent sce); void sessionCreated(HttpSessionEvent event); void sessionDestroyed(HttpSessionEvent event); void requestInitialized(ServletRequestEvent sre); void requestDestroyed(ServletRequestEvent sre); static final String SESSION_MANAGER; static final String META_DATA; }### Answer: @Test public void testSessionDestroyed() { sessionListener.sessionCreated(new HttpSessionEvent(session1)); addRequest(session1); sessionListener.sessionCreated(new HttpSessionEvent(session2)); addRequest(session2); sessionListener.sessionDestroyed(new HttpSessionEvent(session1)); Assert.assertNull(session1.getAttribute(SessionListener.META_DATA)); Assert.assertNotNull(session2.getAttribute(SessionListener.META_DATA)); }
### Question: Controller extends DefaultServlet implements ContainerServlet { @Override protected void doPut(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (isServiceRequest(servletRequest)) { doGet(servletRequest, servletResponse); } else { LOGGER.debug("PUT not allowed for {}", servletRequest.getServletPath()); servletResponse.sendError(HttpStatus.FORBIDDEN.value()); } } Controller(); void serveResource(HttpServletRequest request, HttpServletResponse response); @Override void init(); Wrapper getWrapper(); void setWrapper(Wrapper wrapper); JspHandler getJspHandler(); }### Answer: @Test public void testWebservicePut() { prepareWebserice(HttpMethod.PUT); try { doPut(base.request, base.response); Assert.assertEquals("PUT webservice call", new String(base.out.toByteArray())); } catch (Exception e) { fail(e); } } @Test public void testStaticPut() { when(base.request.getServletPath()).thenReturn("/test.txt"); try { doPut(base.request, base.response); Assert.assertEquals(0, base.out.toByteArray().length); Mockito.verify(base.response).sendError(HttpStatus.FORBIDDEN.value()); } catch (Exception e) { fail(e); } }
### Question: RuleValidation { public static boolean equals(String string1, String string2) { return StringUtils.equals(string1, string2); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testEquals() { assertTrue("equals('a','a')"); assertTrue("equals('b','b')"); assertFalse("equals('a','A')"); assertFalse("equals('a',' A')"); }
### Question: Controller extends DefaultServlet implements ContainerServlet { @Override protected void doDelete(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (isServiceRequest(servletRequest)) { doGet(servletRequest, servletResponse); } else { LOGGER.debug("DELETE not allowed for {}", servletRequest.getServletPath()); servletResponse.sendError(HttpStatus.FORBIDDEN.value()); } } Controller(); void serveResource(HttpServletRequest request, HttpServletResponse response); @Override void init(); Wrapper getWrapper(); void setWrapper(Wrapper wrapper); JspHandler getJspHandler(); }### Answer: @Test public void testWebserviceDelete() { prepareWebserice(HttpMethod.DELETE); try { doDelete(base.request, base.response); Assert.assertEquals("DELETE webservice call", new String(base.out.toByteArray())); } catch (Exception e) { fail(e); } } @Test public void testStaticDelete() { when(base.request.getServletPath()).thenReturn("/test.txt"); try { doDelete(base.request, base.response); Assert.assertEquals(0, base.out.toByteArray().length); Mockito.verify(base.response).sendError(HttpStatus.FORBIDDEN.value()); } catch (Exception e) { fail(e); } }
### Question: RuleValidation { public static boolean regExp(String string, String regex) { return string.matches(regex); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testRegExp() { assertTrue("regExp('abc','[a-z]+')"); assertFalse("regExp('abc','[a-z]{4,}')"); }
### Question: RuleValidation { private static int size(Object item) { if (null == item) { return 0; } if (Collection.class.isAssignableFrom(item.getClass())) { return ((Collection<?>) item).size(); } if (CharSequence.class.isAssignableFrom(item.getClass())) { return ((CharSequence) item).length(); } throw new UnsupportedOperationException("can not invoke size() on object of type" + item.getClass().getName() + "!"); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testSize() { assertTrue("size(foo,3)"); assertFalse("size(foo,4)"); assertTrue("size(multifoo,4)"); assertFalse("size(multifoo,5)"); assertFalse("size(multibar,5)"); }
### Question: Controller extends DefaultServlet implements ContainerServlet { protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, wrapResponseForHeadRequest(response)); } Controller(); void serveResource(HttpServletRequest request, HttpServletResponse response); @Override void init(); Wrapper getWrapper(); void setWrapper(Wrapper wrapper); JspHandler getJspHandler(); }### Answer: @Test public void testHead() throws IOException, ServletException { when(base.request.getServletPath()).thenReturn("/test.txt"); doHead(base.request, base.response); Assert.assertEquals(0, base.out.size()); }
### Question: PageCacheFilter implements javax.servlet.Filter { static boolean isException(String exceptionsProp, String servletPath) { if (null != exceptionsProp) { Set<String> exceptions = new HashSet<>(Arrays.asList(exceptionsProp.split(StringUtils.LF))); for (String e : exceptions) { if (servletPath.startsWith(e.trim())) { return true; } } } return false; } void init(FilterConfig filterConfig); void destroy(); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); }### Answer: @Test public void testIsException() { String servletPath = "/foo/bar/lore/ipsum"; Assert.assertFalse(PageCacheFilter.isException("/foo/me", servletPath)); Assert.assertTrue(PageCacheFilter.isException(servletPath, servletPath)); Assert.assertTrue(PageCacheFilter.isException("/foo/bar/lore/", servletPath)); Assert.assertTrue(PageCacheFilter.isException("/foo/bar", servletPath)); Assert.assertTrue(PageCacheFilter.isException("/foo/", servletPath)); Assert.assertTrue(PageCacheFilter.isException("/", servletPath)); }
### Question: PageCacheFilter implements javax.servlet.Filter { static Integer getExpireAfterSeconds(Properties cachingTimes, boolean antStylePathMatching, String servletPath, Integer defaultValue) { if (null != cachingTimes && !cachingTimes.isEmpty()) { if (antStylePathMatching) { for (Object path : cachingTimes.keySet()) { AntPathMatcher matcher = new AntPathMatcher(); if (matcher.match(path.toString(), servletPath)) { Object entry = cachingTimes.get(path); return Integer.valueOf(entry.toString().trim()); } } } else { String[] pathSegements = servletPath.split(Path.SEPARATOR); int len = pathSegements.length; while (len > 0) { String segment = StringUtils.join(Arrays.copyOfRange(pathSegements, 0, len--), Path.SEPARATOR); Object entry = cachingTimes.get(segment); if (null != entry) { return Integer.valueOf(entry.toString().trim()); } } } } return defaultValue; } void init(FilterConfig filterConfig); void destroy(); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); }### Answer: @Test public void testGetExpireAfterSeconds() { Integer defaultCacheTime = Integer.valueOf(1800); Integer oneMin = Integer.valueOf(60); Integer tenMins = Integer.valueOf(600); Integer oneHour = Integer.valueOf(3600); Properties cachingTimes = new Properties(); String servletPath = "/foo/bar/lore/ipsum"; Integer expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, false, servletPath, defaultCacheTime); Assert.assertEquals(defaultCacheTime, expireAfterSeconds); cachingTimes.put("", oneMin); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, false, servletPath, defaultCacheTime); Assert.assertEquals(oneMin, expireAfterSeconds); cachingTimes.put(servletPath, oneMin); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, false, servletPath, defaultCacheTime); Assert.assertEquals(oneMin, expireAfterSeconds); cachingTimes.clear(); cachingTimes.put("/foo/bar/lore", tenMins); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, false, servletPath, defaultCacheTime); Assert.assertEquals(tenMins, expireAfterSeconds); cachingTimes.clear(); cachingTimes.put("/foo", oneHour); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, false, servletPath, defaultCacheTime); Assert.assertEquals(oneHour, expireAfterSeconds); } @Test public void testGetExpireAfterSecondsAntStyle() { Integer defaultCacheTime = Integer.valueOf(1800); Integer oneMin = Integer.valueOf(60); Integer tenMins = Integer.valueOf(600); Integer oneHour = Integer.valueOf(3600); Properties cachingTimes = new Properties(); String servletPath = "/foo/bar/lore/ipsum"; Integer expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, true, servletPath, defaultCacheTime); Assert.assertEquals(defaultCacheTime, expireAfterSeconds); cachingTimes.put("/**", oneMin); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, true, servletPath, defaultCacheTime); Assert.assertEquals(oneMin, expireAfterSeconds); cachingTimes.put(servletPath, oneMin); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, true, servletPath, defaultCacheTime); Assert.assertEquals(oneMin, expireAfterSeconds); cachingTimes.clear(); cachingTimes.put("/foo/bar/lore/**", tenMins); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, true, servletPath, defaultCacheTime); Assert.assertEquals(tenMins, expireAfterSeconds); cachingTimes.clear(); cachingTimes.put("/foo/**", oneHour); expireAfterSeconds = PageCacheFilter.getExpireAfterSeconds(cachingTimes, true, servletPath, defaultCacheTime); Assert.assertEquals(oneHour, expireAfterSeconds); }
### Question: JspExtensionFilter implements Filter { protected String doReplace(List<RedirectRule> redirectRules, String sourcePath, String domain, String jspExtension, String content) { long startTime = System.currentTimeMillis(); int numRules = 0; if (null != redirectRules) { numRules = redirectRules.size(); for (RedirectRule rule : redirectRules) { content = rule.apply(content); if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} has been applied", rule); } } } if (content.contains(jspExtension)) { Pattern domainPattern = getDomainPattern(domain, jspExtension); content = domainPattern.matcher(content).replaceAll("$1$2"); if (LOGGER.isTraceEnabled()) { LOGGER.trace("replace with pattern {} has been applied", domainPattern); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("handling JSP extensions for source '{}' took {}ms ({} redirect-rules processed)", sourcePath, System.currentTimeMillis() - startTime, numRules); } return content; } JspExtensionFilter(); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); void init(FilterConfig filterConfig); void destroy(); }### Answer: @Test public void testReplace() { Assert.assertEquals("<a href=\"/de/index\">", doReplace("<a href=\"/de/index.jsp\">")); Assert.assertEquals("<a href=\"/de/seite\">", doReplace("<a href=\"/en/page.jsp\">")); Assert.assertEquals("url='/de/seite'", doReplace("url='/en/page.jsp'")); Assert.assertEquals("url='/de/foo' '/en/bar'", doReplace("url='/de/foo.jsp' '/en/bar.jsp'")); Assert.assertEquals("/app", doReplace("/app")); } @Test public void testStripJsp() { assertUnchanged("<a href=\"/de/index\">"); assertUnchanged("<a href=\"/de/seite\">"); assertUnchanged("/de/foobar.jsp"); Assert.assertEquals("<a href=\"/de/foo\">", doReplace("<a href=\"/de/foo.jsp\">")); Assert.assertEquals("'/en/bar'", doReplace("'/en/bar.jsp'")); Assert.assertEquals("/de/index", doReplace("/en/index.jsp")); } @Test public void testReplaceDomain() { assertUnchanged("<a href=\"" + domain + "/de/seite\">"); assertUnchanged("<a href=\"" + domain + "/de/foo\">"); assertUnchanged("http: assertUnchanged("'http: Assert.assertEquals("url='" + domain + "/de/seite'", doReplace("url='" + domain + "/en/page.jsp'")); Assert.assertEquals("url='" + domain + "/de/foo'", doReplace("url='" + domain + "/de/foo.jsp'")); Assert.assertEquals(domain + "/de/foo", doReplace(domain + "/de/foo.jsp")); Assert.assertEquals("<a href=\"" + domain + "/de/seite\">", doReplace("<a href=\"" + domain + "/en/page.jsp\">")); assertUnchanged("http: }
### Question: MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo); }### Answer: @Test public void testSystem() throws Exception { SiteImpl site = getSite(); PathInfo path = getPath(site, "/health/system"); DefaultEnvironment env = getEnv(); MockHttpServletResponse resp = new MockHttpServletResponse(); monitoringHandler.handle(getRequest(ctx), resp, env, site, path); String content = resp.getContentAsString(); Assert.assertTrue(content.contains("java.specification.name")); Assert.assertTrue(content.contains("java.specification.vendor")); Assert.assertTrue(content.contains("java.specification.version")); } @Test public void testEnvironment() throws Exception { SiteImpl site = getSite(); PathInfo path = getPath(site, "/health/environment"); DefaultEnvironment env = getEnv(); MockHttpServletResponse resp = new MockHttpServletResponse(); monitoringHandler.handle(getRequest(ctx), resp, env, site, path); String content = resp.getContentAsString(); Assert.assertTrue(content.contains("JAVA_HOME")); } @Test public void test() throws Exception { SiteImpl site = getSite(); PathInfo path = getPath(site, "/health"); DefaultEnvironment env = getEnv(); MockHttpServletResponse resp = new MockHttpServletResponse(); MockHttpServletRequest req = getRequest(ctx); monitoringHandler.handle(req, resp, env, site, path); String responseBody = resp.getContentAsString().replaceAll("\\d{10}", "1204768206"); WritingJsonValidator.validate(responseBody, "rest/health.json"); req = getRequest(ctx); req.addParameter("details", "true"); resp = new MockHttpServletResponse(); monitoringHandler.handle(req, resp, env, site, path); responseBody = resp.getContentAsString().replaceAll("\\d{10}", "1204768206"); WritingJsonValidator.validate(responseBody, "rest/health-detailed.json"); }
### Question: RuleValidation { public static boolean sizeMin(Object item, int min) { return size(item) >= min; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testSizeMin() { assertTrue("sizeMin(foo,3)"); assertFalse("sizeMin(foo,4)"); assertTrue("sizeMin(multifoo,4)"); assertFalse("sizeMin(multifoo,5)"); assertFalse("sizeMin(multibar,5)"); }
### Question: ImageProcessor { public ImageProcessor quality(double quality) { op.quality(quality); return this; } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath, boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight, int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); }### Answer: @Test public void testQuality() throws IOException { File targetFile = new File(targetFolder, "desert-quality-10.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToWidth(384).quality(10d); ip.getImage(); }
### Question: GuiHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } GuiHandler(File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo); static final String PLATFORM_MESSAGES; }### Answer: @Test public void testRedirectToFirstVisibleApplication() throws ServletException, IOException { servletRequest.setSession(session); MockitoAnnotations.initMocks(this); Mockito.when(platformProperties.getString(Platform.Property.VHOST_MODE)) .thenReturn(VHostMode.NAME_BASED.name()); Mockito.when(platformProperties.getString(Platform.Property.TEMPLATE_FOLDER)).thenReturn("template"); Environment initialEnv = DefaultEnvironment.get(servletContext); initialEnv.setAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG, platformProperties); initialEnv.setAttribute(Scope.PLATFORM, Platform.Environment.SITES, new HashMap<>()); DefaultEnvironment env = DefaultEnvironment.get(servletContext, servletRequest); Mockito.when(siteProperties.getString(SiteProperties.TEMPLATE, null)).thenReturn("appng"); Mockito.when(siteProperties.getString(SiteProperties.DEFAULT_APPLICATION)).thenReturn("manager"); Mockito.when(siteProperties.getString(SiteProperties.MANAGER_PATH)).thenReturn("/manager"); Mockito.when(site.getName()).thenReturn("localhost"); Mockito.when(site.getProperties()).thenReturn(siteProperties); Set<Application> applications = new HashSet<>(); applications.add(applicationB); applications.add(application); Mockito.when(site.getApplications()).thenReturn(applications); Mockito.when(application.getName()).thenReturn("someapp"); Mockito.when(applicationB.isHidden()).thenReturn(true); Mockito.when(subject.hasApplication(application)).thenReturn(true); Mockito.when(subject.isAuthenticated()).thenReturn(true); env.setSubject(subject); Map<String, Site> siteMap = new HashMap<>(); env.setAttribute(Scope.PLATFORM, Platform.Environment.SITES, siteMap); PathInfo pathInfo = new PathInfo("localhost", "http: Arrays.asList("/assets"), Arrays.asList("/de"), "/repository", "jsp"); new GuiHandler(null).handle(servletRequest, servletResponse, env, site, pathInfo); Mockito.verify(site).sendRedirect(env, "/manager/localhost/someapp"); }
### Question: RepositoryWatcher implements Runnable { void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } RepositoryWatcher(Site site, String jspExtension, String ruleSourceSuffix); RepositoryWatcher(); void run(); boolean needsToBeWatched(); static final String DEFAULT_RULE_SUFFIX; }### Answer: @Test(timeout = 100000) public void test() throws Exception { ClassLoader classLoader = RepositoryWatcherTest.class.getClassLoader(); URL url = classLoader.getResource("repository/manager/www"); String rootDir = FilenameUtils.normalize(new File(url.toURI()).getPath(), true); String urlrewrite = classLoader.getResource("conf/urlrewrite.xml").getFile(); RepositoryWatcher repositoryWatcher = new RepositoryWatcher(); SiteImpl site = new SiteImpl(); site.setHost("localhost"); PropertyHolder siteProps = new PropertyHolder(); siteProps.addProperty(SiteProperties.CACHE_TIME_TO_LIVE, 1800, null, Property.Type.INT); siteProps.addProperty(SiteProperties.CACHE_STATISTICS, true, null, Property.Type.BOOLEAN); site.setProperties(siteProps); CacheService.createCacheManager(HazelcastConfigurer.getInstance(null), false); Cache<String, CachedResponse> cache = CacheService.createCache(site); String fehlerJsp = "/de/fehler.jsp"; String testJsp = "/de/test.jsp"; String keyFehlerJsp = "GET" + fehlerJsp; String keyTestJsp = "GET" + testJsp; int timeToLive = 1800; HttpServletRequest req = new MockHttpServletRequest(); String contentType = "text/plain"; byte[] bytes = "a value".getBytes(); cache.put(keyFehlerJsp, new CachedResponse(keyFehlerJsp, site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put(keyTestJsp, new CachedResponse(keyTestJsp, site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put("GET/de/error", new CachedResponse("GET/de/error", site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put("GET/de/fault", new CachedResponse("GET/de/fault", site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); int size = getCacheSize(cache); Assert.assertEquals(4, size); repositoryWatcher.init(cache, rootDir, new File(urlrewrite), RepositoryWatcher.DEFAULT_RULE_SUFFIX, Arrays.asList("de")); Long forwardsUpdatedAt = repositoryWatcher.forwardsUpdatedAt; ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("repositoryWatcher").setDaemon(true).build(); ExecutorService executor = Executors.newSingleThreadExecutor(tf); executor.execute(repositoryWatcher); FileUtils.touch(new File(rootDir, fehlerJsp)); FileUtils.touch(new File(rootDir, testJsp)); FileUtils.touch(new File(urlrewrite)); while (getCacheSize(cache) != 0 || forwardsUpdatedAt == repositoryWatcher.forwardsUpdatedAt) { Thread.sleep(50); } Assert.assertNull(cache.get(keyFehlerJsp)); Assert.assertNull(cache.get(keyTestJsp)); Assert.assertNull(cache.get("GET/de/error")); Assert.assertNull(cache.get("GET/de/fault")); Assert.assertEquals(0, getCacheSize(cache)); Assert.assertTrue(repositoryWatcher.forwardsUpdatedAt > forwardsUpdatedAt); }
### Question: ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } ApplicationPostProcessor(Site site, Application application, DatabaseConnection databaseConnection, CacheManager platformCacheManager, Collection<String> dictionaryNames); void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory); int getOrder(); }### Answer: @Test public void testPostProcessBeanFactory() { Site site = Mockito.mock(Site.class); Application application = Mockito.mock(Application.class); DatasourceConfigurer datasourceConfigurer = Mockito.mock(DatasourceConfigurer.class); DatabaseConnection databaseConnection = new DatabaseConnection(); ArrayList<String> dictionaryNames = new ArrayList<>(); ApplicationPostProcessor applicationPostProcessor = new ApplicationPostProcessor(site, application, databaseConnection, null, dictionaryNames); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerSingleton("mockConfigurer", datasourceConfigurer); ApplicationCacheManager cacheManager = Mockito.mock(ApplicationCacheManager.class); beanFactory.registerSingleton("cacheManager", cacheManager); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); beanFactory.registerSingleton("messageSource", messageSource); beanFactory.registerSingleton("additionalMessageSource", new StaticMessageSource()); applicationPostProcessor.postProcessBeanFactory(beanFactory); Mockito.verify(datasourceConfigurer).configure(databaseConnection); Mockito.verify(cacheManager).initialize(site, application, null); Assert.assertEquals(site, beanFactory.getBean("site")); Assert.assertEquals(application, beanFactory.getBean("application")); Assert.assertEquals(site, beanFactory.getBean(Site.class)); Assert.assertEquals(application, beanFactory.getBean(Application.class)); Assert.assertTrue(messageSource.getParentMessageSource() instanceof MessageSourceChain); Assert.assertTrue(dictionaryNames.contains("messages-core")); }
### Question: SubjectImpl implements Subject, Auditable<Integer> { @Column(name = "locked") public boolean isLocked() { return locked; } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); }### Answer: @Test public void testIsLocked() { SubjectImpl s = new SubjectImpl(); Date now = new Date(); Assert.assertFalse(s.isExpired(now)); s.setExpiryDate(now); Assert.assertFalse(s.isExpired(now)); Assert.assertFalse(s.isExpired(DateUtils.addMinutes(now, -1))); Assert.assertTrue(s.isExpired(DateUtils.addMilliseconds(now, 1))); Assert.assertTrue(s.isExpired(DateUtils.addSeconds(now, 1))); Assert.assertTrue(s.isExpired(DateUtils.addMinutes(now, 1))); }
### Question: SubjectImpl implements Subject, Auditable<Integer> { @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); }### Answer: @Test public void testIsInactive() { SubjectImpl s = new SubjectImpl(); Date now = new Date(); s.setLastLogin(now); int inactiveLockPeriod = 10; Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Date plusTenDays = DateUtils.addDays(now, inactiveLockPeriod); Assert.assertFalse(s.isInactive(plusTenDays, inactiveLockPeriod)); Assert.assertTrue(s.isInactive(DateUtils.addMilliseconds(plusTenDays, 1), inactiveLockPeriod)); Assert.assertTrue(s.isInactive(DateUtils.addDays(now, 11), inactiveLockPeriod)); }
### Question: RuleValidation { public static boolean sizeMax(Object item, int max) { return size(item) <= max; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testSizeMax() { assertTrue("sizeMax(foo,4)"); assertFalse("sizeMax(foo,2)"); assertTrue("sizeMax(multifoo,4)"); assertFalse("sizeMax(multifoo,3)"); assertTrue("sizeMax(multibar,3)"); }
### Question: PropertyImpl extends SimpleProperty implements Property, Auditable<String>, Comparable<Property> { @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } PropertyImpl(); PropertyImpl(String name, String value); PropertyImpl(String name, String value, String defaultValue); @Override @Id @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 3, max = 255, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getName(); @Override boolean isMandatory(); @Override @Transient String getId(); @Override @Version Date getVersion(); @Override @Column(name = "value") String getActualString(); @Override @Column(name = "defaultValue") String getDefaultString(); @Override @Column(name = "description", length = 1024) String getDescription(); @Override @Column(name = "blobValue") @Lob byte[] getBlob(); @Override @Column(name = "clobValue") @Lob String getClob(); @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) Type getType(); @Override int hashCode(); @Override boolean equals(Object o); }### Answer: @Test public void testDetermineType() { PropertyImpl booleanProp = new PropertyImpl("booleanProp", "true"); booleanProp.determineType(); Assert.assertEquals(Property.Type.BOOLEAN, booleanProp.getType()); PropertyImpl intProp = new PropertyImpl("intProp", "5"); intProp.determineType(); Assert.assertEquals(Property.Type.INT, intProp.getType()); PropertyImpl decimalProp = new PropertyImpl("decimalProp", "5.42"); decimalProp.determineType(); Assert.assertEquals(Property.Type.DECIMAL, decimalProp.getType()); PropertyImpl multilineProp = new PropertyImpl("multilineProp", null); multilineProp.setClob("textProp"); multilineProp.determineType(); Assert.assertEquals(Property.Type.MULTILINE, multilineProp.getType()); PropertyImpl textProp = new PropertyImpl("textProp", "test"); textProp.determineType(); Assert.assertEquals(Property.Type.TEXT, textProp.getType()); }
### Question: SiteImpl implements Site, Auditable<Integer> { private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); }### Answer: @Test public void testCloseClassloader() throws IOException { site.setSiteApplications(new HashSet<>()); site.closeSiteContext(); try { URLClassLoader.class.getMethod("close"); Assert.assertTrue("siteclassloader should be closed", isClosed); } catch (NoSuchMethodException e) { Assert.assertFalse("siteclassloader should not be closed", isClosed); } }
### Question: ActionHelper { public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); }### Answer: @Test public void testDeselectAllOptions() { ResponseEntity<Action> actionEntity = new ResponseEntity<>(new Action(), HttpStatus.OK); ActionField field = getSelectionField(); Option a = getOption("a", true); field.getOptions().getEntries().add(a); Option b = getOption("b", true); field.getOptions().getEntries().add(b); Action action = actionEntity.getBody(); action.setFields(new ArrayList<>()); action.getFields().add(field); ActionHelper.create(actionEntity).deselectAllOptions(field.getName()); Assert.assertFalse(a.isSelected()); Assert.assertFalse(b.isSelected()); }
### Question: ActionHelper { public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); }### Answer: @Test public void testSetFieldValue() { Action action = new Action(); ResponseEntity<Action> actionEntity = new ResponseEntity<>(action, HttpStatus.OK); ActionField field = new ActionField(); field.setName("field"); field.setFieldType(FieldType.TEXT); action.setFields(new ArrayList<>()); action.getFields().add(field); ActionHelper actionHelper = ActionHelper.create(actionEntity); Assert.assertNull(actionHelper.getField("field").get().getValue()); actionHelper.setFieldValue("field", "a"); Assert.assertEquals("a", actionHelper.getField("field").get().getValue()); }
### Question: RestClient { protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id, MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable, MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId, String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); }### Answer: @Test public void testCookies() { Map<String, String> cookies = new HashMap<>(); cookies.put("foo", "bar"); cookies.put("lore", "ipsum"); RestClient restClient = new RestClient("foo", cookies); List<String> cookieList = restClient.getHeaders(false).get(HttpHeaders.COOKIE); Assert.assertTrue(cookieList.contains("foo=bar")); Assert.assertTrue(cookieList.contains("lore=ipsum")); }
### Question: RestClient { protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id, MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable, MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId, String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); }### Answer: @Test public void testSetCookies() { RestClient restClient = new RestClient("foo"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.SET_COOKIE, "foo=bar"); headers.add(HttpHeaders.SET_COOKIE, "lore=ipsum;"); restClient.setCookies(new ResponseEntity<>(headers, HttpStatus.OK)); Map<String, String> cookies = restClient.getCookies(); Assert.assertEquals("bar", cookies.get("foo")); Assert.assertEquals("ipsum", cookies.get("lore")); }
### Question: RestClient { public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id, MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable, MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId, String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); }### Answer: @Test public void testDataSource() throws URISyntaxException { RestClient restClient = new RestClient("http: protected <IN, OUT> RestResponseEntity<IN> exchange(URI uri, OUT body, HttpMethod method, Class<IN> returnType) { Assert.assertEquals( "http: uri.toString()); return null; } }; MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("foo", "bar"); parameters.add("47", "11"); Pageable pageable = new Pageable().addSort("foo", OrderEnum.ASC).addSort("bar", OrderEnum.DESC); restClient.datasource("application", "foobar", pageable, parameters); }
### Question: RuleValidation { public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testSizeMinMax() { assertTrue("sizeMinMax(foo,1,3)"); assertFalse("sizeMinMax(foo,4,5)"); assertTrue("sizeMinMax(multifoo,1,4)"); assertFalse("sizeMinMax(multifoo,1,3)"); assertFalse("sizeMinMax(multifoo,5,7)"); assertFalse("sizeMinMax(multibar,1,3)"); assertFalse("sizeMinMax(multibar,5,7)"); }
### Question: HashPassword implements ExecutableCliCommand { public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } HashPassword(); HashPassword(String password); HashPassword(boolean interactive); void execute(CliEnvironment cle); }### Answer: @Test(expected = BusinessException.class) public void testInvalid() throws BusinessException { new HashPassword("").execute(cliEnv); }
### Question: CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); static String CURRENT_COMMAND; static final String APPNG_HOME; }### Answer: @Test public void testAppngHome() { File result = path.getFile(APPNG_ROOT); Mockito.when(cliBootstrapEnvironment.getFileFromEnv(CliBootstrap.APPNG_HOME)).thenReturn(result); Assert.assertEquals(result, CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment)); } @Test public void testAppngHomeUndefined() { try { CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment); Assert.fail("IllegalArgumentException expected, but no exception has been thrown."); } catch (IllegalArgumentException e) { Assert.assertEquals("APPNG_HOME is not defined!", e.getMessage()); } } @Test public void testAppngHomeInvalid() { File result = path.getFile("invalid-path"); Mockito.when(cliBootstrapEnvironment.getFileFromEnv(CliBootstrap.APPNG_HOME)).thenReturn(result); try { CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment); Assert.fail("IllegalArgumentException expected, but no exception has been thrown."); } catch (IllegalArgumentException e) { Assert.assertEquals("The path specified in APPNG_HOME does not exist: " + result, e.getMessage()); } }
### Question: RuleValidation { public static boolean number(String string) { return regExp(string, EXP_NUMBER); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testNumber() { assertFalse("number(foo)"); assertTrue("number(bar)"); }
### Question: PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); }### Answer: @Test public void testTabbedEmpty() throws BusinessException { String table = prettyTable.render(true, true); Assert.assertEquals("\nA\tB\tC\n", table); } @Test public void testTableEmpty() throws BusinessException, IOException { String table = prettyTable.render(false, true); URL resource = getClass().getClassLoader().getResource("PrettyTableTest-empty.txt"); String expected = FileUtils.readFileToString(new File(resource.getFile()), Charset.defaultCharset()); Assert.assertEquals(expected, table); }
### Question: PrettyTable { static String tabbed(String n) { return n + PrettyTable.TAB; } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); }### Answer: @Test public void testTabbed() throws BusinessException { prettyTable.addRow(1, null, 3); String table = prettyTable.render(true, true); Assert.assertEquals("\nA\tB\tC\n1\tnull\t3\n", table); }
### Question: PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); @Override void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor); }### Answer: @Test public void testEditPerson() throws ProcessingException, IOException { CallableAction callableAction = getAction("personEvent", "editPerson").withParam(FORM_ACTION, "editPerson") .withParam("id", "1").getCallableAction(new Person(1, "Luke the Duke", "Skywalker")); callableAction.perform(); WritingXmlValidator.validateXml(callableAction.getAction(), "xml/PersonActionTest-testEditPerson.xml"); } @Test public void testCreatePerson() throws ProcessingException, IOException { CallableAction callableAction = getAction("personEvent", "createPerson").withParam(FORM_ACTION, "createPerson") .getCallableAction(new Person(null, "Obi Wan", "Kenobi")); callableAction.perform(); WritingXmlValidator.validateXml(callableAction.getAction(), "xml/PersonActionTest-testCreatePerson.xml"); }
### Question: Updater { protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request); }### Answer: @Test public void testUpdateAppNGizer() throws Exception { target = UpNGizr.appNGizerHome; Resource resource = getResource("appng-appngizer"); new Updater(new MockServletContext()).updateAppNGizer(resource, target); assertFolderNotEmpty("WEB-INF"); File metaInf = assertFolderNotEmpty("META-INF"); Assert.assertTrue(new File(metaInf, "MANIFEST.MF").exists()); assertFolderNotEmpty("WEB-INF/classes/org/appng/appngizer/model/"); assertFolderNotEmpty("WEB-INF/classes/org/appng/appngizer/controller/"); assertFolderNotEmpty("WEB-INF/lib"); }
### Question: Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request); }### Answer: @Test public void testCheckVersionAvailable() throws IOException { ResponseEntity<Void> checkVersionAvailable = new Updater(new MockServletContext()) .checkVersionAvailable("1.17.0", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, checkVersionAvailable.getStatusCode()); } @Test public void testCheckVersionNotAvailable() throws IOException { ResponseEntity<Void> checkVersionAvailable = new Updater(new MockServletContext()) .checkVersionAvailable("0.8.15", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.NOT_FOUND, checkVersionAvailable.getStatusCode()); }
### Question: RuleValidation { public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; }### Answer: @Test public void testNumberFractionDigits() { assertFalse("numberFractionDigits(foobar,1,1)"); assertFalse("numberFractionDigits(foobar,1,2)"); assertFalse("numberFractionDigits(foobar,2,1)"); assertFalse("numberFractionDigits(foobar,2,2)"); assertFalse("numberFractionDigits(foobar,3,1)"); assertTrue("numberFractionDigits(foobar,3,2)"); assertTrue("numberFractionDigits(foobar,3,3)"); assertTrue("numberFractionDigits(foobar,3,4)"); assertTrue("numberFractionDigits(foobar,4,3)"); assertTrue("numberFractionDigits(foobar,4,4)"); }
### Question: Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request); }### Answer: @Test public void testGetStartPage() throws IOException, URISyntaxException { ResponseEntity<String> startPage = new Updater(new MockServletContext()).getStartPage("1.17.0", "myTarget", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, startPage.getStatusCode()); List<String> lines = Files.readAllLines(new File("src/test/resources/startpage.html").toPath()); List<String> actualLines = Arrays.asList(startPage.getBody().split(System.lineSeparator())); int size = lines.size(); Assert.assertEquals(size, actualLines.size()); for (int i = 0; i < size; i++) { Assert.assertEquals("error in line " + (i + 1), lines.get(i), actualLines.get(i)); } } @Test public void testGetStartPageWithLocalHostName() throws IOException, URISyntaxException { MockServletContext context = new MockServletContext(); context.setInitParameter("useFQDN", "true"); ResponseEntity<String> startPage = new Updater(context).getStartPage("1.17.0", "myTarget", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, startPage.getStatusCode()); Assert.assertTrue(startPage.getBody().contains(InetAddress.getLocalHost().getCanonicalHostName())); }
### Question: Parameter extends BodyTagSupport { public Parameter() { } Parameter(); @Override int doEndTag(); String getName(); void setName(String name); boolean isUnescape(); void setUnescape(boolean unescape); @Override String toString(); }### Answer: @Test public void testParameter() throws IOException, JspException { StringWriter targetWriter = new StringWriter(); Parameter p1 = new Parameter(); p1.setName("param1"); p1.setBodyContent(new MockBodyContent("value1", targetWriter)); p1.setParent(this); p1.doEndTag(); Parameter p2 = new Parameter(); p2.setUnescape(true); p2.setBodyContent(new MockBodyContent("&quot;&Auml;&quot;", targetWriter)); p2.setName("param2"); p2.setParent(this); p2.doEndTag(); Parameter p3 = new Parameter(); p3.setName("param3"); p3.setParent(this); p3.doEndTag(); Assert.assertEquals("value1", parameters.get("param1")); Assert.assertEquals("\"Ä\"", parameters.get("param2")); Assert.assertNull(parameters.get("param3")); Assert.assertEquals("", targetWriter.toString()); }
### Question: Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testWriteToUrl() { Attribute attribute = init(Mode.WRITE, Scope.URL); attribute.doStartTag(); } @Test(expected = UnsupportedOperationException.class) public void testWriteToSite() { Attribute attribute = init(Mode.WRITE, Scope.SITE); attribute.doStartTag(); } @Test(expected = UnsupportedOperationException.class) public void testWriteToPlatform() { Attribute attribute = init(Mode.WRITE, Scope.PLATFORM); attribute.doStartTag(); }
### Question: MultiSiteSupport { public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } void process(Environment env, String application, HttpServletRequest servletRequest); void process(Environment env, String application, String method, HttpServletRequest servletRequest); SiteImpl getCallingSite(); SiteImpl getExecutingSite(); ApplicationProvider getApplicationProvider(); }### Answer: @Test public void test() { MultiSiteSupport multiSiteSupport = new MultiSiteSupport(); String siteName = "localhost"; String applicationName = "application"; MockServletContext servletContext = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setSession(new MockHttpSession(servletContext)); MockPageContext pageContext = new MockPageContext(servletContext, request); Properties properties = Mockito.mock(Properties.class); Mockito.when(properties.getString(Platform.Property.VHOST_MODE)).thenReturn(VHostMode.NAME_BASED.name()); Map<String, Object> platformScope = new ConcurrentHashMap<>(); platformScope.put(Platform.Environment.PLATFORM_CONFIG, properties); Site site = Mockito.mock(SiteImpl.class); Mockito.when(site.getName()).thenReturn(siteName); Mockito.when(site.getHost()).thenReturn(siteName); Mockito.when(site.getDomain()).thenReturn(siteName); Mockito.when(site.getProperties()).thenReturn(Mockito.mock(Properties.class)); Map<String, Site> siteMap = new HashMap<>(); siteMap.put(siteName, site); platformScope.put(Platform.Environment.SITES, siteMap); servletContext.setAttribute(Scope.PLATFORM.name(), platformScope); DefaultEnvironment environment = DefaultEnvironment.get(pageContext); ApplicationContext ctx = Mockito.mock(ApplicationContext.class); environment.setAttribute(PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT, ctx); CoreService coreService = Mockito.mock(CoreService.class); Mockito.when(ctx.getBean(CoreService.class)).thenReturn(coreService); Mockito.when(coreService.getGrantingSite(siteName, applicationName)).thenReturn(null); try { multiSiteSupport.process(environment, applicationName, "method", request); Assert.fail("must throw exception"); } catch (Exception e) { Assert.assertEquals("no application '" + applicationName + "' for site '" + siteName + "'", e.getMessage()); } }
### Question: Permission extends TagSupport { @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } @Override int doStartTag(); String getPermission(); void setPermission(String permission); String getApplication(); void setApplication(String application); }### Answer: @Test public void test() throws JspException { PageContext pageContext = AttributeTest.setupTagletTest(); DefaultEnvironment environment = DefaultEnvironment.get(pageContext); environment.setSubject(new SubjectImpl()); final MultiSiteSupport mock = Mockito.mock(MultiSiteSupport.class); ApplicationProvider app = Mockito.mock(ApplicationProvider.class); Mockito.when(app.getProperties()).thenReturn(Mockito.mock(Properties.class)); Mockito.when(app.getProperties().getBoolean("permissionsEnabled", true)).thenReturn(false); Mockito.when(mock.getApplicationProvider()).thenReturn(app); Mockito.when(mock.getExecutingSite()).thenReturn(Mockito.mock(SiteImpl.class)); Permission permission = new Permission() { @Override protected MultiSiteSupport processMultiSiteSupport(Environment env, HttpServletRequest servletRequest) throws JspException { return mock; } }; permission.setPageContext(pageContext); Assert.assertEquals(Tag.EVAL_BODY_INCLUDE, permission.doStartTag()); }
### Question: TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); }### Answer: @Test public void testTaglet() throws Exception { Mockito.when(taglet.processTaglet(site, application, request, tagletAttributes)).thenReturn("a taglet"); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(taglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertTrue(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(taglet).processTaglet(site, application, request, tagletAttributes); Assert.assertEquals("a taglet", writer.toString()); } @Test public void testGlobalTaglet() throws Exception { Mockito.when(globalTaglet.processTaglet(site, site, application, request, tagletAttributes)) .thenReturn("a global taglet"); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(globalTaglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertTrue(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(globalTaglet).processTaglet(site, site, application, request, tagletAttributes); Assert.assertEquals("a global taglet", writer.toString()); } @Test public void testPageProcessor() throws Exception { Taglet myTaglet = Mockito.spy(new MyTaglet()); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(myTaglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertFalse(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(myTaglet).processTaglet(site, application, request, tagletAttributes); Assert.assertEquals("MyTaglet", writer.toString()); }