src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
CoreService { protected void saveProperties(Properties properties) { Set<String> propertyNames = properties.getPropertyNames(); PropertyHolder propertyHolder = (PropertyHolder) properties; propertyNames.forEach(name -> saveProperty((PropertyImpl) propertyHolder.getProperty(name))); } Subject createSubject(SubjectImpl ... | @Test public void testSaveProperties() { List<Property> props = new ArrayList<>(); PropertyImpl a = new PropertyImpl("foobaz.a", "a"); PropertyImpl b = new PropertyImpl("foobaz.b", "b"); props.add(a); props.add(b); coreService.saveProperties(new PropertyHolder("foobaz.", props)); assertEquals(a, coreService.getProperty... |
CoreService { public PropertyImpl saveProperty(PropertyImpl property) { return propertyRepository.save(property); } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boole... | @Test public void testSaveProperty() { PropertyImpl property = coreService.saveProperty(new PropertyImpl("prop1", "value")); assertNotNull(property); assertNotNull(property.getVersion()); assertEquals("prop1", property.getId()); assertEquals("value", property.getString()); } |
CoreService { public SiteImpl shutdownSite(Environment env, String siteName) { return shutdownSite(env, siteName, false); } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMod... | @Test @Ignore public void testShutdownSite() { } |
CoreService { protected void synchronizeApplicationResources(Environment env, Application application, boolean isFileBased) throws BusinessException { String convertDirection = ""; try { Application currentApplication = applicationRepository.findOne(application.getId()); File applicationFolder = getApplicationFolder(en... | @Test @Ignore public void testSynchronizeApplicationResources() { } |
CoreService { protected MigrationStatus unlinkApplicationFromSite(SiteApplication siteApplication) { Site site = siteApplication.getSite(); ((SiteImpl) site).getSiteApplications().remove(siteApplication); siteApplicationRepository.delete(siteApplication); deleteApplicationPropertiesFromSite(site, siteApplication.getApp... | @Test public void testUnlinkApplicationFromSiteIntegerString() { MigrationStatus migrationStatus = coreService.unlinkApplicationFromSite(1, 1); assertEquals(MigrationStatus.NO_DB_SUPPORTED, migrationStatus); } |
CoreService { public void unsetReloadRequired(SiteApplication siteApplication) { siteApplication.setReloadRequired(false); siteApplicationRepository.findOne(siteApplication.getSiteApplicationId()).setReloadRequired(false); } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformPr... | @Test @Ignore public void testUnsetReloadRequired() { } |
CoreService { public PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword, char[] password, SubjectImpl currentSubject) { PasswordPolicy.ValidationResult validationResult = policy.validatePassword(currentSubject.getAuthName(), currentPassword, password); if (validationResult.isVa... | @Test public void testUpdatePassword() throws BusinessException { SubjectImpl subject = coreService.getSubjectByName("subject-3", false); PasswordPolicy dummyPolicy = new ConfigurablePasswordPolicy() { public ValidationResult validatePassword(String username, char[] currentPassword, char[] password) { return new Valida... |
CoreService { public SubjectImpl updateSubject(SubjectImpl subject) { return subjectRepository.save(subject); } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean p... | @Test @Ignore public void testUpdateSubject() { } |
DatabaseService extends MigrationService { @Transactional public DatabaseConnection initDatabase(java.util.Properties config, boolean managed, boolean setActive) { DatabaseConnection platformConnection = initDatabase(config); MigrationInfoService statusComplete = platformConnection.getMigrationInfoService(); if (setAct... | @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); StringBu... |
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(Strin... | @Test public void testString() { assertTrue("string(foo)"); assertTrue("string(bar)"); assertFalse("string(foobar)"); assertTrue("string('foobar')"); } |
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.P... | @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); } |
LdapService { public boolean loginUser(Site site, String username, char[] password) { LdapCredentials ldapCredentials = new LdapCredentials(site, username, password, false); TlsAwareLdapContext ctx = null; try { ctx = new TlsAwareLdapContext(ldapCredentials); return true; } catch (IOException | NamingException ex) { lo... | @Test public void testLoginUserSucces() throws NamingException, IOException { boolean success; sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "DN"); sitePropertyMocks.put(LdapService.LDAP_USER_BASE_DN, "l=egypt"); sitePropertyMocks.put(LdapService.LDAP_ID_ATTRIBUTE, "uid"); setup("uid=aziz,l=egypt", "ligh... |
LdapService { public List<String> loginGroup(Site site, String username, char[] password, SubjectImpl subject, List<String> groupNames) { LdapCredentials ldapCredentials = new LdapCredentials(site, username, password, false); TlsAwareLdapContext ctx = null; try { ctx = new TlsAwareLdapContext(ldapCredentials); return g... | @Test public void testLoginGroupExistent() throws NamingException, IOException { List<String> searchedGroups; List<String> resultGroups; sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "UPN"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); sitePropertyMocks.put(LdapService.LDAP_USER, "mondosh... |
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 = ... | @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"); sitePro... |
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("Signin... | @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 repos... |
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... | @Test public void testCaptcha() { assertFalse("captcha(bar, SESSION.foobar)"); assertFalse("captcha(bar, SESSION['foobar'])"); assertTrue("captcha(5, SESSION.foobar)"); assertTrue("captcha(5, SESSION['foobar'])"); } |
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[] index... | @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),... |
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); Strin... | @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 ha... |
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 applyPasswor... | @Test public void testIsValidPasswordResetDigest() { testIsValidPasswordResetDigest(new BCryptPasswordHandler(subject)); } |
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); DigestVa... | @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 ... |
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 platf... | @Test public void testGenerate() { for (int i = 0; i < 1000; i++) { String password = passwordPolicy.generatePassword(); assertValid(password); } } |
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... | @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("... |
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(Auth... | @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()); } |
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 isValidP... | @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_SAL... |
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(Str... | @Test public void testEmail() { assertTrue("email('mm@aiticon.de')"); assertTrue("email('_mm@aiticon.de')"); assertFalse("email('mm@aiticon')"); assertFalse("email('@aiticon.de')"); } |
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 calculatePas... | @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); ... |
Sha1PasswordHandler implements PasswordHandler { public boolean isValidPasswordResetDigest(String digest) { return calculatePasswordResetDigest().equals(digest); } Sha1PasswordHandler(AuthSubject authSubject); void applyPassword(String password); boolean isValidPassword(String password); String calculatePasswordResetDi... | @Test public void testIsValidPasswordResetDigest() { testIsValidPasswordResetDigest(new Sha1PasswordHandler(subject)); } |
ConfigurablePasswordPolicy implements PasswordPolicy { @Override public ValidationResult validatePassword(String username, char[] currentPassword, char[] password) { PasswordData passwordData = null; if (null == username) { passwordData = new PasswordData(new String(password)); } else { List<Reference> references = new... | @Test public void testPasswords() { String username = "johndoe"; String currentPassword = "test"; assertFirstError(AllowedCharacterRule.ERROR_CODE, username, currentPassword, "TEst12!!ß"); assertFirstError(WhitespaceRule.ERROR_CODE, username, currentPassword, "TEst12!! "); assertFirstError(UsernameRule.ERROR_CODE, user... |
SessionListener implements ServletContextListener, HttpSessionListener, ServletRequestListener { public void sessionCreated(HttpSessionEvent event) { createSession(event.getSession()); } void contextInitialized(ServletContextEvent sce); void contextDestroyed(ServletContextEvent sce); void sessionCreated(HttpSessionEve... | @Test public void testSessionCreated() { sessionListener.sessionCreated(new HttpSessionEvent(session1)); addRequest(session1); addRequest(session1); Assert.assertEquals(2, ((Session) session1.getAttribute(SessionListener.META_DATA)).getRequests()); } |
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.ge... | @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... |
Controller extends DefaultServlet implements ContainerServlet { @Override protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (!Boolean.TRUE.equals(servletRequest.getServletContext().getAttribute(PlatformStartup.APPNG_STARTED))) { servle... | @Test public void testAttachmentWebService() { when(base.request.getServletPath()).thenReturn("/services/manager/application1/webservice/foobar"); try { AttachmentWebservice attachmentWebservice = getAttachmentWebservice("attachment webservice call", "test.txt"); base.provider.registerBean("foobar", attachmentWebservic... |
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 all... | @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("/te... |
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); s... | @Test public void testEquals() { assertTrue("equals('a','a')"); assertTrue("equals('b','b')"); assertFalse("equals('a','A')"); assertFalse("equals('a',' A')"); } |
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 n... | @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()).... |
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 capt... | @Test public void testRegExp() { assertTrue("regExp('abc','[a-z]+')"); assertFalse("regExp('abc','[a-z]{4,}')"); } |
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 UnsupportedOperationExc... | @Test public void testSize() { assertTrue("size(foo,3)"); assertFalse("size(foo,4)"); assertTrue("size(multifoo,4)"); assertFalse("size(multifoo,5)"); assertFalse("size(multibar,5)"); } |
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 ... | @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()); } |
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())) { retur... | @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.asser... |
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()) { AntPath... | @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 expireA... |
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... | @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' '/e... |
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, se... | @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.getConten... |
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... | @Test public void testSizeMin() { assertTrue("sizeMin(foo,3)"); assertFalse("sizeMin(foo,4)"); assertTrue("sizeMin(multifoo,4)"); assertFalse("sizeMin(multifoo,5)"); assertFalse("sizeMin(multibar,5)"); } |
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)... | @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(); } |
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.PL... | @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.getS... |
ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()... | @Test public void testSoap() throws Exception { String servletPath = "/services/site1/appng-demoapplication/soap/personService/personService.wsdl"; setup(servletPath); List<String> emptyList = new ArrayList<>(); PathInfo pathInfo = new PathInfo("localhost", "localhost", "localhost", servletPath, "/ws", "/services", emp... |
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)... | @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(... |
ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheMana... | @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> dict... |
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 = Validat... | @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)))... |
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(reg... | @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))... |
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... | @Test public void testSizeMax() { assertTrue("sizeMax(foo,4)"); assertFalse("sizeMax(foo,2)"); assertTrue("sizeMax(multifoo,4)"); assertFalse("sizeMax(multifoo,3)"); assertTrue("sizeMax(multibar,3)"); } |
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, Strin... | @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.... |
SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDAT... | @Test public void testSiteInternalRedirect() { site.sendRedirect(environment, "page/foo/bar#anchor", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/ws/foo/page/foo/bar#anchor", response.getHeader(HttpHeaders.LOCATION)); Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()... |
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); @Not... | @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... |
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 Actio... | @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);... |
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<Actio... | @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); ... |
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)); }); } header... | @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... |
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.subs... | @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> cookie... |
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, Stri... | @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> para... |
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 str... | @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)"); } |
CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.pu... | @Test public void testComment() { Assert.assertArrayEquals(new String[0], batch.parseLine("#My first comment")); Assert.assertArrayEquals(new String[0], batch.parseLine("# AnotherOne")); }
@Test public void testSysEnvVariables() { OperatingSystem os = OperatingSystem.detect(); String lang = System.getenv("LANG"); LOGGE... |
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) { runInteract... | @Test(expected = BusinessException.class) public void testInvalid() throws BusinessException { new HashPassword("").execute(cliEnv); } |
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; } | @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 { CliBo... |
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(Strin... | @Test public void testNumber() { assertFalse("number(foo)"); assertTrue("number(bar)"); } |
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) { Strin... | @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()... |
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); } | @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); } |
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 personI... | @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.val... |
Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpda... | @Test public void testUpdateAppNG() throws Exception { target = UpNGizr.appNGHome; Resource resource = getResource("appng-application"); new Updater(new MockServletContext()).updateAppNG(resource, target); assertFolderNotEmpty("WEB-INF"); assertFolderNotEmpty("WEB-INF/classes"); Assert.assertFalse(new File(target, "WEB... |
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())... | @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 ... |
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(... | @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 testCheckVe... |
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 ... | @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("numberFractionDi... |
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 IOE... | @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(... |
Parameter extends BodyTagSupport { public Parameter() { } Parameter(); @Override int doEndTag(); String getName(); void setName(String name); boolean isUnescape(); void setUnescape(boolean unescape); @Override String toString(); } | @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(tru... |
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; } r... | @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... |
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,... | @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 ... |
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); SiteIm... | @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... |
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, BusinessExce... | @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... |
ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quo... | @Test public void testReplaceInFile() throws Exception { ClassLoader classLoader = ApplicationStartupTest.class.getClassLoader(); File original = new File(classLoader.getResource("xml/sourceConfig.xml").toURI()); File copy = new File("src/test/resources/xml/copyConfig.xml"); File replacementSource = new File(classLoade... |
SitePropertyController extends PropertyBase { @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getProper... | @Test public void test() throws Exception { differenceListener.ignoreDifference("/properties/property/description/text()"); Site created = new Site(); created.setName("localhost"); created.setHost("localhost"); created.setDomain("http: created.setDescription("none"); created.setActive(false); created.setCreateRepositor... |
DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDataba... | @Test public void testInitialize() throws Exception { ignorePasswordAndInstalledDate(); postAndVerify("/platform/database/initialize", "xml/database-init.xml", null, HttpStatus.OK); } |
AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects()... | @Test public void testEncode() { Assert.assertEquals("name%20with%20spaces", AppNGizer.encode("name with spaces")); } |
AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(Medi... | @Ignore("Run locally") @Test(expected = HttpClientErrorException.class) public void testUploadPackage() throws Exception { getAppNGizer().uploadPackage("local", new File("pom.xml")); } |
StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); void init(); void setMasterSource(InputStream masterXsl, String templateRoot); void addStyleSheet(InputStream styleSheet, String reference); byte[] getStyleSheet(boolean deleteIncludes); byte[] getStyleSheet(boolean deleteIncludes, OutputStream ... | @Test public void testStyleSheetProvider() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); ssProvider.setName("container"); ssProvider.setInsertBefore("include-4.xsl"); addStyleSheet("include-1.xsl"); addStyleSheet("include-2.xsl"); addStyleSheet("include-3.xsl"); File expected = new File(clas... |
ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String pre... | @Test public void test() throws Exception { String outFile = "src/test/resources/xml/application.xml"; ApplicationPropertyConstantCreator .main(new String[] { outFile, "org.appng.xml.ApplicationProperty", "target/tmp", "PROP_" }); String actual = FileUtils.readFileToString(new File("target/tmp/org/appng/xml/Application... |
ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ... | @Test public void testFile() throws Exception { Map<String, StringBuilder> parsed = parseTags.parse(new File("pages/en/42.jsp")); Assert.assertEquals("The Hitchhiker's Guide to the Galaxy", parsed.get("title").toString()); String contents = parsed.get("contents").toString(); String expected = "The Hitchhiker's Guide to... |
XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); ... | @Test public void testGetString() throws IOException { Assert.assertEquals("abcd", processor.getString("/root/a/string")); Assert.assertEquals("abcd", processor.getString(processor.getNode("/root/a"), "string")); } |
XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespac... | @Test public void testGetBoolean() throws IOException { Assert.assertEquals(Boolean.TRUE, processor.getBoolean("/root/a/boolean")); Assert.assertEquals(Boolean.TRUE, processor.getBoolean(processor.getNode("/root/a"), "boolean")); } |
XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); ... | @Test public void testGetNumber() throws IOException { Assert.assertEquals(3.45d, processor.getNumber("/root/a/double")); Assert.assertEquals(3.45d, processor.getNumber(processor.getNode("/root/a"), "double")); } |
XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); voi... | @Test public void testGetXml() { Node node = processor.getNode("/root/b"); String xml = processor.getXml(node); ByteArrayOutputStream out = new ByteArrayOutputStream(); processor.getXml(node, out); Assert.assertEquals(xml, out.toString()); } |
XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); voi... | @Test public void testNewText() { Text text = processor.newText("data"); Assert.assertEquals("data", text.getData()); } |
ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(w... | @Test public void testFitToHeight() throws IOException { File targetFile = new File(targetFolder, "desert-height-100.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToHeight(100); ImageMetaData metaData = new ImageProcessor(ip.getImage(), null, true).getMetaData(); assertDimensions(133, 100, metaData); } |
XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String... | @Test public void testNewCDATA() { Text text = processor.newCDATA("data"); Assert.assertEquals("data", text.getData()); } |
XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(N... | @Test public void testNewElement() { Element el = processor.newElement("data"); Assert.assertEquals("data", el.getTagName()); } |
XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String p... | @Test public void testNewAttribute() { Attr attr = processor.newAttribute("name", "value"); Assert.assertEquals("name", attr.getName()); Assert.assertEquals("value", attr.getValue()); } |
RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpv... | @Test public void doTest() { MockitoAnnotations.initMocks(this); Map<String, List<String>> paramters = new HashMap<>(); paramters.put(NAME, Arrays.asList("Doe")); paramters.put(INTEGER_LIST, Arrays.asList("1", "2", "3")); paramters.put(BIRTH_DATE, Arrays.asList("14.05.1944")); Mockito.when(request.getParameterNames()).... |
DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> it... | @Test public void testSetItem() { dataContainer.setItem(persons.get(0)); Assert.assertEquals(fieldProcessor, dataContainer.getFieldProcessor()); Assert.assertEquals(persons.get(0), dataContainer.getItem()); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertTrue(dat... |
DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collectio... | @Test public void testSetPage() { dataContainer.setPage(page); Assert.assertNull(dataContainer.getPageable()); Assert.assertEquals(page, dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate(... |
DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> ... | @Test public void testSetItems() { dataContainer.setItems(persons); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertEquals(persons, dataContainer.getItems()); Assert.assertFalse(dataContainer.getWrappedData().is... |
AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String g... | @Test public void testMd5Digest() { String md5Digest = AuthTools.getMd5Digest(testPattern); Assert.assertEquals("7C2AD50DBEA658E2F87DDE1609114237", md5Digest); } |
AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static Strin... | @Test public void testSha1Digest() { String sha1Digest = AuthTools.getSha1Digest(testPattern); Assert.assertEquals("746BDF044C80DD81336A522BF27D8C661947D3EF", sha1Digest); } |
AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static S... | @Test public void testSha512Digest() { String sha512Digest = AuthTools.getSha512Digest(testPattern); Assert.assertEquals( "AB9D85DC074D06B675DAEE7FA4A70C7D0BD8F9A284713DAA0E5689DAA9367DD10258E331D3494053B4F5A1084D7881455DB5AADB84BDFAF5638677ED1D1C4881", sha512Digest); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.