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 subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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("foobaz.a")); assertEquals(b, coreService.getProperty("foobaz.b")); } |
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, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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 devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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(env, currentApplication); if (currentApplication.isFileBased() && !isFileBased) { convertDirection = "filebased to database"; LOGGER.info("application '{}' is beeing converted from {}", currentApplication.getName(), convertDirection); Resources resources = getResources(currentApplication, null, getApplicationRootFolder(env)); writeApplicationResources(currentApplication, false, null, resources.getResources()); deleteApplicationResources(application, applicationFolder); } else if (!currentApplication.isFileBased() && isFileBased) { convertDirection = "database to filebased"; LOGGER.info("application '{}' is beeing converted from {}", currentApplication.getName(), convertDirection); Resources resources = getResources(currentApplication, applicationFolder, null); writeApplicationResources(currentApplication, true, applicationFolder, resources.getResources()); deleteApplicationResources(currentApplication, applicationFolder); } } catch (InvalidConfigurationException e) { throw new BusinessException("error while transforming application '" + application.getName() + "' from " + convertDirection + ", application is in an erroneous state", e); } } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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.getApplication()); DatabaseConnection databaseConnection = siteApplication.getDatabaseConnection(); MigrationStatus status = MigrationStatus.NO_DB_SUPPORTED; if (null != databaseConnection) { databaseConnectionRepository.delete(databaseConnection); status = databaseService.dropDataBaseAndUser(databaseConnection); } String applicationName = siteApplication.getApplication().getName(); LOGGER.info("unlinking application {} from site {}, status of database-connection is {}", applicationName, site.getName(), status); auditableListener.createEvent(Type.INFO, String.format("Removed application %s from site %s", applicationName, site.getName())); if (MigrationStatus.DB_MIGRATED.equals(status)) { auditableListener.createEvent(Type.INFO, String.format("Dropped database %s and user %s", databaseConnection.getJdbcUrl(), databaseConnection.getUserName())); } else if (MigrationStatus.ERROR.equals(status)) { auditableListener.createEvent(Type.ERROR, String.format("Error while dropping database %s and user %s", databaseConnection.getJdbcUrl(), databaseConnection.getUserName())); } return status; } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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.isValid()) { PasswordHandler passwordHandler = getDefaultPasswordHandler(currentSubject); passwordHandler.applyPassword(new String(password)); } return validationResult; } Subject createSubject(SubjectImpl subject); PropertyHolder getPlatformProperties(); PlatformProperties initPlatformConfig(java.util.Properties defaultOverrides, String rootPath,
Boolean devMode, boolean persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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 ValidationResult(true, null); } }; ValidationResult updatePassword = coreService.updatePassword(dummyPolicy, "test".toCharArray(), "foobar".toCharArray(), subject); assertTrue(updatePassword.isValid()); } |
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 persist, boolean tempOverrides); Page<PropertyImpl> getProperties(String siteName, String applicationName); Page<PropertyImpl> getProperties(String siteName, String applicationName, Pageable pageable); PropertyImpl createProperty(Integer siteId, Integer applicationId, PropertyImpl property); SiteImpl getSite(Integer id); SiteImpl getSiteByName(String name); void saveSite(SiteImpl site); PropertyImpl saveProperty(PropertyImpl property); List<SubjectImpl> getSubjectsByType(UserType type); boolean isValidPassword(AuthSubject authSubject, String password); @Deprecated PasswordHandler getPasswordHandler(AuthSubject authSubject); PasswordHandler getDefaultPasswordHandler(AuthSubject authSubject); Subject restoreSubject(String name); boolean login(Environment env, Principal principal); boolean login(Environment env, String digest, int digestMaxValidity); boolean login(Site site, Environment env, String username, String password); boolean loginGroup(Environment env, AuthSubject authSubject, String password, Integer groupId); void logoutSubject(Environment env); PropertyImpl getProperty(String propertyId); void createSite(SiteImpl site); MigrationStatus assignApplicationToSite(SiteImpl site, Application application,
boolean createProperties); PermissionImpl getPermission(String application, String name); PermissionImpl savePermission(PermissionImpl p); RepositoryImpl createRepository(RepositoryImpl repository); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased,
FieldProcessor fp, boolean updateHiddenAndPrivileged); PackageInfo installPackage(final Integer repositoryId, final String name, final String version,
String timestamp, final boolean isPrivileged, final boolean isHidden, final boolean isFileBased); Template provideTemplate(Integer repositoryId, String templateName, String templateVersion,
String templateTimestamp); Integer deleteTemplate(String name); File getApplicationFolder(Environment env, String applicationName); byte[] resetPassword(AuthSubject authSubject, PasswordPolicy passwordPolicy, String email, String hash); String forgotPassword(AuthSubject authSubject); SubjectImpl updateSubject(SubjectImpl subject); AccessibleApplication findApplicationByName(String name); void updateApplication(ApplicationImpl application, boolean isFileBased); List<? extends Group> getGroups(); void deleteSite(String name, FieldProcessor fp); void setSiteActive(String name, boolean active); void deleteSite(Environment env, SiteImpl site); void cleanupSite(Environment env, SiteImpl site, boolean sendDeletedEvent); void deleteProperty(PropertyImpl prop); @Transactional(propagation = Propagation.REQUIRES_NEW) MigrationStatus unlinkApplicationFromSite(Integer siteId, Integer applicationId); void saveRole(RoleImpl role); void deleteRole(Role role); void deleteApplication(String applicationName, FieldProcessor fp); void deletePermission(Permission permission); void addApplicationRolesToGroup(String groupName, String applicationName, List<String> applicationRoleNames,
boolean clear); void addGroupsToSubject(String userName, List<String> groupNames, boolean clear); List<DatabaseConnection> getDatabaseConnectionsForSite(Integer siteId); Page<DatabaseConnection> getDatabaseConnections(Integer siteId, FieldProcessor fp); DatabaseConnection getDatabaseConnection(Integer dcId, boolean clearPassword); PasswordPolicy.ValidationResult updatePassword(PasswordPolicy policy, char[] currentPassword,
char[] password, SubjectImpl currentSubject); @Deprecated Boolean updatePassword(char[] password, char[] passwordConfirmation, SubjectImpl currentSubject); void resetConnection(FieldProcessor fp, Integer conId); GroupImpl createGroup(GroupImpl group); void deleteGroup(GroupImpl group); void deleteApplicationRepository(org.appng.core.model.Repository repository); void deleteSubject(Subject subject); SiteImpl shutdownSite(Environment env, String siteName); SiteImpl shutdownSite(Environment env, String siteName, boolean removeFromSiteMap); void unsetReloadRequired(SiteApplication siteApplication); void setSiteStartUpTime(SiteImpl site, Date date); Collection<ApplicationSubject> getApplicationSubjects(Integer applicationId, Site site); SubjectImpl getSubjectByName(String name, boolean initialize); Subject getSubjectById(Integer id, boolean initialize); org.appng.core.model.Repository getApplicationRepositoryByName(String repositoryName); void saveRepository(RepositoryImpl repo); List<ApplicationImpl> getApplications(); List<RoleImpl> getApplicationRolesForApplication(Integer applicationId); List<RoleImpl> getApplicationRoles(); List<RepositoryImpl> getApplicationRepositories(); List<SiteImpl> getSites(); List<SubjectImpl> getSubjects(); GroupImpl getGroupByName(String name); GroupImpl getGroupByName(String name, boolean init); void updateGroup(GroupImpl group); Subject getSubjectByEmail(String email); int addPermissions(String applicationName, String roleName, List<String> permissionNames); int removePermissions(String applicationName, String roleName, List<String> permissionNames); Role getApplicationRoleForApplication(Integer applicationId, String roleName); RoleImpl getApplicationRoleForApplication(String applicationName, String roleName); RoleImpl initRole(RoleImpl role); List<? extends Permission> getPermissionsForApplication(Integer applicationId); Site getGrantingSite(String grantedSite, String grantedApplication); Map<String, String> getCacheStatistics(Integer siteId); List<CachedResponse> getCacheEntries(Integer siteId); void expireCacheElement(Integer siteId, String cacheElement); int expireCacheElementsStartingWith(Integer siteId, String cacheElementPrefix); void clearCacheStatistics(Integer siteId); void clearCache(Integer siteId); Application getApplicationForConnection(DatabaseConnection dbc); DatabaseConnection getDatabaseConnection(SiteImpl site, ApplicationImpl application); SiteApplication getSiteApplication(String site, String application); SiteApplication getSiteApplicationWithGrantedSites(String site, String application); SiteApplication grantApplicationForSites(String site, String application, List<String> siteNames); void createEvent(Type type, String message, HttpSession session); void createEvent(Type type, String message, Object... args); void setSiteReloadCount(SiteImpl site); } | @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 (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); } | @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; } } } |
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; } | @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.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); } | @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) { logException(ldapCredentials.ldapHost, ldapCredentials.principal, ex); } finally { closeContext(ctx); } return false; } 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; } | @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", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertTrue(success); sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "UPN"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); setup("aziz@egypt", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertTrue(success); sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "SAM"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); setup("egypt\\aziz", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertTrue(success); sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "bogus"); setup("aziz", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertTrue(success); }
@Test public void testLoginUserFailure() throws NamingException, IOException { boolean success; List<Exception> exList; Exception ex; LdapContextMock ldapContextMock; sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "SAM"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); ldapContextMock = setup("bielefeld\\aziz", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); exList = ldapContextMock.exceptionHistory; ex = exList.size() > 0 ? exList.get(exList.size() - 1) : new Exception("Placeholder - nothing was thrown."); Assert.assertFalse(success); Assert.assertEquals(LdapContextMock.MSG_WRONG_USER, ex.getMessage()); sitePropertyMocks.replace(LdapService.LDAP_PRINCIPAL_SCHEME, "SAM"); sitePropertyMocks.replace(LdapService.LDAP_DOMAIN, "egypt"); ldapContextMock = setup("egypt\\aziz", "shadow", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertFalse(success); exList = ldapContextMock.exceptionHistory; ex = exList.size() > 0 ? exList.get(exList.size() - 1) : new Exception("Placeholder - nothing was thrown."); Assert.assertFalse(success); Assert.assertEquals(LdapContextMock.MSG_WRONG_PASS, ex.getMessage()); }
@Test public void testLoginUserStartTls() 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"); sitePropertyMocks.put(LdapService.LDAP_START_TLS, true); setup("uid=aziz,l=egypt", "light", null, null); success = ldapService.loginUser(mockedSite, "aziz", "light".toCharArray()); Assert.assertTrue(success); } |
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 getUserGroups(ctx.delegate, username, site, subject, groupNames); } catch (NamingException | IOException ex) { logException(ldapCredentials.ldapHost, ldapCredentials.principal, ex); } finally { closeContext(ctx); } return new ArrayList<>(); } 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; } | @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, "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"); searchedGroups = Arrays.asList(LdapContextMock.MOCKED_GROUP_NAME); resultGroups = ldapService.loginGroup(mockedSite, "aZiZ", "light".toCharArray(), mockedSubject, searchedGroups); Assert.assertArrayEquals(searchedGroups.toArray(new String[0]), resultGroups.toArray(new String[0])); }
@Test public void testLoginGroupExistentNoGroupBaseDn() 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, "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, ""); setup("aziz@egypt", "light", "mondoshawan@egypt", "stones"); searchedGroups = Arrays.asList("cn=logingroup,ou=groups,l=egypt"); resultGroups = ldapService.loginGroup(mockedSite, "aZiZ", "light".toCharArray(), mockedSubject, searchedGroups); Assert.assertArrayEquals(searchedGroups.toArray(new String[0]), resultGroups.toArray(new String[0])); }
@Test public void testLoginGroupExistentServiceUserDirectDN() 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, "cn=mondoshawan,l=homeplanet"); 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", "cn=mondoshawan,l=homeplanet", "stones"); searchedGroups = Arrays.asList(LdapContextMock.MOCKED_GROUP_NAME); resultGroups = ldapService.loginGroup(mockedSite, "aziz", "light".toCharArray(), mockedSubject, searchedGroups); Assert.assertArrayEquals(searchedGroups.toArray(new String[0]), resultGroups.toArray(new String[0])); }
@Test public void testLoginGroupMissing() 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, "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"); searchedGroups = Arrays.asList( "Well, if there's a bright center to the universe, you're on the usergroup that it's farthest from."); resultGroups = ldapService.loginGroup(mockedSite, "aziz", "light".toCharArray(), mockedSubject, searchedGroups); Assert.assertArrayEquals(new String[0], resultGroups.toArray(new String[0])); } |
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; } | @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()); } } |
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); } | @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()); } |
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; } | @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[] 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); } | @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)); } |
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(); } | @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)); } |
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(); } | @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); DigestValidator(String digest, int maxOffsetMinutes); boolean validate(String sharedSecret); String getUsername(); String getTimestamp(); String getUtcOffset(); } | @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); } |
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; } | @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); 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; } | @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())); } |
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); } | @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 isValidPassword(String password); String calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); } | @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)); } |
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; } | @Test public void testEmail() { assertTrue("email('[email protected]')"); assertTrue("email('[email protected]')"); 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 calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); } | @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 calculatePasswordResetDigest(); boolean isValidPasswordResetDigest(String digest); void migrate(CoreService service, String password); } | @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 ArrayList<>(); if (null != currentPassword) { references.add(new HistoricalReference(new String(currentPassword))); } passwordData = new PasswordData(username, new String(password), references); } RuleResult validate = passwordValidator.validate(passwordData); List<MessageParam> messages = validate.getDetails().stream().map(d -> new MessageParam() { public String getMessageKey() { return ConfigurablePasswordPolicy.class.getSimpleName() + "." + d.getErrorCode(); } public Object[] getMessageArgs() { return d.getValues(); } }).collect(Collectors.toList()); return new ValidationResult(validate.isValid(), messages.toArray(new MessageParam[0])); } @Override void configure(Properties platformProperties); boolean isValidPassword(char[] password); @Override ValidationResult validatePassword(String username, char[] currentPassword, char[] password); String getErrorMessageKey(); String generatePassword(); PasswordValidator getValidator(); } | @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, username, currentPassword, username + "12!O"); assertFirstError(HistoryRule.ERROR_CODE, username, "Test123!!", "Test123!!"); String noUpperCase = EnglishCharacterData.UpperCase.getErrorCode(); String noLowerCase = EnglishCharacterData.LowerCase.getErrorCode(); String noDigit = EnglishCharacterData.Digit.getErrorCode(); String noSpecial = EnglishCharacterData.Special.getErrorCode(); assertFirstError(noUpperCase, username, currentPassword, "testtest"); assertFirstError(noLowerCase, username, currentPassword, "TESTTEST"); assertFirstError(noLowerCase, username, currentPassword, "12345678"); assertFirstError(noLowerCase, username, currentPassword, "!!!!!!!!"); assertFirstError(noDigit, username, currentPassword, "testTEST"); assertFirstError(noUpperCase, username, currentPassword, "test1234"); assertFirstError(noUpperCase, username, currentPassword, "test!!!!"); assertFirstError(noLowerCase, username, currentPassword, "TEST1234"); assertFirstError(noLowerCase, username, currentPassword, "TEST!!!!"); assertFirstError(noLowerCase, username, currentPassword, "1234!!!!"); assertFirstError(noSpecial, username, currentPassword, "testTEST12"); assertFirstError(noSpecial, username, currentPassword, "testTEST12"); assertFirstError(noDigit, username, currentPassword, "testTEST!!"); assertFirstError(noUpperCase, username, currentPassword, "test1234!!"); assertFirstError(noLowerCase, username, currentPassword, "TEST1234!!"); String toShort = LengthRule.ERROR_CODE_MIN; assertFirstError(toShort, username, currentPassword, "Test!12"); assertFirstError(toShort, username, currentPassword, "Test12!"); assertFirstError(toShort, username, currentPassword, "12Test!"); assertFirstError(toShort, username, currentPassword, "12!Test"); assertFirstError(toShort, username, currentPassword, "!Test12"); assertFirstError(toShort, username, currentPassword, "!12Test"); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "teST12!!".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "teST!!12".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "TEst!!12".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "TEst12!!".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "12!!teST".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "12!!TEst".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "!!12teST".toCharArray()).isValid()); Assert.assertTrue( policy.validatePassword(username, currentPassword.toCharArray(), "!!12TEst".toCharArray()).isValid()); } |
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; } | @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.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; } | @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)); } |
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))) { servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); servletResponse.setContentType(MediaType.TEXT_HTML_VALUE); servletResponse.setContentLength(loadingScreen.length); servletResponse.getOutputStream().write(loadingScreen); return; } String servletPath = servletRequest.getServletPath(); String serverName = servletRequest.getServerName(); Environment env = getEnvironment(servletRequest, servletResponse); String hostIdentifier = RequestUtil.getHostIdentifier(servletRequest, env); Site site = RequestUtil.getSiteByHost(env, hostIdentifier); Properties platformProperties = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); Boolean allowPlainRequests = platformProperties.getBoolean(ALLOW_PLAIN_REQUESTS, true); if (site != null) { try { int requests = ((SiteImpl) site).addRequest(); LOGGER.debug("site {} currently handles {} requests", site, requests); PathInfo pathInfo = RequestUtil.getPathInfo(env, site, servletPath); if (pathInfo.isMonitoring()) { monitoringHandler.handle(servletRequest, servletResponse, env, site, pathInfo); } else { site = RequestUtil.waitForSite(env, site.getName()); if (site.hasState(SiteState.STARTED)) { boolean enforcePrimaryDomain = site.getProperties() .getBoolean(SiteProperties.ENFORCE_PRIMARY_DOMAIN, false); if (enforcePrimaryDomain) { String primaryDomain = site.getDomain(); if (!(primaryDomain.startsWith(SCHEME_HTTP + serverName)) || (primaryDomain.startsWith(SCHEME_HTTPS + serverName))) { Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, primaryDomain); } } setRequestAttributes(servletRequest, env, pathInfo); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); RequestHandler requestHandler = null; String appngData = platformProperties.getString(org.appng.api.Platform.Property.APPNG_DATA); File debugFolder = new File(appngData, "debug").getAbsoluteFile(); if (!(debugFolder.exists() || debugFolder.mkdirs())) { LOGGER.warn("Failed to create {}", debugFolder.getPath()); } if (("/".equals(servletPath)) || ("".equals(servletPath)) || (null == servletPath)) { if (!pathInfo.getDocumentDirectories().isEmpty()) { String defaultPage = site.getProperties().getString(SiteProperties.DEFAULT_PAGE); String target = pathInfo.getDocumentDirectories().get(0) + SLASH + defaultPage; Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, target); } else { LOGGER.warn("{} is empty for site {}, can not process request!", SiteProperties.DOCUMENT_DIR, site.getName()); } } else if (pathInfo.isStaticContent() || pathInfo.getServletPath().startsWith(templatePrefix) || pathInfo.isDocument()) { requestHandler = new StaticContentHandler(this); } else if (pathInfo.isGui()) { requestHandler = new GuiHandler(debugFolder); } else if (pathInfo.isService()) { ApplicationContext ctx = env.getAttribute(Scope.PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT); MarshallService marshallService = ctx.getBean(MarshallService.class); PlatformTransformer platformTransformer = ctx.getBean(PlatformTransformer.class); requestHandler = new ServiceRequestHandler(marshallService, platformTransformer, debugFolder); } else if (pathInfo.isJsp()) { requestHandler = jspHandler; } else if (pathInfo.isMonitoring()) { requestHandler = monitoringHandler; } else if (ERRORPAGE.equals(servletPath)) { requestHandler = new ErrorPageHandler(); } else { if (allowPlainRequests && !pathInfo.isRepository()) { super.doGet(servletRequest, servletResponse); int status = servletResponse.getStatus(); LOGGER.debug("returned {} for request {}", status, servletPath); } else { servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); LOGGER.debug("was not an internal request, rejecting {}", servletPath); } } if (null != requestHandler) { if (site.hasState(SiteState.STARTED)) { requestHandler.handle(servletRequest, servletResponse, env, site, pathInfo); if (pathInfo.isGui() && servletRequest.isRequestedSessionIdValid()) { getEnvironment(servletRequest, servletResponse).setAttribute(SESSION, EnvironmentKeys.PREVIOUS_PATH, servletPath); } } else { LOGGER.error("site {} should be STARTED.", site); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); } } } else { LOGGER.error("timeout while waiting for site {}", site); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); } } } finally { if (null != site) { int requests = ((SiteImpl) site).removeRequest(); LOGGER.debug("site {} currently handles {} requests", site, requests); } } } else if (allowPlainRequests) { LOGGER.debug("no site found for request '{}'", servletPath); super.doGet(servletRequest, servletResponse); int status = servletResponse.getStatus(); LOGGER.debug("returned {} for request '{}'", status, servletPath); } else { LOGGER.debug("access to '{}' not allowed", servletPath); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); } } Controller(); void serveResource(HttpServletRequest request, HttpServletResponse response); @Override void init(); Wrapper getWrapper(); void setWrapper(Wrapper wrapper); JspHandler getJspHandler(); } | @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", attachmentWebservice); doGet(base.request, base.response); Mockito.verify(base.response).setContentType(HttpHeaders.CONTENT_TYPE_TEXT_PLAIN); Mockito.verify(base.response).setHeader(Mockito.eq(HttpHeaders.CONTENT_DISPOSITION), Mockito.eq("attachment; filename=\"test.txt\"")); Assert.assertEquals("attachment webservice call", new String(base.out.toByteArray())); } catch (Exception e) { fail(e); } }
@Test public void testAttachmentWebServiceNoFile() { when(base.request.getServletPath()).thenReturn("/services/manager/application1/webservice/foobar"); try { AttachmentWebservice attachmentWebservice = getAttachmentWebservice("attachment webservice call", "test.txt"); base.provider.registerBean("foobar", attachmentWebservice); doGet(base.request, base.response); Mockito.verify(base.response).setContentType(HttpHeaders.CONTENT_TYPE_TEXT_PLAIN); Assert.assertEquals("attachment webservice call", new String(base.out.toByteArray())); } catch (Exception e) { fail(e); } }
@Test public void testWebservice() { prepareWebserice(HttpMethod.GET); try { doGet(base.request, base.response); Assert.assertEquals("GET webservice call", new String(base.out.toByteArray())); } catch (Exception e) { fail(e); } }
@Test public void testMonitoring() { prepareMonitoring("/health"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Mockito.verify(base.response).setContentType(HttpHeaders.CONTENT_TYPE_APPLICATION_JSON); Assert.assertTrue(actual.contains("\"name\" : \"manager\"")); Assert.assertTrue(actual.contains("\"state\" : \"STARTED\"")); } catch (Exception e) { fail(e); } }
@Test public void testMonitoringSystem() { prepareMonitoring("/health/system"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertTrue(actual.contains("java.runtime.name")); Assert.assertTrue(actual.contains("java.runtime.version")); } catch (Exception e) { fail(e); } }
@Test public void testMonitoringEnv() { prepareMonitoring("/health/environment"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); if (OperatingSystem.isLinux()) { Assert.assertTrue(actual.contains("LANG")); Assert.assertTrue(actual.contains("USER")); } else if (OperatingSystem.isWindows()) { Assert.assertTrue(actual.contains("USERNAME")); Assert.assertTrue(actual.contains("Path")); } } catch (Exception e) { fail(e); } }
@Test public void testStaticFromRepository() { when(base.request.getServletPath()).thenReturn("/assets/test.txt"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals("/repository/manager/www/assets/test.txt", actual); } catch (Exception e) { fail(e); } }
@Test public void testStatic() { when(base.request.getServletPath()).thenReturn("/test.txt"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals("/test.txt", actual); } catch (Exception e) { fail(e); } }
@Test public void testTemplate() { when(base.request.getServletPath()).thenReturn("/template/assets/test.txt"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals("/repository/manager/www/template/assets/test.txt", actual); } catch (Exception e) { fail(e); } }
@Test public void testTemplateWithTemplateInPath() { when(base.request.getServletPath()).thenReturn("/template/resources/template/test.txt"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals("/repository/manager/www/template/resources/template/test.txt", actual); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testTemplateResourceFromApplication() { when(base.request.getServletPath()).thenReturn("/template_dummy-application/test.txt"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals("/WEB-INF/cache/platform/manager/dummy-application/resources/test.txt", actual); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testDoc() { String rootPath = base.platformProperties.getString("platform.platformRootPath"); String wwwRootPath = rootPath + File.separator + "repository" + File.separator + "manager" + File.separator + "www"; String realPath = new File(new File("").getAbsoluteFile(), wwwRootPath).getAbsolutePath(); when(base.request.getServletPath()).thenReturn("/de/test"); when(base.ctx.getRealPath("/repository/manager/www")).thenReturn(realPath); final String jspCalled = "JSP called"; try { jspHandler = Mockito.mock(JspHandler.class); Answer<Void> jspAnswer = new Answer<Void>() { public Void answer(InvocationOnMock invocation) throws Throwable { HttpServletResponse httpServletResponse = (HttpServletResponse) invocation.getArguments()[1]; httpServletResponse.getOutputStream().write(jspCalled.getBytes()); return null; } }; Mockito.doAnswer(jspAnswer).when(jspHandler).handle(isA(HttpServletRequest.class), isA(HttpServletResponse.class), isA(Environment.class), isA(Site.class), isA(PathInfo.class)); doGet(base.request, base.response); Assert.assertEquals(jspCalled, new String(base.out.toByteArray())); } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); Assert.fail(writer.toString()); } }
@Test public void testErrorPage() { when(base.request.getServletPath()).thenReturn("/errorpage"); try { doGet(base.request, base.response); verify(base.request).getRequestDispatcher("/de/fehler.jsp"); verify(base.request).setAttribute(RequestHandler.FORWARDED, Boolean.TRUE); verify(base.dispatcher).forward(base.request, base.response); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testErrorDoc() { when(base.request.getServletPath()).thenReturn("/errorpage"); try { when(base.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).thenReturn("/de/foobar"); doGet(base.request, base.response); verify(base.request).getRequestDispatcher("/de/fehler.jsp"); verify(base.request).setAttribute(RequestHandler.FORWARDED, Boolean.TRUE); verify(base.dispatcher).forward(base.request, base.response); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testRoot() { when(base.request.getServletPath()).thenReturn(""); try { doGet(base.request, base.response); verify(base.response).setStatus(301); verify(base.response).setHeader(HttpHeaders.LOCATION, "/de/index"); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testRootWithPath() { when(base.request.getServletPath()).thenReturn("/de"); try { doGet(base.request, base.response); verify(base.response).setStatus(301); verify(base.response).setHeader(HttpHeaders.LOCATION, "/de/index"); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testDocNoSite() { when(base.request.getServerName()).thenReturn("localhost"); when(base.request.getServletPath()).thenReturn("/de"); try { doGet(base.request, base.response); verify(base.response).getStatus(); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testJsp() throws ServletException { jspHandler = Mockito.mock(JspHandler.class); when(base.request.getServletPath()).thenReturn("/foo/bar.jsp"); try { when(base.request.getAttribute(RequestHandler.FORWARDED)).thenReturn(Boolean.TRUE); doGet(base.request, base.response); verify(jspHandler).handle(Mockito.eq(base.request), Mockito.eq(base.response), Mockito.eq(env), Mockito.eq(base.siteMap.get("manager")), Mockito.any(PathInfo.class)); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testStaticForSite() { when(base.request.getServletPath()).thenReturn("/de/test.pdf"); try { doGet(base.request, base.response); Assert.assertEquals("/repository/manager/www/de/test.pdf", new String(base.out.toByteArray())); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testStaticNoSite() { when(base.request.getServerName()).thenReturn("localhost"); when(base.request.getServletPath()).thenReturn("/repository/manager/www/de/test.txt"); try { doGet(base.request, base.response); Assert.assertEquals("/repository/manager/www/de/test.txt", new String(base.out.toByteArray())); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testLoadingPage() { Mockito.when(base.ctx.getAttribute(PlatformStartup.APPNG_STARTED)).thenReturn(false); when(base.request.getServletPath()).thenReturn("/dummy"); try { doGet(base.request, base.response); String actual = new String(base.out.toByteArray()); Assert.assertEquals(new String(loadingScreen), actual); } catch (Exception e) { fail(e); } finally { Mockito.when(base.ctx.getAttribute(PlatformStartup.APPNG_STARTED)).thenReturn(true); } } |
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(); } | @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); } } |
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; } | @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 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(); } | @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); } } |
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; } | @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 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; } | @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 response); @Override void init(); Wrapper getWrapper(); void setWrapper(Wrapper wrapper); JspHandler getJspHandler(); } | @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())) { return true; } } } return false; } void init(FilterConfig filterConfig); void destroy(); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); } | @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)); } |
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); } | @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); } |
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(); } | @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: } |
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); } | @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"); } |
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; } | @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); 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(); } | @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.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; } | @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"); } |
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()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } | @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", emptyList, emptyList, "", ""); Mockito.when(environment.getAttribute(Scope.REQUEST, EnvironmentKeys.PATH_INFO)).thenReturn(pathInfo); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals("[SOAP-Call] site1 appng-demoapplication", servletResponse.getContentAsString()); }
@Test public void testActionUnsupportedMediaType() throws Exception { String servletPath = "/services/localhost/appng-demoapplication/action/foobar/siteEvent/create"; PathInfo setupPath = setupPath(servletPath); handle(servletRequest, servletResponse, environment, site, setupPath); Assert.assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), servletResponse.getStatus()); }
@Test public void testWebservice() throws Exception { String servletPath = "/services/localhost/appng-demoapplication/webservice/personService"; PathInfo pathInfo = setupPath(servletPath); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals("Webservice-Call", servletResponse.getContentAsString()); Assert.assertEquals(HttpHeaders.CONTENT_TYPE_TEXT_PLAIN, servletResponse.getContentType()); Assert.assertEquals(HttpStatus.ACCEPTED.value(), servletResponse.getStatus()); }
@Test public void testSiteNotStarted() throws Exception { PathInfo pathInfo = setupPath("/services/localhost/foobar"); site.setState(SiteState.STARTING); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals(StringUtils.EMPTY, servletResponse.getContentAsString()); Assert.assertNull(servletResponse.getContentType()); Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE.value(), servletResponse.getStatus()); } |
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; } | @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); } |
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(); } | @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")); } |
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); } | @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))); } |
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); } | @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)); } |
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; } | @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, 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); } | @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()); } |
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.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(); } | @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()); }
@Test public void testSiteInternalRedirectMSIE() { Mockito.when(environment.getAttribute(REQUEST, HttpHeaders.USER_AGENT)).thenReturn("MSIE"); site.sendRedirect(environment, "page/foo/bar#anchor", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/ws/foo/page/foo/bar?tab=anchor#anchor", response.getHeader(HttpHeaders.LOCATION)); Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); }
@Test public void testExternalRedirect() { site.sendRedirect(environment, "/some/uri", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/some/uri", 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); @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(); } | @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); } } |
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); } | @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()); } |
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); } | @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()); } |
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); } | @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")); } |
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); } | @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")); } |
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); } | @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); } |
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; } | @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.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | @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"); LOGGER.info("OS is {} ({}) with LANG {}", os, System.getProperty("os.name"), lang); switch (os) { case LINUX: Assert.assertArrayEquals(new String[0], batch.parseLine("def LANG = ${systemEnv['LANG']}")); String langVar = variables.get("LANG"); Assert.assertEquals(String.format("Expected value %s for variable LANG, but was %s", lang, langVar), lang, langVar); break; case WINDOWS: Assert.assertArrayEquals(new String[0], batch.parseLine("def temp = ${systemEnv['TEMP']}")); Assert.assertTrue(StringUtils.isNotBlank(variables.get("temp"))); break; case MACOSX: Assert.assertArrayEquals(new String[0], batch.parseLine("def HOME = ${systemEnv['HOME']}")); Assert.assertTrue(StringUtils.containsIgnoreCase(variables.get("HOME"), "users")); break; case OTHER: Assert.fail("Unsupported operating system found: " + os); } }
@Test public void testCommandParsing() { Assert.assertArrayEquals(new String[0], batch.parseLine("# a comment")); Assert.assertArrayEquals(new String[0], batch.parseLine("def foo = bar")); Assert.assertArrayEquals(new String[0], batch.parseLine("")); Assert.assertArrayEquals(new String[] { "-i", "-f", "-g", "-h" }, batch.parseLine("-i -f -g -h")); Assert.assertArrayEquals(new String[] { "-k", "chunk", "with", "space", "\"in double-quotes\"" }, batch.parseLine("-k chunk with space \"in double-quotes\"")); Assert.assertArrayEquals(new String[] { "-initdatabase" }, batch.parseLine("-initdatabase")); Assert.assertArrayEquals( new String[] { "create-site", "-n", "manager", "-h", "localhost", "-d", "http: batch.parseLine("create-site -n manager -h localhost -d http: Assert.assertArrayEquals(new String[] { "-r", "\"L R\"", "-f" }, batch.parseLine("-r \"L R\" -f")); Assert.assertArrayEquals( new String[] { "import-application", "-n", "appng-authentication", "-v", "1.0-SNAPSHOT", "-r", "\"Local Repository\"", "-f" }, batch.parseLine( "import-application -n appng-authentication -v 1.0-SNAPSHOT -r \"Local Repository\" -f")); }
@Test public void testCommandVariables() { checkVariables("def DEPLOY = -f", "DEPLOY", "-f"); checkVariables("def MANAGER_APP =appng-manager ", "MANAGER_APP", "appng-manager"); checkVariables("def MANAGER_VERSION = 1.1-SNAPSHOT", "MANAGER_VERSION", "1.1-SNAPSHOT"); checkVariables("def REPOSITORY=\"Local Repository\"", "REPOSITORY", "\"Local Repository\""); checkVariables("def ADMIN_GROUP=Administrator", "ADMIN_GROUP", "Administrator"); checkVariables("def ADMIN_SUBJECT=admin", "ADMIN_GROUP", "Administrator"); checkVariables("def ROLE_NAME=Platform Administrator", "ROLE_NAME", "\"Platform Administrator\""); Assert.assertArrayEquals(new String[] { "test", "-f" }, batch.parseLine("test ${DEPLOY}")); Assert.assertArrayEquals( new String[] { "import-application", "-n", "appng-manager", "-v", "1.1-SNAPSHOT", "-r", "\"Local Repository\"", "-c", "-f" }, batch.parseLine( "import-application -n ${MANAGER_APP} -v ${MANAGER_VERSION} -r ${REPOSITORY} -c ${DEPLOY}")); Assert.assertArrayEquals( new String[] { "add-applicationrole", "-g", "Administrator", "-p", "appng-manager", "-r", "\"Platform Administrator\"" }, batch.parseLine("add-applicationrole -g ${ADMIN_GROUP} -p ${MANAGER_APP} -r ${ROLE_NAME}")); Assert.assertArrayEquals( new String[] { "create-subject", "-u", "admin", "-p", "tester", "-n", "\"appNG Administrator\"", "-l", "en", "-e", "[email protected]" }, batch.parseLine( "create-subject -u ${ADMIN_SUBJECT} -p tester -n \"appNG Administrator\" -l en -e [email protected]")); }
@Test public void testCommandUndeclaredVariables() { Assert.assertArrayEquals(new String[] { "foo", "$BAR" }, batch.parseLine("foo $BAR")); Assert.assertArrayEquals( new String[] { "prefix", "$UNDECLARED_VAR", "suffix", "plus", "\"quotes with space\"" }, batch.parseLine("prefix $UNDECLARED_VAR suffix plus 'quotes with space'")); }
@Test public void testQuotes() { Assert.assertArrayEquals(new String[] { "\"foo\"", "\"bar\"" }, batch.parseLine("\"foo\" \"bar\"")); Assert.assertArrayEquals(new String[] { "\"foo\"", "further", "parameters" }, batch.parseLine("\"foo\" further parameters")); Assert.assertArrayEquals(new String[] { "\"foo\"", "\"bar\"" }, batch.parseLine("'foo' 'bar'")); Assert.assertArrayEquals(new String[] { "\"foo\"", "further", "parameters" }, batch.parseLine("'foo' further parameters")); } |
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); } | @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 { 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()); } } |
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; } | @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) { 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); } | @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); } |
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 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); } | @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"); } |
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) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @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); } | @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-INF/conf").exists()); assertFolderNotEmpty("WEB-INF/lib"); }
@Test public void testBlockedIP() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("foobar.org"); ResponseEntity<String> updated = new Updater(request.getServletContext()).updateAppng("1.17.0", null, request); Assert.assertEquals(HttpStatus.FORBIDDEN, updated.getStatusCode()); } |
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); } | @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"); } |
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); } | @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()); } |
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; } | @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)"); } |
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); } | @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())); } |
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(true); p2.setBodyContent(new MockBodyContent(""Ä"", 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()); } |
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); } | @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(); } |
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(); } | @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()); } } |
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); } | @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()); } |
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); } | @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()); } |
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.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } static void main(String[] args); } | @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(classLoader.getResource("txt/replacement.txt").toURI()); FileUtils.deleteQuietly(copy); FileUtils.copyFile(original, copy); Charset utf8 = StandardCharsets.UTF_8; String replacement = IOUtils.toString(new FileInputStream(replacementSource), utf8); System.out.println("Replacement String: " + replacement); ApplicationStartup.replaceInFile(copy, "${replaceMe}", replacement); String newContent = IOUtils.toString(new FileInputStream(copy), utf8); Assert.assertEquals("C:\\Foo\\Bar\\Bla\\Blubb", newContent); } |
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 getPropertyResponse(prop, siteByName, null); } @GetMapping(value = { "/site/{site}/property", "/site/{site}/properties" }) ResponseEntity<Properties> listProperties(@PathVariable("site") String site); @PutMapping(value = "/site/{site}/properties") ResponseEntity<Properties> updateProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @PostMapping(value = "/site/{site}/properties") ResponseEntity<Properties> createProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @DeleteMapping(value = "/site/{site}/properties") ResponseEntity<Properties> deleteProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @GetMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop); @PostMapping(value = "/site/{site}/property") ResponseEntity<Property> createProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @PutMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> updateProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @DeleteMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> deleteProperty(@PathVariable("site") String site,
@PathVariable("prop") String property); } | @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.setCreateRepositoryPath(true); postAndVerify("/site", "xml/site-create.xml", created, HttpStatus.CREATED); getAndVerify("/site/localhost/property", "xml/site-property-list.xml", HttpStatus.OK); Property prop = new Property(); prop.setName(SiteProperties.ASSETS_DIR); prop.setValue("42"); prop.setDefaultValue("this has no effect"); prop.setDescription("foo"); putAndVerify("/site/localhost/property/" + prop.getName(), "xml/site-property-update.xml", prop, HttpStatus.OK); Property xss = new Property(); xss.setName(SiteProperties.XSS_EXCEPTIONS); xss.setValue("#comment\nfoo\nbar"); xss.setClob(true); xss.setDescription("exceptions for XSS protection"); putAndVerify("/site/localhost/property/" + xss.getName(), "xml/site-property-update2.xml", xss, HttpStatus.OK); prop.setName("theAnswer"); prop.setDefaultValue("42"); prop.setDescription("to life, the universe and everything"); postAndVerify("/site/localhost/property", "xml/site-property-create.xml", prop, HttpStatus.CREATED); getAndVerify("/site/localhost/property/theAnswer", "xml/site-property-create.xml", HttpStatus.OK); deleteAndVerify("/site/localhost/property/theAnswer", null, HttpStatus.NO_CONTENT); Properties properties = new Properties(); prop.setName("myNewProp"); properties.getProperty().add(prop); Property existing = new Property(); existing.setName(prop.getName()); properties.getProperty().add(existing); postAndVerify("/site/localhost/properties", "xml/site-properties-create.xml", properties, HttpStatus.OK); properties.getProperty().remove(existing); Property notExisting = new Property(); notExisting.setName("notExisting"); properties.getProperty().add(notExisting); putAndVerify("/site/localhost/properties", "xml/site-properties-update.xml", properties, HttpStatus.OK); deleteAndVerify("/site/localhost/properties", "xml/site-properties-delete.xml", properties, HttpStatus.OK); } |
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.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } @GetMapping(value = "/platform/database") ResponseEntity<Database> info(); @PutMapping(value = "/platform/database") ResponseEntity<Database> updateRootConnection(@RequestBody org.appng.appngizer.model.xml.Database database); @PostMapping(value = "/platform/database/initialize") ResponseEntity<Database> initialize(
@RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged); @GetMapping(value = "/site/{name}/database") ResponseEntity<Databases> getDatabaseConnections(@PathVariable("name") String name); @GetMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> getDatabaseConnectionForApplication(@PathVariable("site") String site,
@PathVariable("app") String app); @PutMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> updateDatabaseConnectionforApplication(@PathVariable("site") String site,
@PathVariable("app") String app, @RequestBody org.appng.appngizer.model.xml.Database database); @GetMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> getDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id); @PutMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> updateDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id, @RequestBody org.appng.appngizer.model.xml.Database database); } | @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(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } | @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(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } | @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 additionalOut); DocumentBuilderFactory getDocumentBuilderFactory(); void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory); TransformerFactory getTransformerFactory(); void setTransformerFactory(TransformerFactory transformerFactory); DocumentBuilder getDocumentBuilder(); void setDocumentBuilder(DocumentBuilder documentBuilder); Transformer getTransformer(); void setTransformer(Transformer transformer); String getInsertBefore(); void setInsertBefore(String insertBefore); String getName(); void setName(String name); String getId(); void cleanup(); boolean isValid(); } | @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(classLoader.getResource("xsl/result.xsl").toURI()).getAbsoluteFile(); File result = new File("target/xsl/result-2.xsl"); FileUtils.writeByteArrayToFile(result, ssProvider.getStyleSheet(true)); List<String> lines1 = FileUtils.readLines(expected, "UTF-8"); List<String> lines2 = FileUtils.readLines(result, "UTF-8"); Assert.assertEquals(lines1.size(), lines2.size()); for (int i = 0; i < lines1.size(); i++) { Assert.assertEquals(lines1.get(i).trim(), lines2.get(i).trim()); } } |
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 prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".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)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } static void main(String[] args); } | @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/ApplicationProperty.java"), StandardCharsets.UTF_8); String expected = FileUtils.readFileToString(new File("src/test/resources/ApplicationProperty.java"), StandardCharsets.UTF_8); Assert.assertEquals(expected, actual); } |
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 ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } | @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 the Galaxy is a comic science fiction series"; Assert.assertTrue(contents.startsWith(expected)); }
@Test public void testNestedTags() throws Exception { String in = "<a:searchable index=\"true\" field=\"contents\">" + "<a:searchable index=\"true\" field=\"field1\"> A </a:searchable>" + "<a:searchable index=\"true\" field=\"field2\"> B </a:searchable>" + "<a:searchable index=\"false\"> C </a:searchable>" + " D </a:searchable>"; Map<String, StringBuilder> parsed = new ParseTags("a").parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertEquals("A", parsed.get("field1").toString()); Assert.assertEquals("B", parsed.get("field2").toString()); Assert.assertNull(parsed.get("field3")); Assert.assertEquals("A B D", parsed.get("contents").toString()); }
@Test public void testNotIndexed() throws Exception { String in = "<html><head></head><appNG:searchable index=\"false\">" + "<appNG:searchable index=\"true\" field=\"field1\"> A </appNG:searchable>" + "<appNG:searchable index=\"true\" field=\"field2\"> B </appNG:searchable>" + "<appNG:searchable index=\"false\"> C </appNG:searchable>" + " D </appNG:searchable></html>"; Map<String, StringBuilder> parsed = parseTags.parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertNull(parsed.get("field1")); Assert.assertNull(parsed.get("field2")); Assert.assertNull(parsed.get("field3")); Assert.assertNull(parsed.get("contents")); } |
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); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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 namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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(width, height); } 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(); } | @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 getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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 prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | @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(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } RequestDataBinder(T target, Request request); RequestDataBinder(T target, Request request, ConversionService conversionService); protected RequestDataBinder(T target); @SuppressWarnings("unchecked") T bind(); } | @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()).thenReturn(paramters.keySet()); Mockito.when(request.getParameterList(Mockito.anyString())).then(new Answer<List<String>>() { public List<String> answer(InvocationOnMock invocation) throws Throwable { return paramters.get(invocation.getArgumentAt(0, String.class)); } }); Map<String, List<FormUpload>> formUploads = getFormUploads(); List<FormUpload> pictures = formUploads.get(PICTURE); Mockito.when(request.getFormUploads()).thenReturn(formUploads); Mockito.when(request.getFormUploads(PICTURE)).thenReturn(pictures); Mockito.when(request.getFormUploads(MORE_PICTURES)).thenReturn(pictures); ConfigurableConversionService conversionService = getConversionService(); RequestDataBinder<Person> requestDataBinder = new RequestDataBinder<Person>(new Person(), request, conversionService); Person person = requestDataBinder.bind(); validate(pictures, person); } |
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<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | @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(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate()); } |
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(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | @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<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | @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().isPaginate()); } |
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 getSha1Digest(String input); static String getSha512Digest(String input); } | @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 String getSha1Digest(String input); static String getSha512Digest(String input); } | @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 String getSha1Digest(String input); static String getSha512Digest(String input); } | @Test public void testSha512Digest() { String sha512Digest = AuthTools.getSha512Digest(testPattern); Assert.assertEquals( "AB9D85DC074D06B675DAEE7FA4A70C7D0BD8F9A284713DAA0E5689DAA9367DD10258E331D3494053B4F5A1084D7881455DB5AADB84BDFAF5638677ED1D1C4881", sha512Digest); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.