public void setUp() throws Exception { IUnifiedRepository repository = new MockUnifiedRepository(new MockUnifiedRepository.SpringSecurityCurrentUserProvider()); datasourceMgmtService = new JcrBackedDatasourceMgmtService(repository, new DatabaseDialectService()); datasourceMgmtWebService = new DefaultDatasourceMgmtWebService(datasourceMgmtService); dbConnectionAdapter = new DatabaseConnectionAdapter(); SecurityContextHolder.getContext() .setAuthentication( new UsernamePasswordAuthenticationToken( MockUnifiedRepository.root().getName(), null, new GrantedAuthority[0])); repository.createFolder( repository.getFile("/etc").getId(), new RepositoryFile.Builder(FOLDER_PDI).folder(true).build(), new RepositoryFileAcl.Builder(MockUnifiedRepository.root()) .ace(MockUnifiedRepository.everyone(), READ, READ_ACL, WRITE, WRITE_ACL) .build(), null); repository.createFolder( repository.getFile("/etc/pdi").getId(), new RepositoryFile.Builder(FOLDER_DATABASES).folder(true).build(), null); SecurityContextHolder.getContext() .setAuthentication( new UsernamePasswordAuthenticationToken(EXP_LOGIN, null, new GrantedAuthority[0])); }
/** * Logs in with given username. * * @param username username of user * @param tenantId tenant to which this user belongs * @tenantAdmin true to add the tenant admin authority to the user's roles */ protected void login(final String username, final ITenant tenant, String[] roles) { StandaloneSession pentahoSession = new StandaloneSession(tenantedUserNameUtils.getPrincipleId(tenant, username)); pentahoSession.setAuthenticated( tenant.getId(), tenantedUserNameUtils.getPrincipleId(tenant, username)); PentahoSessionHolder.setSession(pentahoSession); pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenant.getId()); final String password = "******"; List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); for (String roleName : roles) { authList.add( new GrantedAuthorityImpl(tenantedRoleNameUtils.getPrincipleId(tenant, roleName))); } GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]); UserDetails userDetails = new User(username, password, true, true, true, true, authorities); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password, authorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(auth); SecurityHelper.getInstance().becomeUser(tenantedUserNameUtils.getPrincipleId(tenant, username)); SecurityContextHolder.getContext().setAuthentication(auth); }
public Object authorize(AbstractSecurityContext context) throws Exception { log.debug("Authorize: %s", context); log.debug( "Is %s secured? %b", context.getDestination().getId(), context.getDestination().isSecured()); startAuthorization(context); HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteContext.getCurrentInstance(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); SecurityContext securityContextBefore = null; int securityContextHashBefore = 0; if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { securityContextBefore = loadSecurityContextFromSession(); if (securityContextBefore == null) securityContextBefore = SecurityContextHolder.getContext(); else securityContextHashBefore = securityContextBefore.hashCode(); SecurityContextHolder.setContext(securityContextBefore); authentication = securityContextBefore.getAuthentication(); } if (context.getDestination().isSecured()) { if (!isAuthenticated(authentication) || authentication instanceof AnonymousAuthenticationToken) { log.debug("Is not authenticated!"); throw SecurityServiceException.newNotLoggedInException("User not logged in"); } if (!userCanAccessService(context, authentication)) { log.debug("Access denied for: %s", authentication.getName()); throw SecurityServiceException.newAccessDeniedException("User not in required role"); } } try { Object returnedObject = securityInterceptor != null ? securityInterceptor.invoke(context) : endAuthorization(context); return returnedObject; } catch (AccessDeniedException e) { throw SecurityServiceException.newAccessDeniedException(e.getMessage()); } catch (InvocationTargetException e) { handleAuthorizationExceptions(e); throw e; } finally { if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { // Do this only when not already filtered by Spring Security SecurityContext securityContextAfter = SecurityContextHolder.getContext(); SecurityContextHolder.clearContext(); saveSecurityContextInSession(securityContextAfter, securityContextHashBefore); } } }
protected void login(final String username, final String tenantId, final boolean tenantAdmin) { StandaloneSession pentahoSession = new StandaloneSession(username); pentahoSession.setAuthenticated(username); pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenantId); final String password = "******"; List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); authList.add( new GrantedAuthorityImpl( MessageFormat.format(tenantAuthenticatedAuthorityNamePattern, tenantId))); if (tenantAdmin) { authList.add( new GrantedAuthorityImpl( MessageFormat.format(tenantAdminAuthorityNamePattern, tenantId))); } GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]); UserDetails userDetails = new User(username, password, true, true, true, true, authorities); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password, authorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(auth); manager.newTenant(); manager.newUser(); }
protected void onSetUpInTransaction() throws Exception { super.onSetUpInTransaction(); servletConfig = new MockServletConfig(new MockServletContext(), "simple"); MockServletConfig complexConfig = new MockServletConfig(servletConfig.getServletContext(), "complex"); complexConfig.addInitParameter("publishContext", "false"); complexConfig.addInitParameter("class", "notWritable"); complexConfig.addInitParameter("unknownParam", "someValue"); simpleDispatcherServlet = new DispatcherServlet(); simpleDispatcherServlet.setContextClass(SimpleWebApplicationContext.class); simpleDispatcherServlet.init(servletConfig); complexDispatcherServlet = new DispatcherServlet(); complexDispatcherServlet.setContextClass(WebApplicationContext.class); complexDispatcherServlet.setNamespace("test"); Constants constants = (Constants) applicationContext.getBean("constants"); Authentication auth = constants.getAuthentication(applicationContext); SecurityContextHolder.getContext().setAuthentication(auth); parent = (Controller) applicationContext.getBean("workCodeController"); child = (Controller) applicationContext.getBean("workCodeFormController"); sf = (SessionFactory) applicationContext.getBean("sessionFactory"); }
protected boolean isLoggedIn() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication.getPrincipal() == null) { return false; } return true; }
public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException { // TODO Auto-generated method stub FilterInvocation filterInvocation = (FilterInvocation) filter; String requestURI = filterInvocation.getRequestUrl(); Map<String, Set<String>> urlAuthorities = this.getUrlAuthorities(filterInvocation); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); boolean isSuperUser = false; if (auth != null) { for (int i = 0; i < auth.getAuthorities().length; i++) { if ("超级管理员".equals(auth.getAuthorities()[i].getAuthority())) { isSuperUser = true; break; } } if ((!isSuperUser) && (!isUrlGrantedRight(requestURI, auth))) { return null; } else { String grantedAuthorities = null; grantedAuthorities = getAuth(requestURI, auth); if (grantedAuthorities != null) { ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor(); configAttrEditor.setAsText(grantedAuthorities); return (ConfigAttributeDefinition) configAttrEditor.getValue(); } } } return null; }
/** {@inheritDoc} */ @Override protected void doFilterHttp( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { boolean shouldFilter = AclUtils.shouldFilter(); try { if (shouldFilter) { String user = SecurityContextHolder.getContext().getAuthentication().getName(); List<Group> groups = m_groupDao.findGroupsForUser(user); String[] groupNames = new String[groups.size()]; for (int i = 0; i < groups.size(); i++) { groupNames[i] = groups.get(i).getName(); } m_filterManager.enableAuthorizationFilter(groupNames); } chain.doFilter(request, response); } finally { if (shouldFilter) { m_filterManager.disableAuthorizationFilter(); } } }
public Principal login(Object credentials, String charset) { List<String> decodedCredentials = Arrays.asList(decodeBase64Credentials(credentials, charset)); HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance(); HttpServletRequest httpRequest = context.getRequest(); String user = decodedCredentials.get(0); String password = decodedCredentials.get(1); Authentication auth = new UsernamePasswordAuthenticationToken(user, password); Principal principal = null; ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext( httpRequest.getSession().getServletContext()); if (ctx != null) { AbstractAuthenticationManager authenticationManager = BeanFactoryUtils.beanOfTypeIncludingAncestors(ctx, AbstractAuthenticationManager.class); try { Authentication authentication = authenticationManager.authenticate(auth); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); principal = authentication; SecurityContextHolder.setContext(securityContext); saveSecurityContextInSession(securityContext, 0); endLogin(credentials, charset); } catch (AuthenticationException e) { handleAuthenticationExceptions(e); } } log.debug("User %s logged in", user); return principal; }
@Before public void setUp() { String[] configFiles = new String[] {"springTestFilterBeans.xml"}; this.ctx = new ClassPathXmlApplicationContext(configFiles); SecurityContextHolder.getContext().setAuthentication(null); this.filter = (NegotiateSecurityFilter) this.ctx.getBean("waffleNegotiateSecurityFilter"); }
private void setCurrentUser(String username) { originalSecurityContext = SecurityContextHolder.getContext(); SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication( new UsernamePasswordAuthenticationToken( new User(username, "", true, new GrantedAuthority[] {}), null)); SecurityContextHolder.setContext(context); }
@BeforeMethod public void setupSysadmin() { Enterprise e = enterpriseGenerator.createUniqueInstance(); Role r = roleGenerator.createInstance(); User u = userGenerator.createInstance(e, r, "sysadmin", "sysadmin"); setup(e, r, u); SecurityContextHolder.getContext().setAuthentication(new SysadminAuthentication()); }
protected boolean isAdmin() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication.getPrincipal() == null) { return false; } if (hasAdminRole(authentication.getAuthorities())) { return true; } return false; }
protected User getLoggedInUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { return null; } Object obj = auth.getPrincipal(); if (obj instanceof UserDetails) { return (User) obj; } return null; }
public User getUser() { // 取得登录用户 SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); User user = null; if (auth.getPrincipal() instanceof UserDetails) { user = (User) auth.getPrincipal(); } return user; }
/** * After returning, grab the user, check if they've been modified and reset the SecurityContext if * they have. * * @param returnValue the user object * @param method the name of the method executed * @param args the arguments to the method * @param target the target class * @throws Throwable thrown when args[0] is null or not a User object */ public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { User user = (User) args[0]; if (user.getVersion() != null) { // reset the authentication object if current user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles boolean signupUser = resolver.isAnonymous(auth); if (auth != null && !signupUser) { User currentUser = getCurrentUser(auth); if (currentUser.getId().equals(user.getId())) { auth = new UsernamePasswordAuthenticationToken( user, user.getPassword(), user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); } } } }
/** * Returns the connected user details. * * @return */ public static Account getLoginAccount() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authen = context.getAuthentication(); Object principal = null; if (authen != null) { principal = authen.getPrincipal(); } if (principal != null && principal instanceof Account) { return (Account) principal; } else { return null; } } // - getLoginAccount
protected void loginAsRepositoryAdmin() { StandaloneSession pentahoSession = new StandaloneSession(repositoryAdminUsername); pentahoSession.setAuthenticated(repositoryAdminUsername); final GrantedAuthority[] repositoryAdminAuthorities = new GrantedAuthority[] {}; final String password = "******"; UserDetails repositoryAdminUserDetails = new User( repositoryAdminUsername, password, true, true, true, true, repositoryAdminAuthorities); Authentication repositoryAdminAuthentication = new UsernamePasswordAuthenticationToken( repositoryAdminUserDetails, password, repositoryAdminAuthorities); PentahoSessionHolder.setSession(pentahoSession); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication(repositoryAdminAuthentication); }
@Test public void testGuestIsDisabled() throws IOException, ServletException { String securityPackage = "Negotiate"; SimpleFilterChain filterChain = new SimpleFilterChain(); SimpleHttpRequest request = new SimpleHttpRequest(); String clientToken = BaseEncoding.base64().encode("Guest".getBytes()); request.addHeader("Authorization", securityPackage + " " + clientToken); SimpleHttpResponse response = new SimpleHttpResponse(); this.filter.doFilter(request, response, filterChain); assertEquals(401, response.getStatus()); assertNull(SecurityContextHolder.getContext().getAuthentication()); }
public void testAddUserWithoutAdminRole() throws Exception { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertTrue(auth.isAuthenticated()); UserManager userManager = makeInterceptedTarget(); User user = new User("admin"); user.setId(2L); try { userManager.saveUser(user); fail("AccessDeniedException not thrown"); } catch (AccessDeniedException expected) { assertNotNull(expected); assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED); } }
/** * {@inheritDoc} * * <p>Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and * {@code credentials} and passes to Spring Security {@code AuthenticationManager}. */ @Override protected Authentication getAuthentication( final Principal principal, final Credentials credentials) throws RepositoryException { // only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit // indirectly) if (!(credentials instanceof SimpleCredentials)) { logger.debug("credentials not instance of SimpleCredentials; returning null"); // $NON-NLS-1$ return null; } SimpleCredentials simpleCredentials = (SimpleCredentials) credentials; UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword())); boolean authenticated = false; try { org.springframework.security.Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getName().equals(simpleCredentials.getUserID())) { // see if there's already an active Authentication for this user. authenticated = true; } else { // delegate to Spring Security getAuthenticationManager().authenticate(token); authenticated = true; } } catch (AuthenticationException e) { logger.debug("authentication exception", e); // $NON-NLS-1$ } final boolean authenticateResult = authenticated; return new Authentication() { public boolean canHandle(Credentials credentials) { // this is decided earlier in getAuthentication return true; } public boolean authenticate(Credentials credentials) throws RepositoryException { return authenticateResult; } }; }
/** * Save the user, encrypting their passwords if necessary * * @return success when good things happen * @throws Exception when bad things happen */ public String save() throws Exception { user.setEnabled(true); // Set the default user role on this new user user.addRole(roleManager.getRole(Constants.USER_ROLE)); try { userManager.saveUser(user); } catch (AccessDeniedException ade) { // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity log.warn(ade.getMessage()); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (UserExistsException e) { log.warn(e.getMessage()); List<Object> args = new ArrayList<Object>(); args.add(user.getUsername()); args.add(user.getEmail()); addActionError(getText("errors.existing.user", args)); // redisplay the unencrypted passwords user.setPassword(user.getConfirmPassword()); return INPUT; } saveMessage(getText("user.registered")); getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); // log user in automatically UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( user.getUsername(), user.getConfirmPassword(), user.getAuthorities()); auth.setDetails(user); SecurityContextHolder.getContext().setAuthentication(auth); // Send an account information e-mail mailMessage.setSubject(getText("signup.email.subject")); try { sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest())); } catch (MailException me) { addActionError(me.getMostSpecificCause().getMessage()); } return SUCCESS; }
void onValidateForm() { provider.setUserDetailsService(userserve); provider.setPasswordEncoder(new ShaPasswordEncoder()); authtoken = new UsernamePasswordAuthenticationToken(fLogin, fpass); provider.setSaltSource(salt); Authentication token = null; try { token = provider.authenticate(authtoken); } catch (org.springframework.security.BadCredentialsException e) { loginform.recordError("Either the Username or Password is incorrect, Please try again."); return; } if (token.isAuthenticated()) { System.out.println("user has been authenticated"); this.user = userDAO.findByUsername(fLogin); SecurityContextHolder.getContext().setAuthentication(token); SavedRequest savedRequest = (SavedRequest) requestGlobals .getHTTPServletRequest() .getSession() .getAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY); Session s = request.getSession(false); s.invalidate(); s = request.getSession(true); if (savedRequest != null) { url = null; try { url = new URL(savedRequest.getRequestURL()); } catch (MalformedURLException e) { System.out.println("malformed url:" + savedRequest.getRequestURI()); } } } else { // fpass = null; // fLogin = null; loginform.recordError("Either the Username or Password is incorrect, Please try again."); } }
/** * Try to get the User information from the session. * * @return represents the user currently in session */ private UserDetails getUserDetails() { UserDetails user = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (null != auth) { Object obj = auth.getPrincipal(); if (obj instanceof UserDetails) { user = (UserDetails) obj; log.debug("Found username: " + user.getUsername()); } } if (null == user) { user = new NoCurrentUserDetails(); } return user; }
@RequestMapping("/sys/sysres/toResources.htm") public ModelAndView toResources( HttpServletRequest request, HttpServletResponse response, @ModelAttribute("res") TSysRes res, @ModelAttribute("page") Page page) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); TUser u = (TUser) (auth.getPrincipal()); List<TSysRes> resList = rService.querySysRes(res, page, u); Map<String, Object> mode = new HashMap<String, Object>(); mode.put("user", u); mode.put("resList", resList); mode.put("page", page); return new ModelAndView(QUERY_ALL_RES, mode); }
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && targetRole != null) { if (shouldCheck(authentication) && allowedIPAddresses != null) { if (!shouldAllow(request)) { throw new AccessDeniedException( "Access has been denied for your IP address: " + request.getRemoteAddr()); } } } else { log.warn( "The IPRoleAuthentificationFilter should be placed after the user has been authentificated in filter chain"); } filterChain.doFilter(request, response); }
@Override protected void doFilterHttp( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String ticketParameter = request.getParameter(GENERATE_TICKET_PARAM_NAME); if (!StringUtils.isEmpty(ticketParameter)) { if (SecurityContextHolder.getContext().getAuthentication() == null) { log.error(MISSING_AUTH_ERROR_MESSAGE); sendError(response, MISSING_AUTH_ERROR_MESSAGE); response.flushBuffer(); return; } String appName = request.getParameter(REQUESTING_APP_PARAM_NAME); if (StringUtils.isEmpty(appName)) { sendError(response, "Required parameter " + REQUESTING_APP_PARAM_NAME + " is not set"); return; } String username = request.getParameter(REQUESTING_USERNAME_PARAM_NAME); if (StringUtils.isEmpty(username)) { sendError(response, "Required parameter " + REQUESTING_USERNAME_PARAM_NAME + " is not set"); return; } LoginTicket ticket = null; try { ticket = getLoginTicketManager().generateNewTicket(appName, username); } catch (ExternalAppNotMappedException e) { sendError( response, "Application name '" + appName + "' was not found in the current Pentaho mappings"); return; } // TODO: use a cleaner way to output JSON, maybe? response.getWriter().write("{\"ticketId\": \"" + ticket.getIdAsString() + "\"}"); response.flushBuffer(); return; } else { chain.doFilter(request, response); } }
@Override protected void setUp() throws Exception { super.setUp(); // store initial security context for later restoration initialSecurityContext = SecurityContextHolder.getContext(); SecurityContext context = new SecurityContextImpl(); User user = new User("user"); user.setId(1L); user.setPassword("password"); user.addRole(new Role(Constants.USER_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); context.setAuthentication(token); SecurityContextHolder.setContext(context); }
@Test public void testNegotiate() throws IOException, ServletException { String securityPackage = "Negotiate"; SimpleFilterChain filterChain = new SimpleFilterChain(); SimpleHttpRequest request = new SimpleHttpRequest(); String clientToken = BaseEncoding.base64().encode(WindowsAccountImpl.getCurrentUsername().getBytes()); request.addHeader("Authorization", securityPackage + " " + clientToken); SimpleHttpResponse response = new SimpleHttpResponse(); this.filter.doFilter(request, response, filterChain); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertNotNull(auth); GrantedAuthority[] authorities = auth.getAuthorities(); assertNotNull(authorities); assertEquals(3, authorities.length); assertEquals("ROLE_USER", authorities[0].getAuthority()); assertEquals("ROLE_USERS", authorities[1].getAuthority()); assertEquals("ROLE_EVERYONE", authorities[2].getAuthority()); assertEquals(0, response.getHeaderNamesSize()); }
protected void onSetUpInTransaction() throws Exception { super.onSetUpInTransaction(); HoursWorked hours = null; HoursWorkedDaoHibernate dao = null; JobManager mgrJob = null; FulltimeAgreements fulltimeAgreement = null; FulltimeAgreementDao fulltimeDao = null; WorkCodeDao workcodeDao = null; PeoplePropertiesDao peopleDao = null; JobDao jobDao = null; HoursWorkedDao hoursDao = null; PeopleProperties people = null; super.onSetUpBeforeTransaction(); mgrJob = (JobManager) applicationContext.getBean("jobManager"); Constants constants = (Constants) applicationContext.getBean("constants"); Authentication auth = constants.getAuthentication(applicationContext); SecurityContextHolder.getContext().setAuthentication(auth); CodeTermDao termDao = (CodeTermDao) applicationContext.getBean("termDao"); CodeTerm term = termDao.findTerm("FA"); if (term == null) { term = new CodeTerm(); term.setTerm("FA"); termDao.saveTerms(term); } PayPeriodDao payDao = (PayPeriodDao) applicationContext.getBean("payPeriodDao"); PayPeriodDao payPeriodDao = (PayPeriodDao) applicationContext.getBean("payPeriodDao"); workcodeDao = (WorkCodeDao) applicationContext.getBean("workCodeDao"); peopleDao = (PeoplePropertiesDao) applicationContext.getBean("peoplePropertiesDao"); people = peopleDao.getPerson("000201922"); if (people == null) { // inserted = true; people = new PeopleProperties(); people.setFirstName("first"); people.setLastName("last"); people.setMiddleName("middle"); people.setGovernmentId("999999999"); people.setPeopleId("000201922"); peopleDao.save(people); log.debug("INSERTED PERSON"); } // 133 Bus.Office 01-IS-00-133 59 000203290 01-IS-00-133 jobDao = (JobDao) applicationContext.getBean("jobDao"); Job jobBus = mgrJob.getJobByDepartment("133"); if (jobBus == null) { log.debug("insert job "); // insertedJob = true; jobBus = new Job(); // job.setId(1L); jobBus.setAccountNumber("XXX"); jobBus.setDepartment("133"); jobBus.setDescription("bus.off"); jobDao.saveJob(jobBus); } Job jobIt = jobDao.getJob("071"); if (jobIt == null) { log.debug("insert job "); jobIt = new Job(); jobIt.setAccountNumber("XXX"); jobIt.setDepartment("071"); jobIt.setDescription("it"); jobDao.saveJob(jobIt); } fulltimeDao = (FulltimeAgreementDao) applicationContext.getBean("fulltimeAgreementDao"); Set<FulltimeAgreements> agreements = people.getFulltimeAgreements(); fulltimeAgreement = new FulltimeAgreements(); fulltimeAgreement.setActive(true); fulltimeAgreement.setJob(jobIt); fulltimeAgreement.setOvertime(555); fulltimeAgreement.setRate(555); fulltimeAgreement.setPeople(people); agreements.add(fulltimeAgreement); hoursDao = (HoursWorkedDao) applicationContext.getBean("hoursWorkedDao"); List<HoursWorked> hoursList = hoursDao.getHoursWorked("000201922", "133", Constants.getDate("MM/dd/yyyy", "01/01/2008")); if (hoursList == null || hoursList.size() < 1) { log.debug("insert hours "); // insertedJob = true; hours = new HoursWorked(); hours.setPeopleId("000201922"); hours.setJob(mgrJob.getJobByDepartment("133")); hours.setDateIn(Constants.getDate("MM/dd/yyyy", "01/01/2008")); WorkCode w = workcodeDao.getWorkCode("LOGIN"); hours.setWorkcode(w); hoursDao.saveHoursWorked(hours); } termDao = (CodeTermDao) applicationContext.getBean("termDao"); term = termDao.findTerm("FA"); if (term == null) { term = new CodeTerm(); term.setTerm("FA"); termDao.saveTerms(term); } payPeriodDao = (PayPeriodDao) applicationContext.getBean("payPeriodDao"); java.sql.Date beginDate = Constants.getSqlDate("MM/dd/yyyy", "01/01/2008"); PayPer pay = (PayPer) payPeriodDao.getPeriod(beginDate, false); if (pay == null) { pay = new PayPer(); pay.setCodeTerm(term); pay.setBeginDate(beginDate); pay.setEndDate( Constants.addField(Calendar.DATE, -1, Constants.addField(Calendar.MONTH, 1, beginDate))); pay.setPpYear("" + Constants.year(beginDate)); payPeriodDao.savePeriod(pay); } AwardedDao awardDao = (AwardedDao) applicationContext.getBean("awardedDao"); List<Awarded> awarded = (List<Awarded>) awardDao.getAward("000201922", "2008", "FA"); if (awarded == null || awarded.size() == 0) { AgreementsDao agreeDao = (AgreementsDao) applicationContext.getBean("agreementsDao"); Awarded award1 = new Awarded(); award1.setAmount(2000); award1.setAwards(awardDao.getAwards("IWX652")); award1.setCodeTerm(term); PeopleProperties p = new PeopleProperties(); p.setPeopleId("000201922"); award1.setPerson(p); award1.setYear("2008"); awardDao.saveAward(award1); Agreements agree = new Agreements(); agree.setAmount(-1); agree.setAwarded(award1); agree.setJob(jobBus); agree.setRate(655); agreeDao.saveAgreement(agree); Awarded award2 = new Awarded(); award2.setAmount(444); award2.setAwards(awardDao.getAwards("FWN651")); award2.setCodeTerm(term); p = new PeopleProperties(); p.setPeopleId("000198239"); award1.setPerson(p); award2.setYear("2008"); awardDao.saveAward(award2); Agreements agree2 = new Agreements(); agree2.setAmount(100); agree2.setAwarded(award2); agree2.setJob(jobIt); agree2.setRate(655); agreeDao.saveAgreement(agree2); } }