├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── screenshots ├── APIResponse.png ├── Dashboard.png ├── HomePage.png ├── RegisterWithValidationFail.png └── RegisterWithValidationSuccess.png └── src ├── main ├── java │ └── yourwebproject2 │ │ ├── auth │ │ ├── AuthCredentialsMissingException.java │ │ ├── AuthenticationFailedException.java │ │ ├── CORSFilter.java │ │ └── JWTTokenAuthFilter.java │ │ ├── controller │ │ ├── CategoryController.java │ │ ├── ErrorController.java │ │ ├── JobController.java │ │ └── UserController.java │ │ ├── core │ │ ├── AbstractJobSchedulingWorker.java │ │ ├── JobExecutionThread.java │ │ ├── MailSendingTask.java │ │ ├── NewJobSchedulingWorker.java │ │ ├── RetryJobSchedulingWorker.java │ │ ├── YourWebProjectJobCoreDaemon.java │ │ └── tool │ │ │ ├── AdminUserTool.java │ │ │ └── CategoryTool.java │ │ ├── framework │ │ ├── api │ │ │ └── APIResponse.java │ │ ├── controller │ │ │ └── BaseController.java │ │ ├── data │ │ │ ├── BaseHibernateJPARepository.java │ │ │ ├── BaseJPARepository.java │ │ │ ├── BaseJPAServiceImpl.java │ │ │ ├── BaseService.java │ │ │ ├── Entity.java │ │ │ └── JPAEntity.java │ │ ├── exception │ │ │ ├── EmailNotFoundException.java │ │ │ └── NotFoundException.java │ │ └── servlet │ │ │ └── BaseDispatcherServlet.java │ │ ├── interceptor │ │ ├── WebAppExceptionAdvice.java │ │ └── WebAppMetricsInterceptor.java │ │ ├── model │ │ ├── dto │ │ │ ├── CategoryDTO.java │ │ │ ├── JobDTO.java │ │ │ └── UserDTO.java │ │ ├── entity │ │ │ ├── Category.java │ │ │ ├── Job.java │ │ │ ├── MailerJob.java │ │ │ ├── User.java │ │ │ └── helper │ │ │ │ └── CategoryPriorityComparator.java │ │ └── repository │ │ │ ├── CategoryRepository.java │ │ │ ├── JobRepository.java │ │ │ ├── UserRepository.java │ │ │ └── impl │ │ │ ├── CategoryRepositoryImpl.java │ │ │ ├── JobRepositoryImpl.java │ │ │ └── UserRepositoryImpl.java │ │ ├── service │ │ ├── CategoryService.java │ │ ├── JobService.java │ │ ├── MailJobService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── CategoryServiceImpl.java │ │ │ ├── JobServiceImpl.java │ │ │ ├── MailJobServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ ├── servlet │ │ └── YourWebAppDispatcherServlet.java │ │ └── unusedspringsecurity │ │ ├── CSRFHeaderFilter.java │ │ ├── RESTAuthFilter.java │ │ ├── RESTAuthenticationEntryPoint.java │ │ ├── UserDetailsService.java │ │ ├── UserDetailsServiceImpl.java │ │ ├── UserRole.java │ │ ├── appContext-security.xml │ │ └── token │ │ ├── StatelessAuthenticationFilter.java │ │ ├── TokenAuthenticationService.java │ │ ├── TokenHandler.java │ │ ├── TokenUserAuthentication.java │ │ └── TokenUserService.java ├── resources │ ├── config │ │ ├── database │ │ │ ├── hibernate.cfg.xml │ │ │ └── test-hibernate.cfg.xml │ │ └── spring │ │ │ ├── appContext-auth.xml │ │ │ ├── appContext-interceptor.xml │ │ │ ├── appContext-jdbc-test.xml │ │ │ ├── appContext-jdbc.xml │ │ │ ├── appContext-repository.xml │ │ │ ├── appContext-scheduler.xml │ │ │ ├── appContext-service.xml │ │ │ ├── appContext-servlet.xml │ │ │ └── appContext-ywp2.xml │ └── logback.xml └── webapp │ ├── WEB-INF │ ├── error.jsp │ └── web.xml │ ├── index.html │ ├── res │ ├── css │ │ ├── app.css │ │ ├── sandstone.bootstrap.min.css │ │ ├── slate.bootstrap.min.css │ │ └── superhero.bootstrap.min.css │ └── js │ │ ├── angular-animate │ │ ├── angular-animate.js │ │ ├── angular-animate.min.js │ │ ├── angular-animate.min.js.map │ │ └── index.js │ │ ├── angular-cookies │ │ ├── angular-cookies.js │ │ ├── angular-cookies.min.js │ │ ├── angular-cookies.min.js.map │ │ └── index.js │ │ ├── angular-messages │ │ ├── angular-messages.js │ │ ├── angular-messages.min.js │ │ ├── angular-messages.min.js.map │ │ └── index.js │ │ ├── angular-mocks │ │ ├── angular-mocks.js │ │ ├── ngAnimateMock.js │ │ ├── ngMock.js │ │ └── ngMockE2E.js │ │ ├── angular-resource │ │ ├── angular-resource.js │ │ ├── angular-resource.min.js │ │ ├── angular-resource.min.js.map │ │ └── index.js │ │ ├── angular-route │ │ ├── angular-route.js │ │ ├── angular-route.min.js │ │ ├── angular-route.min.js.map │ │ └── index.js │ │ ├── angular-ui-router │ │ ├── api │ │ │ └── angular-ui-router.d.ts │ │ └── release │ │ │ ├── angular-ui-router.js │ │ │ └── angular-ui-router.min.js │ │ ├── angular │ │ ├── angular-csp.css │ │ ├── angular.js │ │ ├── angular.min.js │ │ ├── angular.min.js.gzip │ │ ├── angular.min.js.map │ │ └── index.js │ │ ├── bootstrap │ │ └── dist │ │ │ ├── css │ │ │ ├── bootstrap-theme.css │ │ │ ├── bootstrap-theme.css.map │ │ │ ├── bootstrap-theme.min.css │ │ │ ├── bootstrap.css │ │ │ ├── bootstrap.css.map │ │ │ └── bootstrap.min.css │ │ │ ├── fonts │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ └── glyphicons-halflings-regular.woff │ │ │ └── js │ │ │ ├── bootstrap.js │ │ │ └── bootstrap.min.js │ │ ├── cryptojs │ │ └── rollups │ │ │ ├── aes.js │ │ │ ├── hmac-md5.js │ │ │ ├── hmac-ripemd160.js │ │ │ ├── hmac-sha1.js │ │ │ ├── hmac-sha224.js │ │ │ ├── hmac-sha256.js │ │ │ ├── hmac-sha3.js │ │ │ ├── hmac-sha384.js │ │ │ ├── hmac-sha512.js │ │ │ ├── md5.js │ │ │ ├── pbkdf2.js │ │ │ ├── rabbit-legacy.js │ │ │ ├── rabbit.js │ │ │ ├── rc4.js │ │ │ ├── ripemd160.js │ │ │ ├── sha1.js │ │ │ ├── sha224.js │ │ │ ├── sha256.js │ │ │ ├── sha3.js │ │ │ ├── sha384.js │ │ │ ├── sha512.js │ │ │ └── tripledes.js │ │ ├── jquery │ │ └── dist │ │ │ ├── jquery.js │ │ │ ├── jquery.min.js │ │ │ └── jquery.min.map │ │ └── spring-security-csrf-token-interceptor │ │ └── dist │ │ └── spring-security-csrf-token-interceptor.min.js │ └── webui │ ├── YWP2Web.js │ ├── controllers │ ├── AdminController.js │ ├── AppController.js │ ├── HomeController.js │ ├── LoginController.js │ └── RegisterController.js │ ├── modules │ ├── Admin.js │ ├── App.js │ ├── Auth.js │ ├── Common.js │ └── FlashMessage.js │ ├── services │ ├── AppService.js │ └── AuthService.js │ ├── templates │ └── admin.html │ └── views │ ├── access-denied.html │ ├── common │ ├── footer.html │ ├── header.html │ ├── nfooter.html │ └── nheader.html │ ├── dashboard.html │ ├── home.html │ ├── login.html │ └── register.html └── test └── java └── yourwebproject2 ├── BCryptPaswordEncoderTester.java ├── CategoryControllerTest.java └── JobControllerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Spring-AngularJS-Java-WebApp-Template-Project.iml 3 | .idea 4 | target -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Y Kamesh Rao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /screenshots/APIResponse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/screenshots/APIResponse.png -------------------------------------------------------------------------------- /screenshots/Dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/screenshots/Dashboard.png -------------------------------------------------------------------------------- /screenshots/HomePage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/screenshots/HomePage.png -------------------------------------------------------------------------------- /screenshots/RegisterWithValidationFail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/screenshots/RegisterWithValidationFail.png -------------------------------------------------------------------------------- /screenshots/RegisterWithValidationSuccess.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/screenshots/RegisterWithValidationSuccess.png -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/auth/AuthCredentialsMissingException.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.auth; 2 | 3 | import javax.servlet.ServletException; 4 | 5 | /** 6 | * Exception indicating Auth credentials missing. 7 | * 8 | * @author: kameshr 9 | */ 10 | public class AuthCredentialsMissingException extends ServletException { 11 | private static final long serialVersionUID = -8799659324455306881L; 12 | 13 | public AuthCredentialsMissingException(String message) { 14 | super(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/auth/AuthenticationFailedException.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.auth; 2 | 3 | import javax.servlet.ServletException; 4 | 5 | /** 6 | * Exception indication Authentication failure 7 | * 8 | * @author: kameshr 9 | */ 10 | public class AuthenticationFailedException extends ServletException { 11 | private static final long serialVersionUID = -8799659324455306881L; 12 | 13 | public AuthenticationFailedException(String message) { 14 | super(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/auth/CORSFilter.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.auth; 2 | 3 | import org.springframework.core.Ordered; 4 | import org.springframework.core.annotation.Order; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.*; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | /** 13 | * If required. not used here. 14 | * 15 | * @author: kameshr 16 | */ 17 | @Component 18 | @Order(Ordered.HIGHEST_PRECEDENCE) 19 | public class CORSFilter implements Filter { 20 | 21 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 22 | HttpServletRequest request = (HttpServletRequest) req; 23 | HttpServletResponse response = (HttpServletResponse) res; 24 | response.setHeader("Access-Control-Allow-Origin", "*"); 25 | response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); 26 | response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 27 | response.setHeader("Access-Control-Max-Age", "3600"); 28 | if (request.getMethod() != "OPTIONS") { 29 | chain.doFilter(req, res); 30 | } else { 31 | } 32 | } 33 | 34 | public void init(FilterConfig filterConfig) {} 35 | 36 | public void destroy() {} 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/auth/JWTTokenAuthFilter.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.auth; 2 | 3 | import io.jsonwebtoken.Claims; 4 | import io.jsonwebtoken.Jwts; 5 | import yourwebproject2.service.UserService; 6 | import org.apache.commons.lang.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.web.filter.OncePerRequestFilter; 11 | 12 | import javax.servlet.FilterChain; 13 | import javax.servlet.ServletException; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | import java.io.IOException; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.regex.Pattern; 20 | 21 | /** 22 | * @author: kameshr 23 | */ 24 | public class JWTTokenAuthFilter extends OncePerRequestFilter { 25 | private static List AUTH_ROUTES = new ArrayList<>(); 26 | private static List NO_AUTH_ROUTES = new ArrayList<>(); 27 | public static final String JWT_KEY = "JWT-TOKEN-SECRET"; 28 | 29 | static { 30 | AUTH_ROUTES.add(Pattern.compile("/api/*")); 31 | NO_AUTH_ROUTES.add("/api/user/authenticate"); 32 | NO_AUTH_ROUTES.add("/api/user/register"); 33 | } 34 | 35 | private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class); 36 | 37 | @Autowired 38 | private UserService userService; 39 | 40 | @Override 41 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 42 | FilterChain filterChain) throws ServletException, IOException { 43 | String authorizationHeader = request.getHeader("authorization"); 44 | String authenticationHeader = request.getHeader("authentication"); 45 | String route = request.getRequestURI(); 46 | 47 | // no auth route matching 48 | boolean needsAuthentication = false; 49 | 50 | for (Pattern p : AUTH_ROUTES) { 51 | if (p.matcher(route).matches()) { 52 | needsAuthentication = true; 53 | break; 54 | } 55 | } 56 | 57 | if(route.startsWith("/api/")) { 58 | needsAuthentication = true; 59 | } 60 | 61 | if (NO_AUTH_ROUTES.contains(route)) { 62 | needsAuthentication = false; 63 | } 64 | 65 | // Checking whether the current route needs to be authenticated 66 | if (needsAuthentication) { 67 | // Check for authorization header presence 68 | String authHeader = null; 69 | if (authorizationHeader == null || authorizationHeader.equalsIgnoreCase("")) { 70 | if (authenticationHeader == null || authenticationHeader.equalsIgnoreCase("")) { 71 | authHeader = null; 72 | } else { 73 | authHeader = authenticationHeader; 74 | LOG.info("authentication: " + authenticationHeader); 75 | } 76 | } else { 77 | authHeader = authorizationHeader; 78 | LOG.info("authorization: " + authorizationHeader); 79 | } 80 | 81 | if (StringUtils.isBlank(authHeader) || !authHeader.startsWith("Bearer ")) { 82 | throw new AuthCredentialsMissingException("Missing or invalid Authorization header."); 83 | } 84 | 85 | final String token = authHeader.substring(7); // The part after "Bearer " 86 | try { 87 | final Claims claims = Jwts.parser().setSigningKey(JWT_KEY) 88 | .parseClaimsJws(token).getBody(); 89 | request.setAttribute("claims", claims); 90 | 91 | // Now since the authentication process if finished 92 | // move the request forward 93 | filterChain.doFilter(request, response); 94 | } catch (final Exception e) { 95 | throw new AuthenticationFailedException("Invalid token. Cause:"+e.getMessage()); 96 | } 97 | } else { 98 | filterChain.doFilter(request, response); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/controller/ErrorController.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.controller; 2 | 3 | import yourwebproject2.framework.api.APIResponse; 4 | import yourwebproject2.framework.controller.BaseController; 5 | import org.apache.commons.lang.exception.ExceptionUtils; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.text.MessageFormat; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * @author: kameshr 21 | */ 22 | @Controller 23 | public class ErrorController extends BaseController { 24 | private static Logger LOG = LoggerFactory.getLogger(ErrorController.class); 25 | 26 | @RequestMapping("error") 27 | public @ResponseBody APIResponse customError(HttpServletRequest request, HttpServletResponse response) { 28 | Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); 29 | Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); 30 | String exceptionMessage = (String) request.getAttribute("javax.servlet.error.message"); 31 | 32 | HttpStatus httpStatus = HttpStatus.valueOf(statusCode); 33 | String httpReason = httpStatus.getReasonPhrase(); 34 | 35 | String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri"); 36 | if (requestUri == null) { 37 | requestUri = "Unknown"; 38 | } 39 | 40 | Map resp = new HashMap<>(); 41 | String message = MessageFormat.format("{0} {1} returned for {2} with message: {3}", 42 | statusCode, httpReason, requestUri, exceptionMessage); 43 | resp.put("message", message); 44 | resp.put("cause", exceptionMessage); 45 | resp.put("exceptionRootCauseMessage", ExceptionUtils.getRootCauseMessage(throwable)); 46 | resp.put("stacktrace", ExceptionUtils.getRootCauseStackTrace(throwable)); 47 | 48 | LOG.error(message); 49 | ExceptionUtils.printRootCauseStackTrace(throwable); 50 | LOG.error(ExceptionUtils.getFullStackTrace(throwable)); 51 | 52 | return APIResponse.toExceptionResponse(exceptionMessage, resp); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/controller/JobController.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.controller; 2 | 3 | import yourwebproject2.framework.api.APIResponse; 4 | import yourwebproject2.framework.controller.BaseController; 5 | import yourwebproject2.model.dto.JobDTO; 6 | import yourwebproject2.model.entity.Category; 7 | import yourwebproject2.model.entity.Job; 8 | import yourwebproject2.service.CategoryService; 9 | import yourwebproject2.service.JobService; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.stereotype.Controller; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import java.util.Date; 17 | 18 | /** 19 | * Job submission and status APIs 20 | * 21 | * Created by Y.Kamesh on 8/2/2015. 22 | */ 23 | @Controller 24 | @RequestMapping("job") 25 | public class JobController extends BaseController { 26 | private static Logger LOG = LoggerFactory.getLogger(JobController.class); 27 | 28 | @Autowired 29 | private JobService jobService; 30 | 31 | @Autowired 32 | private CategoryService categoryService; 33 | 34 | /** 35 | * Method to handle creation of the job by extracting the jobInfo json from 36 | * POST body expected in the format - {"name":"job1", "metadataJsonString":"{}", "callbackUrl":"", "catId":1} 37 | * 38 | * @param jobDTO 39 | * @return 40 | * @throws Exception 41 | */ 42 | @RequestMapping(value = "/submit", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER}) 43 | public @ResponseBody 44 | APIResponse submitJob(@RequestBody JobDTO jobDTO) throws Exception { 45 | Long catId = jobDTO.getCatId(); 46 | 47 | if(catId==null) { 48 | throw new IllegalArgumentException("categoryId is required to prioritize"); 49 | } 50 | 51 | Category category = categoryService.findById(catId); 52 | 53 | Job job = new Job(); 54 | job.setName(jobDTO.getName()); 55 | job.setMetadataJson(jobDTO.getMetadataJsonString()); 56 | job.setCategory(category); 57 | job.setCallbackUrl(jobDTO.getCallbackURL()); 58 | job.setSubmitTime(new Date(System.currentTimeMillis())); 59 | job.setStatus(Job.Status.NEW); 60 | job.setRetryCount(0); 61 | 62 | jobService.insert(job); 63 | return APIResponse.toOkResponse(job); 64 | } 65 | 66 | /** 67 | * Method to get the status of a job by given id 68 | * GET 69 | * 70 | * @param jobId 71 | * @return 72 | * @throws Exception 73 | */ 74 | @RequestMapping(value = "/status/{jobId}", method = RequestMethod.GET) 75 | public @ResponseBody 76 | APIResponse jobStatus(@PathVariable Long jobId) throws Exception { 77 | Job job = jobService.findById(jobId); 78 | return APIResponse.toOkResponse(job); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/AbstractJobSchedulingWorker.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | import yourwebproject2.model.entity.Job; 4 | import yourwebproject2.service.JobService; 5 | import org.slf4j.Logger; 6 | 7 | import java.util.Map; 8 | import java.util.concurrent.Future; 9 | 10 | /** 11 | * @author: kameshr 12 | */ 13 | public abstract class AbstractJobSchedulingWorker { 14 | void processResults(Map, Job> result, JobService jobService, Logger LOG) { 15 | for(Future jobFuture : result.keySet()) { 16 | try { 17 | Job resultJob = jobFuture.get(); 18 | LOG.info("Job Status: name="+resultJob.getName()+" status="+resultJob.getStatus()); 19 | jobService.update(jobFuture.get()); 20 | } catch (Exception e) { 21 | e.printStackTrace(); 22 | Job failedJob = result.get(jobFuture); 23 | failedJob.setStatus(Job.Status.FAILED); 24 | try { 25 | jobService.update(failedJob); 26 | } catch (Exception e1) { 27 | e1.printStackTrace(); 28 | } 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/JobExecutionThread.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | import yourwebproject2.model.entity.Job; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.util.Date; 8 | import java.util.concurrent.Callable; 9 | 10 | /** 11 | * Created by Y.Kamesh on 8/2/2015. 12 | */ 13 | public class JobExecutionThread implements Callable { 14 | private static Logger LOG = LoggerFactory.getLogger(JobExecutionThread.class); 15 | private Job job; 16 | 17 | public JobExecutionThread(Job jobInfo) { 18 | job = jobInfo; 19 | } 20 | 21 | @Override 22 | public Job call() throws Exception { 23 | LOG.info("Executing the Job: "+job.getName()); 24 | Thread.sleep(10); 25 | LOG.info("Finished executing the Job: "+job.getName()); 26 | job.setCompletionTime(new Date(System.currentTimeMillis())); 27 | job.setStatus(Job.Status.SUCCESSFUL); 28 | return job; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/MailSendingTask.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | /** 4 | * @author: kameshr 5 | */ 6 | public class MailSendingTask { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | import yourwebproject2.model.entity.Job; 4 | import yourwebproject2.model.entity.helper.CategoryPriorityComparator; 5 | import yourwebproject2.service.JobService; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.scheduling.annotation.Scheduled; 10 | 11 | import java.util.*; 12 | import java.util.concurrent.ExecutorService; 13 | import java.util.concurrent.Executors; 14 | import java.util.concurrent.Future; 15 | 16 | /** 17 | * Created by Y.Kamesh on 8/5/2015. 18 | */ 19 | public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { 20 | private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); 21 | 22 | @Autowired 23 | private JobService jobService; 24 | 25 | private ExecutorService executorService = Executors.newFixedThreadPool(50); 26 | 27 | /** 28 | * Runs every five minutes. 29 | */ 30 | @Scheduled(initialDelay = 5000L, fixedRate = 5 * 60 * 1000L) 31 | public void scheduleNewJobsForExecution() { 32 | LOG.info("Fetching new jobs as per category and submit time priority..."); 33 | List newJobs = jobService.fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); 34 | LOG.info("Fetched Jobs Count: "+newJobs.size()); 35 | Collections.sort(newJobs, new CategoryPriorityComparator()); 36 | 37 | Map, Job> result = new LinkedHashMap<>(); 38 | for(Job newJob : newJobs) { 39 | try { 40 | LOG.info("Scheduling Job: name="+newJob.getName()+", priority="+newJob.getCategory().getPriority() 41 | +", submitTime="+newJob.getSubmitTime()); 42 | newJob.setScheduledTime(new Date(System.currentTimeMillis())); 43 | newJob.setStatus(Job.Status.PRIORITIZED); 44 | jobService.update(newJob); 45 | result.put(executorService.submit(new JobExecutionThread(newJob)), newJob); 46 | LOG.info("Scheduled Job: name="+newJob.getName()+", priority="+newJob.getCategory().getPriority() 47 | +", scheduledTime="+newJob.getScheduledTime()); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | LOG.info("Done scheduling the jobs"); 53 | LOG.info("Waiting on results of the jobs"); 54 | 55 | LOG.info("Fetching results of the jobs"); 56 | 57 | processResults(result, jobService, LOG); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | import yourwebproject2.model.entity.Job; 4 | import yourwebproject2.model.entity.helper.CategoryPriorityComparator; 5 | import yourwebproject2.service.JobService; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.scheduling.annotation.Scheduled; 10 | 11 | import java.util.*; 12 | import java.util.concurrent.ExecutorService; 13 | import java.util.concurrent.Executors; 14 | import java.util.concurrent.Future; 15 | 16 | /** 17 | * Created by Y.Kamesh on 8/5/2015. 18 | */ 19 | public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { 20 | private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); 21 | 22 | @Autowired 23 | private JobService jobService; 24 | 25 | private ExecutorService executorService = Executors.newFixedThreadPool(50); 26 | 27 | /** 28 | * Runs every fifteen minutes. 29 | */ 30 | @Scheduled(initialDelay = 5000L, fixedRate = 15 * 60 * 1000L) 31 | public void scheduleRetryJobsForExecution() { 32 | LOG.info("Fetching failed jobs as per category and submit time priority..."); 33 | List retryableJobs = jobService.fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); 34 | LOG.info("Fetched Jobs Count: "+retryableJobs.size()); 35 | Collections.sort(retryableJobs, new CategoryPriorityComparator()); 36 | 37 | Map, Job> result = new LinkedHashMap<>(); 38 | for(Job retryableJob : retryableJobs) { 39 | try { 40 | LOG.info("Scheduling Job: name="+retryableJob.getName()); 41 | retryableJob.setScheduledTime(new Date(System.currentTimeMillis())); 42 | retryableJob.setRetryCount(retryableJob.getRetryCount()+1); 43 | retryableJob.setStatus(Job.Status.RETRYING); 44 | jobService.update(retryableJob); 45 | result.put(executorService.submit(new JobExecutionThread(retryableJob)), retryableJob); 46 | } catch (Exception e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | LOG.info("Done scheduling the job retrials"); 51 | LOG.info("Waiting on results of the job retrials"); 52 | 53 | LOG.info("Fetching results of the jobs"); 54 | 55 | processResults(result, jobService, LOG); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/YourWebProjectJobCoreDaemon.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.support.ClassPathXmlApplicationContext; 7 | 8 | /** 9 | * Main class to run job execution logic in a demon mode 10 | * 11 | * Created by Y.Kamesh on 8/8/2015. 12 | */ 13 | public class YourWebProjectJobCoreDaemon { 14 | private static Logger LOG = LoggerFactory.getLogger(YourWebProjectJobCoreDaemon.class); 15 | public static void main(String[] args) { 16 | LOG.info("Starting the Job scheduling and execution daemon."); 17 | ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", 18 | "classpath:/config/spring/appContext-repository.xml", 19 | "classpath:/config/spring/appContext-service.xml", 20 | "classpath:/config/spring/appContext-scheduler.xml"}, true); 21 | LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames()); 22 | LOG.info("Job scheduling and execution daemon started."); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/tool/AdminUserTool.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core.tool; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.support.ClassPathXmlApplicationContext; 7 | 8 | /** 9 | * @author: kameshr 10 | */ 11 | public class AdminUserTool { 12 | private static Logger LOG = LoggerFactory.getLogger(AdminUserTool.class); 13 | public static void main(String[] args) { 14 | LOG.info("Starting the Job scheduling and execution daemon."); 15 | ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", 16 | "classpath:/config/spring/appContext-repository.xml", 17 | "classpath:/config/spring/appContext-service.xml", 18 | "classpath:/config/spring/appContext-interceptor.xml"}, true); 19 | LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames()); 20 | LOG.info("Job scheduling and execution daemon started."); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/core/tool/CategoryTool.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.core.tool; 2 | 3 | import yourwebproject2.model.entity.Category; 4 | import yourwebproject2.service.CategoryService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.support.ClassPathXmlApplicationContext; 9 | 10 | import java.util.HashMap; 11 | 12 | /** 13 | * @author: kameshr 14 | */ 15 | public class CategoryTool { 16 | private static Logger LOG = LoggerFactory.getLogger(CategoryTool.class); 17 | public static void main(String[] args) throws Exception { 18 | LOG.info("Category Creation Tool"); 19 | 20 | if(args==null || args.length < 2) { 21 | printUsage(); 22 | } 23 | 24 | HashMap params = new HashMap<>(); 25 | for(String arg: args) { 26 | String[] p = arg.split("="); 27 | if(p == null) { 28 | continue; 29 | } 30 | 31 | switch(p[0].toLowerCase()) { 32 | case "name": 33 | params.put("name", p[1]); 34 | break; 35 | case "priority": 36 | params.put("priority", p[1]); 37 | break; 38 | case "parent": 39 | params.put("parent", p[1]); 40 | break; 41 | } 42 | } 43 | 44 | Integer priority = null; 45 | if(params.containsKey("name") && (params.containsKey("priority") || params.containsKey("parent"))) { 46 | if(params.containsKey("priority")) { 47 | try { 48 | priority = Integer.parseInt(params.get("priority")); 49 | } catch (NumberFormatException nfe) { 50 | System.out.println("Priority not a number"); 51 | System.exit(1); 52 | } 53 | } 54 | } else { 55 | printUsage(); 56 | } 57 | 58 | LOG.info("Params: "+params); 59 | System.out.println("Params: "+params); 60 | 61 | ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", 62 | "classpath:/config/spring/appContext-repository.xml", 63 | "classpath:/config/spring/appContext-service.xml", 64 | "classpath:/config/spring/appContext-interceptor.xml"}, true); 65 | LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames()); 66 | 67 | CategoryService categoryService = (CategoryService) ctx.getBean("categoryServiceImpl"); 68 | 69 | if(categoryService.isCategoryPresent(params.get("name"))) { 70 | System.out.println("Category taken"); 71 | System.exit(1); 72 | } 73 | 74 | Category parentCategory = null; 75 | if(params.containsKey("parent")) { 76 | parentCategory = categoryService.findByCategoryName(params.get("parent")); 77 | } 78 | 79 | if(parentCategory != null && priority != null) { 80 | if(parentCategory.getPriority() != priority) { 81 | System.out.println("Sub-Category has to take same priority as parent"); 82 | System.exit(1); 83 | } 84 | } 85 | 86 | if(categoryService.isPriorityPresent(priority)) { 87 | System.out.println("Priority taken"); 88 | System.exit(1); 89 | } 90 | 91 | Category category = new Category(); 92 | category.setName(params.get("name")); 93 | category.setPriority(priority); 94 | if(parentCategory != null) { 95 | category.setPriority(parentCategory.getPriority()); 96 | category.setParentCategory(parentCategory); 97 | } 98 | 99 | categoryService.insert(category); 100 | 101 | LOG.info("Category Successfully Created"); 102 | } 103 | 104 | public static void printUsage() { 105 | System.out.println("java CategoryTool name= priority= parent="); 106 | System.exit(1); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/api/APIResponse.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.api; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import org.springframework.web.servlet.ModelAndView; 5 | 6 | /** 7 | * Created by Y.Kamesh on 8/2/2015. 8 | */ 9 | @JsonInclude(JsonInclude.Include.NON_NULL) 10 | public class APIResponse { 11 | public static final String API_RESPONSE = "apiResponse"; 12 | Object result; 13 | String time; 14 | long code; 15 | 16 | public static class ExceptionAPIResponse extends APIResponse { 17 | Object details; 18 | 19 | public Object getDetails() { 20 | return details; 21 | } 22 | 23 | public void setDetails(Object details) { 24 | this.details = details; 25 | } 26 | } 27 | 28 | public Object getResult() { 29 | return result; 30 | } 31 | 32 | public void setResult(Object result) { 33 | this.result = result; 34 | } 35 | 36 | public String getTime() { 37 | return time; 38 | } 39 | 40 | public void setTime(String time) { 41 | this.time = time; 42 | } 43 | 44 | public long getCode() { 45 | return code; 46 | } 47 | 48 | public void setCode(long code) { 49 | this.code = code; 50 | } 51 | 52 | public static APIResponse toOkResponse(Object data) { 53 | return toAPIResponse(data, 200); 54 | } 55 | 56 | public static APIResponse toErrorResponse(Object data) { 57 | return toAPIResponse(data, 2001); 58 | } 59 | 60 | public static ExceptionAPIResponse toExceptionResponse(String result, Object details) { 61 | ExceptionAPIResponse response = new ExceptionAPIResponse(); 62 | response.setResult(result); 63 | response.setDetails(details); 64 | response.setCode(2001); 65 | return response; 66 | } 67 | 68 | public APIResponse withModelAndView(ModelAndView modelAndView) { 69 | modelAndView.addObject(API_RESPONSE, this); 70 | return this; 71 | } 72 | 73 | public static APIResponse toAPIResponse(Object data, long code) { 74 | APIResponse response = new APIResponse(); 75 | response.setResult(data); 76 | response.setCode(code); 77 | return response; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.controller; 2 | 3 | import yourwebproject2.model.dto.UserDTO; 4 | import org.apache.commons.lang.Validate; 5 | import org.json.JSONObject; 6 | import org.springframework.security.crypto.codec.Base64; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.io.IOException; 10 | import java.util.Scanner; 11 | 12 | /** 13 | * All controllers in spring should extend this controller so as to have 14 | * centralize control for doing any sort of common functionality. 15 | * e.g. extracting data from post request body 16 | * 17 | * @author : Y Kamesh Rao 18 | */ 19 | public abstract class BaseController { 20 | protected static final String JSON_API_CONTENT_HEADER = "Content-type=application/json"; 21 | 22 | public String extractPostRequestBody(HttpServletRequest request) throws IOException { 23 | if ("POST".equalsIgnoreCase(request.getMethod())) { 24 | Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A"); 25 | return s.hasNext() ? s.next() : ""; 26 | } 27 | return ""; 28 | } 29 | 30 | public JSONObject parseJSON(String object) { 31 | return new JSONObject(object); 32 | } 33 | 34 | public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) { 35 | String[] basicAuth = authHeader.split(" "); 36 | Validate.isTrue(basicAuth.length == 2, "the auth header is not splittable with space"); 37 | Validate.isTrue(basicAuth[0].equalsIgnoreCase("basic"), "not basic auth: "+basicAuth[0]); 38 | Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), "encoded value not base64"); 39 | 40 | String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes())); 41 | String[] creds = decodedAuthHeader.split(":"); 42 | Validate.isTrue(creds.length == 2, "the creds were not concatenated using ':', could not split the decoded header"); 43 | 44 | userDTO.setEmail(creds[0]); 45 | userDTO.setPassword(creds[1]); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/BaseHibernateJPARepository.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | import org.hibernate.Criteria; 4 | import org.hibernate.FlushMode; 5 | import org.hibernate.SessionFactory; 6 | import org.hibernate.criterion.Order; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import java.io.Serializable; 11 | import java.util.Collection; 12 | 13 | /** 14 | * Generic CRUD Repository class functionality with Hibernate Session Factory 15 | * 16 | * Created by Y.Kamesh on 8/2/2015. 17 | */ 18 | public abstract class BaseHibernateJPARepository implements BaseJPARepository { 19 | protected @Autowired 20 | SessionFactory sessionFactory; 21 | protected Class clazz; 22 | 23 | 24 | @SuppressWarnings("unchecked") 25 | public void setupEntityClass(Class clazz) { 26 | this.clazz = clazz; 27 | } 28 | 29 | 30 | public void delete(T object) { 31 | sessionFactory.getCurrentSession().delete(object); 32 | } 33 | 34 | 35 | @Transactional 36 | public T insert(T object) { 37 | sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO); 38 | sessionFactory.getCurrentSession().save(object); 39 | sessionFactory.getCurrentSession().flush(); 40 | return object; 41 | } 42 | 43 | 44 | @Transactional 45 | public T update(T object) { 46 | sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO); 47 | sessionFactory.getCurrentSession().update(object); 48 | sessionFactory.getCurrentSession().flush(); 49 | return object; 50 | } 51 | 52 | 53 | @Transactional 54 | public T insertOrUpdate(T object) { 55 | sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO); 56 | sessionFactory.getCurrentSession().saveOrUpdate(object); 57 | sessionFactory.getCurrentSession().flush(); 58 | return object; 59 | } 60 | 61 | 62 | @Transactional(readOnly = true) 63 | public T findById(ID id) { 64 | return (T) sessionFactory.getCurrentSession().get(clazz, id); 65 | } 66 | 67 | 68 | public Collection findAllByPage(int pageNum, int countPerPage, Order order) { 69 | Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz); 70 | c.setMaxResults(countPerPage); 71 | c.setFirstResult(pageNum * countPerPage); 72 | return c.list(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/BaseJPARepository.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | import org.hibernate.criterion.Order; 4 | 5 | import java.io.Serializable; 6 | import java.util.Collection; 7 | 8 | /** 9 | * Generic JPA Repository protocol with common CRUD operations and some specific find operations 10 | * 11 | * Created by Y.Kamesh on 8/2/2015. 12 | */ 13 | public interface BaseJPARepository { 14 | /** 15 | * Method to setup the class type of the Entity for which 16 | * the DAO works 17 | * 18 | * @param clazz 19 | */ 20 | public void setupEntityClass(Class clazz); 21 | 22 | /** 23 | * Method to insert the new row into config.database table 24 | * 25 | * @param object 26 | * The object entity to be persisted 27 | */ 28 | public T insert(T object); 29 | 30 | /** 31 | * Method to update an existing row in the config.database table 32 | * 33 | * @param object 34 | * The object entity to be updated 35 | */ 36 | public T update(T object); 37 | 38 | /** 39 | * Method to insert a new row or update a row if it was 40 | * already existing in the system. 41 | * 42 | * @param object 43 | * The object entity to be updated 44 | */ 45 | public T insertOrUpdate(T object); 46 | 47 | /** 48 | * Method to delete an existing row in the config.database table 49 | * 50 | * @param object 51 | * The object entity to be deleted 52 | */ 53 | public void delete(T object); 54 | 55 | /** 56 | * Method to find a database item by id 57 | * 58 | * @param id 59 | * The id by which the row has to be found 60 | */ 61 | public T findById(ID id); 62 | 63 | /** 64 | * Method to find a collection of database entities by pages 65 | * 66 | * @param pageNum 67 | * @param countPerPage 68 | * @param order 69 | * 70 | * @return 71 | * 72 | * @throws Exception 73 | */ 74 | public Collection findAllByPage(int pageNum, int countPerPage, Order order); 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | import org.hibernate.criterion.Order; 4 | 5 | import java.io.Serializable; 6 | import java.util.Collection; 7 | 8 | /** 9 | * BaseService implementation for basic access to service 10 | * methods of CRUD operations on entity 11 | * 12 | * @author : Y Kamesh Rao 13 | */ 14 | public abstract class BaseJPAServiceImpl implements BaseService { 15 | protected BaseJPARepository baseJpaRepository; 16 | protected Class entityClass; 17 | 18 | public T insert(T object) throws Exception { 19 | return baseJpaRepository.insert(object); 20 | } 21 | 22 | public T update(T object) throws Exception { 23 | return baseJpaRepository.update(object); 24 | } 25 | 26 | public void delete(T object) throws Exception { 27 | baseJpaRepository.delete(object); 28 | } 29 | 30 | public T findById(ID id) throws Exception { 31 | T result = baseJpaRepository.findById(id); 32 | 33 | if (result != null) 34 | return result; 35 | else 36 | throw new Exception("Not Found"); 37 | } 38 | 39 | public Collection findAllByPage(int pageNum, int countPerPage, Order order) throws Exception { 40 | return null; //To change body of implemented methods use File | Settings | File Templates. 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/BaseService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | import org.hibernate.criterion.Order; 4 | 5 | import java.io.Serializable; 6 | import java.util.Collection; 7 | 8 | /** 9 | * Interface listing the most basic services required to be present in any 10 | * service built upon an domain entity object that is persisted using repository. 11 | * 12 | * @author : Y Kamesh Rao 13 | */ 14 | public interface BaseService { 15 | /** 16 | * Method to setup the service with basic 17 | * required data. Called after Spring initialization. 18 | */ 19 | public void setupService(); 20 | 21 | /** 22 | * Service to insert the new object 23 | * 24 | * @param object 25 | * The newly object 26 | */ 27 | public T insert(T object) throws Exception; 28 | 29 | /** 30 | * Service to update an existing object 31 | * 32 | * @param object 33 | * The existing object 34 | */ 35 | public T update(T object) throws Exception; 36 | 37 | /** 38 | * Service to delete an existing object 39 | * 40 | * @param object 41 | * The existing object 42 | */ 43 | public void delete(T object) throws Exception; 44 | 45 | /** 46 | * Service to find an existing object by its given id and query name 47 | * 48 | * @param id 49 | * Id of the resource 50 | */ 51 | public T findById(ID id) throws Exception; 52 | 53 | 54 | /** 55 | * Service to find a collection of entities by pages 56 | * 57 | * @param pageNum 58 | * @param countPerPage 59 | * @param order 60 | * 61 | * @return 62 | * 63 | * @throws Exception 64 | */ 65 | public Collection findAllByPage(int pageNum, int countPerPage, Order order) throws Exception; 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/Entity.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | /** 4 | * Proxy interface for all the concrete 5 | * entities to extend from. 6 | * 7 | * @author : Y Kamesh Rao 8 | */ 9 | public interface Entity { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/data/JPAEntity.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.data; 2 | 3 | import org.codehaus.jackson.annotate.JsonIgnore; 4 | 5 | import javax.persistence.*; 6 | import javax.xml.bind.annotation.XmlElement; 7 | import java.io.Serializable; 8 | import java.util.Date; 9 | 10 | /** 11 | * JPAEntity to declare fields to be in each entity table like id 12 | * and creational timestamps 13 | * 14 | * @author : Y Kamesh Rao 15 | */ 16 | @MappedSuperclass 17 | public abstract class JPAEntity implements Entity { 18 | protected T id; 19 | protected Date createdAt; 20 | protected Date updatedAt; 21 | 22 | 23 | public JPAEntity() { 24 | createdAt = new Date(); 25 | updatedAt = new Date(); 26 | } 27 | 28 | 29 | /** 30 | * To make XStream deserialization assign values to 31 | * base class fields of createdAt and updatedAt 32 | * 33 | * @return 34 | */ 35 | public Object readResolve() { 36 | if (this.createdAt == null) { 37 | this.createdAt = new Date(); 38 | this.updatedAt = createdAt; 39 | } 40 | 41 | return this; 42 | } 43 | 44 | 45 | @XmlElement(type = Object.class) @Id @GeneratedValue 46 | public T getId() { 47 | return id; 48 | } 49 | 50 | 51 | public void setId(T id) { 52 | this.id = id; 53 | } 54 | 55 | 56 | @JsonIgnore @Temporal(TemporalType.DATE) @Column 57 | public Date getCreatedAt() { 58 | return createdAt; 59 | } 60 | 61 | 62 | public void setCreatedAt(Date createdAt) { 63 | this.createdAt = createdAt; 64 | } 65 | 66 | 67 | @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column 68 | public Date getUpdatedAt() { 69 | return updatedAt; 70 | } 71 | 72 | 73 | public void setUpdatedAt(Date updatedAt) { 74 | this.updatedAt = updatedAt; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.exception; 2 | 3 | 4 | import org.springframework.security.core.AuthenticationException; 5 | 6 | /** 7 | * @author: kameshr 8 | */ 9 | public class EmailNotFoundException extends AuthenticationException { 10 | public EmailNotFoundException(String message) { 11 | super(message); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/exception/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.exception; 2 | 3 | /** 4 | * @author: kameshr 5 | */ 6 | public class NotFoundException extends Exception { 7 | public NotFoundException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/framework/servlet/BaseDispatcherServlet.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.framework.servlet; 2 | 3 | import org.springframework.web.servlet.DispatcherServlet; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | import java.io.IOException; 9 | 10 | /** 11 | * @author: Kamesh Rao Yeduvakula 12 | * @date: 8/02/2015 13 | */ 14 | public class BaseDispatcherServlet extends DispatcherServlet { 15 | 16 | private static final long serialVersionUID = 112233448L; 17 | 18 | 19 | @Override 20 | protected void doService(final HttpServletRequest request, final HttpServletResponse response) throws Exception { 21 | super.doService(request, response); 22 | } 23 | 24 | 25 | @Override 26 | protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception { 27 | super.doDispatch(request, response); 28 | } 29 | 30 | 31 | @Override 32 | protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, 33 | IOException { 34 | super.service(request, response); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/interceptor/WebAppExceptionAdvice.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.interceptor; 2 | 3 | import yourwebproject2.framework.api.APIResponse; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.web.bind.annotation.ControllerAdvice; 7 | import org.springframework.web.bind.annotation.ExceptionHandler; 8 | import org.springframework.web.bind.annotation.ResponseBody; 9 | 10 | /** 11 | * Exception Handler Controller Advice to catch all controller exceptions and respond gracefully to 12 | * the caller 13 | * 14 | * Created by Y.Kamesh on 8/2/2015. 15 | */ 16 | @ControllerAdvice 17 | public class WebAppExceptionAdvice { 18 | private static Logger LOG = LoggerFactory.getLogger(WebAppExceptionAdvice.class); 19 | 20 | @ExceptionHandler(Exception.class) 21 | @ResponseBody 22 | public APIResponse handleAnyException(Exception e) { 23 | LOG.error(e.getMessage()); 24 | e.printStackTrace(); 25 | return APIResponse.toErrorResponse(e.getMessage()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/interceptor/WebAppMetricsInterceptor.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.interceptor; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.servlet.ModelAndView; 6 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | /** 12 | * An MVC interceptor to collect metrics like processing time of a controller action handler 13 | * 14 | * Created by Y.Kamesh on 8/2/2015. 15 | */ 16 | public class WebAppMetricsInterceptor extends HandlerInterceptorAdapter { 17 | private static Logger LOG = LoggerFactory.getLogger(WebAppMetricsInterceptor.class); 18 | private long startTime = 0L; 19 | 20 | @Override 21 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 22 | LOG.info("processing: " + request.getRequestURI() + " Handler: " + handler.toString()); 23 | startTime = System.currentTimeMillis(); 24 | return super.preHandle(request, response, handler); 25 | } 26 | 27 | @Override 28 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 29 | super.postHandle(request, response, handler, modelAndView); 30 | LOG.info("processed: " + request.getRequestURI() + " Handler: " + handler.toString()); 31 | long responseTime = System.currentTimeMillis() - startTime; 32 | LOG.info(String.format("responseTime: %d ms", responseTime)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/dto/CategoryDTO.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.dto; 2 | 3 | /** 4 | * 5 | * {"name":"cat1", "priority":2, "parent":"pCat"} 6 | * 7 | * @author: kameshr 8 | */ 9 | public class CategoryDTO { 10 | String name; 11 | Integer priority; 12 | String parent; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public Integer getPriority() { 23 | return priority; 24 | } 25 | 26 | public void setPriority(Integer priority) { 27 | this.priority = priority; 28 | } 29 | 30 | public String getParent() { 31 | return parent; 32 | } 33 | 34 | public void setParent(String parent) { 35 | this.parent = parent; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "CategoryDTO{" + 41 | "name='" + name + '\'' + 42 | ", priority=" + priority + 43 | ", parent='" + parent + '\'' + 44 | '}'; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/dto/JobDTO.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.dto; 2 | 3 | /** 4 | * {"name":"job1", "metadataJsonString":"{}", "callbackUrl":"", "catId":1} 5 | * 6 | * @author: kameshr 7 | */ 8 | public class JobDTO { 9 | String name; 10 | String metadataJsonString; 11 | String callbackURL; 12 | Long catId; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public String getMetadataJsonString() { 23 | return metadataJsonString; 24 | } 25 | 26 | public void setMetadataJsonString(String metadataJsonString) { 27 | this.metadataJsonString = metadataJsonString; 28 | } 29 | 30 | public Long getCatId() { 31 | return catId; 32 | } 33 | 34 | public void setCatId(Long catId) { 35 | this.catId = catId; 36 | } 37 | 38 | public String getCallbackURL() { 39 | return callbackURL; 40 | } 41 | 42 | public void setCallbackURL(String callbackURL) { 43 | this.callbackURL = callbackURL; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return "JobDTO{" + 49 | "name='" + name + '\'' + 50 | ", metadataJsonString='" + metadataJsonString + '\'' + 51 | ", catId=" + catId + 52 | ", callbackURL='" + callbackURL + '\'' + 53 | '}'; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.dto; 2 | 3 | /** 4 | * @author: kameshr 5 | */ 6 | public class UserDTO { 7 | String email; 8 | String password; 9 | String displayName; 10 | String encryptedPassword; 11 | String iv; 12 | String salt; 13 | int keySize; 14 | int iterations; 15 | 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | public String getPassword() { 25 | return password; 26 | } 27 | 28 | public void setPassword(String password) { 29 | this.password = password; 30 | } 31 | 32 | public String getDisplayName() { 33 | return displayName; 34 | } 35 | 36 | public void setDisplayName(String displayName) { 37 | this.displayName = displayName; 38 | } 39 | 40 | public String getEncryptedPassword() { 41 | return encryptedPassword; 42 | } 43 | 44 | public void setEncryptedPassword(String encryptedPassword) { 45 | this.encryptedPassword = encryptedPassword; 46 | } 47 | 48 | public String getIv() { 49 | return iv; 50 | } 51 | 52 | public void setIv(String iv) { 53 | this.iv = iv; 54 | } 55 | 56 | public String getSalt() { 57 | return salt; 58 | } 59 | 60 | public void setSalt(String salt) { 61 | this.salt = salt; 62 | } 63 | 64 | public int getKeySize() { 65 | return keySize; 66 | } 67 | 68 | public void setKeySize(int keySize) { 69 | this.keySize = keySize; 70 | } 71 | 72 | public int getIterations() { 73 | return iterations; 74 | } 75 | 76 | public void setIterations(int iterations) { 77 | this.iterations = iterations; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/entity/Category.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.entity; 2 | 3 | import yourwebproject2.framework.data.JPAEntity; 4 | import org.hibernate.validator.constraints.NotBlank; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.NotNull; 8 | 9 | /** 10 | * Category Entity 11 | * 12 | * Created by Y.Kamesh on 8/2/2015. 13 | */ 14 | @Entity 15 | @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), 16 | @Index(name="priority_idx", columnList = "priority"), 17 | @Index(name="parentCategory_idx", columnList = "parent_category")}) 18 | public class Category extends JPAEntity { 19 | private String name; 20 | private Integer priority; 21 | private Category parentCategory; 22 | 23 | @NotNull @NotBlank 24 | @Column 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | @NotNull 34 | @Column 35 | public Integer getPriority() { 36 | return priority; 37 | } 38 | 39 | public void setPriority(Integer priority) { 40 | this.priority = priority; 41 | } 42 | 43 | @ManyToOne(fetch = FetchType.EAGER) 44 | public Category getParentCategory() { 45 | return parentCategory; 46 | } 47 | 48 | public void setParentCategory(Category parentCategory) { 49 | this.parentCategory = parentCategory; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "Category{" + 55 | "name='" + name + '\'' + 56 | ", priority=" + priority + 57 | ", parentCategory=" + parentCategory + 58 | '}'; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/entity/Job.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.entity; 2 | 3 | import yourwebproject2.framework.data.JPAEntity; 4 | import org.hibernate.validator.constraints.NotBlank; 5 | 6 | import javax.persistence.*; 7 | import javax.validation.constraints.NotNull; 8 | import java.util.Date; 9 | 10 | /** 11 | * The core Job Entity 12 | * 13 | * Created by Y.Kamesh on 8/2/2015. 14 | */ 15 | @Entity 16 | @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), 17 | @Index(name="status_idx", columnList = "status"), 18 | @Index(name="category_idx", columnList = "category")}) 19 | public class Job extends JPAEntity { 20 | public enum Status { 21 | NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL 22 | } 23 | 24 | private String name; 25 | private String metadataJson; 26 | private String callbackUrl; 27 | private Date submitTime; 28 | private Status status; 29 | private Date scheduledTime; 30 | private Date completionTime; 31 | private Integer retryCount; 32 | private Category category; 33 | 34 | @NotNull @NotBlank 35 | @Column 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | @Column 45 | public String getCallbackUrl() { 46 | return callbackUrl; 47 | } 48 | 49 | public void setCallbackUrl(String callbackUrl) { 50 | this.callbackUrl = callbackUrl; 51 | } 52 | 53 | @Column 54 | public String getMetadataJson() { 55 | return metadataJson; 56 | } 57 | 58 | public void setMetadataJson(String metadataJson) { 59 | this.metadataJson = metadataJson; 60 | } 61 | 62 | @NotNull 63 | @Column 64 | public Date getSubmitTime() { 65 | return submitTime; 66 | } 67 | 68 | public void setSubmitTime(Date submitTime) { 69 | this.submitTime = submitTime; 70 | } 71 | 72 | @OneToOne(fetch = FetchType.EAGER) 73 | public Category getCategory() { 74 | return category; 75 | } 76 | 77 | public void setCategory(Category category) { 78 | this.category = category; 79 | } 80 | 81 | @NotNull 82 | @Column 83 | public Status getStatus() { 84 | return status; 85 | } 86 | 87 | public void setStatus(Status status) { 88 | this.status = status; 89 | } 90 | 91 | @Column 92 | public Date getScheduledTime() { 93 | return scheduledTime; 94 | } 95 | 96 | public void setScheduledTime(Date scheduledTime) { 97 | this.scheduledTime = scheduledTime; 98 | } 99 | 100 | @Column 101 | public Date getCompletionTime() { 102 | return completionTime; 103 | } 104 | 105 | public void setCompletionTime(Date completionTime) { 106 | this.completionTime = completionTime; 107 | } 108 | 109 | @Column 110 | public Integer getRetryCount() { 111 | return retryCount; 112 | } 113 | 114 | public void setRetryCount(Integer retryCount) { 115 | this.retryCount = retryCount; 116 | } 117 | 118 | @Override 119 | public String toString() { 120 | return "Job{" + 121 | "name='" + name + '\'' + 122 | ", metadataJson='" + metadataJson + '\'' + 123 | ", callbackUrl='" + callbackUrl + '\'' + 124 | ", submitTime=" + submitTime + 125 | ", status=" + status + 126 | ", scheduledTime=" + scheduledTime + 127 | ", completionTime=" + completionTime + 128 | ", retryCount=" + retryCount + 129 | ", category=" + category + 130 | '}'; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/entity/MailerJob.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.entity; 2 | 3 | /** 4 | * @author: kameshr 5 | */ 6 | public class MailerJob extends Job { 7 | enum MailType { 8 | CONFIRMATION, PASSWORD_RESET 9 | } 10 | 11 | public static MailerJob buildMailerJobForUser(User user, MailType mailType) { 12 | MailerJob mailerJob = new MailerJob(); 13 | //mailerJob.set 14 | return mailerJob; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/entity/User.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import yourwebproject2.framework.data.JPAEntity; 5 | import org.hibernate.validator.constraints.Email; 6 | import org.hibernate.validator.constraints.NotBlank; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | 9 | import javax.persistence.*; 10 | import javax.validation.constraints.NotNull; 11 | import java.io.Serializable; 12 | import java.util.Date; 13 | 14 | 15 | /** 16 | * Created by Y.Kamesh on 10/9/2015. 17 | */ 18 | @Entity 19 | @Inheritance(strategy = InheritanceType.SINGLE_TABLE) 20 | @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true), 21 | @Index(name="displayName_idx", columnList = "display_name") }) 22 | public class User extends JPAEntity implements Serializable { 23 | public enum Role { 24 | USER, 25 | ADMIN 26 | } 27 | 28 | private String email; 29 | private @JsonIgnore String password; 30 | private boolean enabled; 31 | private Role role; 32 | private String displayName; 33 | 34 | private @JsonIgnore Integer loginCount; 35 | private Date currentLoginAt; 36 | private Date lastLoginAt; 37 | private @JsonIgnore String currentLoginIp; 38 | private @JsonIgnore String lastLoginIp; 39 | 40 | private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 41 | 42 | @Column @Email @NotNull @NotBlank 43 | public String getEmail() { 44 | return this.email; 45 | } 46 | 47 | public void setEmail(String email) { 48 | this.email = email; 49 | } 50 | 51 | @JsonIgnore @Column(nullable = false, length = 60) 52 | public String getPassword() { 53 | return this.password; 54 | } 55 | 56 | public void setPassword(String password) { 57 | this.password = password; 58 | } 59 | 60 | @Column(nullable = false) 61 | public boolean isEnabled() { 62 | return this.enabled; 63 | } 64 | 65 | public void setEnabled(boolean enabled) { 66 | this.enabled = enabled; 67 | } 68 | 69 | @Column(nullable = false) 70 | public Role getRole() { 71 | return this.role; 72 | } 73 | 74 | public void setRole(Role role) { 75 | this.role = role; 76 | } 77 | 78 | @Column(name="display_name") 79 | public String getDisplayName() { 80 | return displayName; 81 | } 82 | 83 | public void setDisplayName(String displayName) { 84 | this.displayName = displayName; 85 | } 86 | 87 | @JsonIgnore @Column 88 | public Integer getLoginCount() { 89 | return loginCount; 90 | } 91 | 92 | public void setLoginCount(Integer loginCount) { 93 | this.loginCount = loginCount; 94 | } 95 | 96 | @Column 97 | public Date getCurrentLoginAt() { 98 | return currentLoginAt; 99 | } 100 | 101 | public void setCurrentLoginAt(Date currentLoginAt) { 102 | this.currentLoginAt = currentLoginAt; 103 | } 104 | 105 | @Column 106 | public Date getLastLoginAt() { 107 | return lastLoginAt; 108 | } 109 | 110 | public void setLastLoginAt(Date lastLoginAt) { 111 | this.lastLoginAt = lastLoginAt; 112 | } 113 | 114 | @JsonIgnore @Column 115 | public String getCurrentLoginIp() { 116 | return currentLoginIp; 117 | } 118 | 119 | public void setCurrentLoginIp(String currentLoginIp) { 120 | this.currentLoginIp = currentLoginIp; 121 | } 122 | 123 | @JsonIgnore @Column 124 | public String getLastLoginIp() { 125 | return lastLoginIp; 126 | } 127 | 128 | public void setLastLoginIp(String lastLoginIp) { 129 | this.lastLoginIp = lastLoginIp; 130 | } 131 | 132 | /** 133 | * Method to create the hash of the password before storing 134 | * 135 | * @param pass 136 | * 137 | * @return SHA hash digest of the password 138 | */ 139 | public static synchronized String hashPassword(String pass) { 140 | return passwordEncoder.encode(pass); 141 | } 142 | 143 | public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) { 144 | return passwordEncoder.matches(rawPass, encodedPass); 145 | } 146 | 147 | @Override 148 | public String toString() { 149 | return "User{" + 150 | "email='" + email + '\'' + 151 | ", password='" + password + '\'' + 152 | ", enabled=" + enabled + 153 | ", role=" + role + 154 | ", displayName='" + displayName + '\'' + 155 | ", loginCount=" + loginCount + 156 | ", currentLoginAt=" + currentLoginAt + 157 | ", lastLoginAt=" + lastLoginAt + 158 | ", currentLoginIp='" + currentLoginIp + '\'' + 159 | ", lastLoginIp='" + lastLoginIp + '\'' + 160 | '}'; 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.entity.helper; 2 | 3 | import yourwebproject2.model.entity.Job; 4 | 5 | import java.util.Comparator; 6 | 7 | /** 8 | * Created by Y.Kamesh on 8/8/2015. 9 | */ 10 | public class CategoryPriorityComparator implements Comparator { 11 | 12 | /** 13 | * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as 14 | * the first argument is less than, equal to, or greater than the second. 15 | * 16 | * @param o1 17 | * @param o2 18 | * @return 19 | */ 20 | @Override 21 | public int compare(Job o1, Job o2) { 22 | // ordering of priority is 1... 2... 3.... N...., where 1 is higher 23 | if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { 24 | return 1; 25 | } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { 26 | return -1; 27 | } else { 28 | return 0; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/CategoryRepository.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository; 2 | 3 | import yourwebproject2.framework.data.BaseJPARepository; 4 | import yourwebproject2.model.entity.Category; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * CRUD operations come from Base Repo but additional operations can be defined here. 10 | * 11 | * @author: kameshr 12 | */ 13 | public interface CategoryRepository extends BaseJPARepository { 14 | /** 15 | * Finds a category with the given categoryName 16 | * 17 | * @param categoryName 18 | * @return 19 | */ 20 | public Category findByCategoryName(String categoryName); 21 | 22 | /** 23 | * Finds a category with the given categoryPriority 24 | * 25 | * @param categoryPriority 26 | * @return 27 | */ 28 | public Category findByCategoryPriority(Integer categoryPriority); 29 | 30 | /** 31 | * Finds sub categories with the given parentCategory 32 | * 33 | * @param parentCategory 34 | * @return 35 | */ 36 | public List findSubCategories(Category parentCategory); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/JobRepository.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository; 2 | 3 | import yourwebproject2.framework.data.BaseJPARepository; 4 | import yourwebproject2.model.entity.Job; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author: kameshr 10 | */ 11 | public interface JobRepository extends BaseJPARepository { 12 | /** 13 | * 14 | * @param count 15 | * @return 16 | */ 17 | public List fetchNewJobsToBeScheduledForExecutionPerPriority(int count); 18 | 19 | /** 20 | * 21 | * @param count 22 | * @return 23 | */ 24 | public List fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); 25 | 26 | /** 27 | * 28 | * @param count 29 | * @return 30 | */ 31 | public List fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); 32 | 33 | /** 34 | * 35 | * @param count 36 | * @return 37 | */ 38 | public List fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository; 2 | 3 | import yourwebproject2.framework.data.BaseJPARepository; 4 | import yourwebproject2.model.entity.User; 5 | 6 | /** 7 | * 8 | * DD Repository for User related actions and events 9 | * 10 | * @author: kameshr 11 | */ 12 | public interface UserRepository extends BaseJPARepository { 13 | /** 14 | * Finds a user with the given email 15 | * 16 | * @param email 17 | * @return 18 | */ 19 | public User findByEmail(String email); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/impl/CategoryRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository.impl; 2 | 3 | import yourwebproject2.framework.data.BaseHibernateJPARepository; 4 | import yourwebproject2.model.entity.Category; 5 | import yourwebproject2.model.repository.CategoryRepository; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import javax.annotation.PostConstruct; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by Y.Kamesh on 8/2/2015. 15 | */ 16 | @Repository 17 | public class CategoryRepositoryImpl extends BaseHibernateJPARepository implements CategoryRepository { 18 | private static Logger LOG = LoggerFactory.getLogger(CategoryRepositoryImpl.class); 19 | 20 | @PostConstruct 21 | public void setUp() { 22 | LOG.info("categoryRepository created..!"); 23 | } 24 | 25 | @Override 26 | public Category findByCategoryName(String categoryName) { 27 | return (Category) sessionFactory.getCurrentSession().createQuery("from Category c where c.name = :categoryName") 28 | .setParameter("categoryName", categoryName).uniqueResult(); 29 | } 30 | 31 | @Override 32 | public Category findByCategoryPriority(Integer categoryPriority) { 33 | return (Category) sessionFactory.getCurrentSession().createQuery("from Category c where c.priority = :categoryPriority") 34 | .setParameter("categoryPriority", categoryPriority).uniqueResult(); 35 | } 36 | 37 | @Override 38 | public List findSubCategories(Category parentCategory) { 39 | return (List) sessionFactory.getCurrentSession().createQuery("from Category c where c.parentCategory = :parentCategory") 40 | .setParameter("parentCategory", parentCategory).list(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/impl/JobRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository.impl; 2 | 3 | import yourwebproject2.framework.data.BaseHibernateJPARepository; 4 | import yourwebproject2.model.entity.Job; 5 | import yourwebproject2.model.repository.JobRepository; 6 | import org.hibernate.Criteria; 7 | import org.hibernate.criterion.Order; 8 | import org.hibernate.criterion.Restrictions; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.stereotype.Repository; 12 | 13 | import javax.annotation.PostConstruct; 14 | import java.util.List; 15 | 16 | /** 17 | * Created by Y.Kamesh on 8/2/2015. 18 | */ 19 | @Repository 20 | public class JobRepositoryImpl extends BaseHibernateJPARepository implements JobRepository { 21 | private static Logger LOG = LoggerFactory.getLogger(JobRepositoryImpl.class); 22 | 23 | @PostConstruct 24 | public void setUp() { 25 | LOG.info("jobRepository created..!"); 26 | } 27 | 28 | @Override 29 | public List fetchNewJobsToBeScheduledForExecutionPerPriority(int count) { 30 | Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz); 31 | c.setMaxResults(count); 32 | c.add(Restrictions.eq("status", Job.Status.NEW)); 33 | c.addOrder(Order.asc("categoryPriority")); 34 | c.addOrder(Order.asc("submitTime")); 35 | return c.list(); 36 | } 37 | 38 | @Override 39 | public List fetchFailedJobsToBeScheduledForExecutionPerPriority(int count) { 40 | Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz); 41 | c.setMaxResults(count); 42 | c.add(Restrictions.eq("status", Job.Status.FAILED)); 43 | c.add(Restrictions.lt("retryCount", 4)); 44 | c.addOrder(Order.desc("categoryPriority")); 45 | c.addOrder(Order.asc("submitTime")); 46 | return c.list(); 47 | } 48 | 49 | @Override 50 | public List fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) { 51 | Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz); 52 | c.setMaxResults(count); 53 | c.add(Restrictions.eq("status", Job.Status.NEW)); 54 | c.addOrder(Order.asc("submitTime")); 55 | return c.list(); 56 | } 57 | 58 | @Override 59 | public List fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) { 60 | Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz); 61 | c.setMaxResults(count); 62 | c.add(Restrictions.eq("status", Job.Status.FAILED)); 63 | c.addOrder(Order.asc("submitTime")); 64 | return c.list(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/model/repository/impl/UserRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.model.repository.impl; 2 | 3 | import yourwebproject2.framework.data.BaseHibernateJPARepository; 4 | import yourwebproject2.model.entity.User; 5 | import yourwebproject2.model.repository.UserRepository; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Repository; 9 | 10 | /** 11 | * 12 | * User Repository Implementation 13 | * 14 | * @author: kameshr 15 | */ 16 | @Repository 17 | public class UserRepositoryImpl extends BaseHibernateJPARepository implements UserRepository { 18 | private static Logger LOG = LoggerFactory.getLogger(UserRepositoryImpl.class); 19 | 20 | @Override 21 | public User findByEmail(String email) { 22 | return (User) sessionFactory.getCurrentSession().createQuery("from User u where u.email = :email") 23 | .setParameter("email", email).uniqueResult(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/CategoryService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service; 2 | 3 | import yourwebproject2.framework.data.BaseService; 4 | import yourwebproject2.framework.exception.NotFoundException; 5 | import yourwebproject2.model.entity.Category; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Brings in the basic CRUD service ops from BaseService. Insert additional ops here. 11 | * 12 | * Created by Y.Kamesh on 8/2/2015. 13 | */ 14 | public interface CategoryService extends BaseService { 15 | /** 16 | * Validates whether the given category already 17 | * exists in the system. 18 | * 19 | * @param categoryName 20 | * 21 | * @return 22 | */ 23 | public boolean isCategoryPresent(String categoryName); 24 | 25 | /** 26 | * Validates whether the given category priority already 27 | * exists in the system. 28 | * 29 | * @param priorityId 30 | * 31 | * @return 32 | */ 33 | public boolean isPriorityPresent(Integer priorityId); 34 | 35 | /** 36 | * Find category by name 37 | * 38 | * @param categoryName 39 | * @return 40 | */ 41 | public Category findByCategoryName(String categoryName) throws NotFoundException; 42 | 43 | /** 44 | * Find sub categories by parent category 45 | * 46 | * @param parentCategory 47 | * @return 48 | */ 49 | public List findSubCategories(Category parentCategory) throws NotFoundException; 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/JobService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service; 2 | 3 | import yourwebproject2.framework.data.BaseService; 4 | import yourwebproject2.model.entity.Job; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Created by Y.Kamesh on 8/2/2015. 10 | */ 11 | public interface JobService extends BaseService { 12 | /** 13 | * 14 | * @param count 15 | * @return 16 | */ 17 | public List fetchNewJobsToBeScheduledForExecutionPerPriority(int count); 18 | 19 | /** 20 | * 21 | * @param count 22 | * @return 23 | */ 24 | public List fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); 25 | 26 | /** 27 | * 28 | * @param count 29 | * @return 30 | */ 31 | public List fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); 32 | 33 | /** 34 | * 35 | * @param count 36 | * @return 37 | */ 38 | public List fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); 39 | } -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/MailJobService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service; 2 | 3 | import yourwebproject2.framework.data.BaseService; 4 | import yourwebproject2.model.entity.Job; 5 | import yourwebproject2.model.entity.User; 6 | 7 | /** 8 | * @author: kameshr 9 | */ 10 | public interface MailJobService extends BaseService { 11 | 12 | /** 13 | * Sends the confirmation mail to user. 14 | * 15 | * @param user 16 | */ 17 | public void sendConfirmationMail(User user); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/UserService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service; 2 | 3 | import yourwebproject2.framework.data.BaseService; 4 | import yourwebproject2.framework.exception.EmailNotFoundException; 5 | import yourwebproject2.model.entity.User; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | /** 10 | * 11 | * Service class to have business logic operation on User entity 12 | * 13 | * @author: kameshr 14 | */ 15 | public interface UserService extends BaseService { 16 | 17 | /** 18 | * Register a new user into the system 19 | * 20 | * @param user 21 | * @param request 22 | * 23 | * @return 24 | */ 25 | public User registerUser(User user, HttpServletRequest request); 26 | 27 | 28 | /** 29 | * Login a new user into the system 30 | * 31 | * @param user 32 | * @param request 33 | * 34 | * @return 35 | */ 36 | public User loginUser(User user, HttpServletRequest request); 37 | 38 | 39 | /** 40 | * Method to validate whether the given password 41 | * is same as users password stored in the system 42 | * 43 | * @param user 44 | * @param pass 45 | * 46 | * @return 47 | */ 48 | public boolean isValidPass(User user, String pass); 49 | 50 | 51 | /** 52 | * Validates whether the given email already 53 | * exists in the system. 54 | * 55 | * @param email 56 | * 57 | * @return 58 | */ 59 | public boolean isEmailExists(String email); 60 | 61 | 62 | /** 63 | * Finds a user entity by the given email 64 | * 65 | * @param email 66 | * @return 67 | */ 68 | public User findByEmail(String email) throws EmailNotFoundException; 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service.impl; 2 | 3 | import yourwebproject2.framework.data.BaseJPAServiceImpl; 4 | import yourwebproject2.framework.exception.NotFoundException; 5 | import yourwebproject2.model.entity.Category; 6 | import yourwebproject2.model.repository.CategoryRepository; 7 | import yourwebproject2.service.CategoryService; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import javax.annotation.PostConstruct; 15 | import java.util.List; 16 | 17 | /** 18 | * Created by Y.Kamesh on 8/2/2015. 19 | */ 20 | @Service 21 | @Transactional 22 | public class CategoryServiceImpl extends BaseJPAServiceImpl implements CategoryService { 23 | private static Logger LOG = LoggerFactory.getLogger(CategoryServiceImpl.class); 24 | 25 | private @Autowired 26 | CategoryRepository categoryRepository; 27 | 28 | @PostConstruct 29 | public void setupService() { 30 | LOG.info("setting up categoryService..."); 31 | this.baseJpaRepository = categoryRepository; 32 | this.entityClass = Category.class; 33 | this.baseJpaRepository.setupEntityClass(Category.class); 34 | LOG.info("categoryService created..."); 35 | } 36 | 37 | 38 | @Override 39 | public boolean isCategoryPresent(String categoryName) { 40 | if (categoryRepository.findByCategoryName(categoryName) != null) { 41 | return true; 42 | } else 43 | return false; 44 | } 45 | 46 | @Override 47 | public boolean isPriorityPresent(Integer categoryPriority) { 48 | if (categoryRepository.findByCategoryPriority(categoryPriority) != null) { 49 | return true; 50 | } else 51 | return false; 52 | } 53 | 54 | @Override 55 | public Category findByCategoryName(String categoryName) throws NotFoundException { 56 | Category c = categoryRepository.findByCategoryName(categoryName); 57 | 58 | if(c==null) { 59 | throw new NotFoundException("Category: "+categoryName + " not found"); 60 | } 61 | 62 | return c; 63 | } 64 | 65 | @Override 66 | public List findSubCategories(Category parentCategory) throws NotFoundException { 67 | List categories = categoryRepository.findSubCategories(parentCategory); 68 | 69 | if(categories==null || categories.size()==0) { 70 | throw new NotFoundException("Subcategories for category: "+parentCategory.getName()+ " not found"); 71 | } 72 | 73 | return categories; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/impl/JobServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service.impl; 2 | 3 | import yourwebproject2.framework.data.BaseJPAServiceImpl; 4 | import yourwebproject2.model.entity.Job; 5 | import yourwebproject2.model.repository.JobRepository; 6 | import yourwebproject2.service.JobService; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | import javax.annotation.PostConstruct; 13 | import javax.transaction.Transactional; 14 | import java.util.List; 15 | 16 | /** 17 | * Created by Y.Kamesh on 8/2/2015. 18 | */ 19 | @Service 20 | @Transactional 21 | public class JobServiceImpl extends BaseJPAServiceImpl implements JobService { 22 | private static Logger LOG = LoggerFactory.getLogger(JobServiceImpl.class); 23 | 24 | protected @Autowired 25 | JobRepository jobRepository; 26 | 27 | @PostConstruct 28 | public void setupService() { 29 | LOG.info("setting up jobService..."); 30 | this.baseJpaRepository = jobRepository; 31 | this.entityClass = Job.class; 32 | this.baseJpaRepository.setupEntityClass(Job.class); 33 | LOG.info("jobService created..."); 34 | } 35 | 36 | @Override 37 | public List fetchNewJobsToBeScheduledForExecutionPerPriority(int count) { 38 | return jobRepository.fetchNewJobsToBeScheduledForExecutionPerPriority(count); 39 | } 40 | 41 | @Override 42 | public List fetchFailedJobsToBeScheduledForExecutionPerPriority(int count) { 43 | return jobRepository.fetchFailedJobsToBeScheduledForExecutionPerPriority(count); 44 | } 45 | 46 | @Override 47 | public List fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) { 48 | return jobRepository.fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(count); 49 | } 50 | 51 | @Override 52 | public List fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) { 53 | return jobRepository.fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(count); 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/impl/MailJobServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service.impl; 2 | 3 | import yourwebproject2.framework.data.BaseJPAServiceImpl; 4 | import yourwebproject2.model.entity.Job; 5 | import yourwebproject2.model.entity.User; 6 | import yourwebproject2.model.repository.JobRepository; 7 | import yourwebproject2.service.MailJobService; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.annotation.PostConstruct; 14 | import javax.transaction.Transactional; 15 | 16 | /** 17 | * @author: kameshr 18 | */ 19 | @Service 20 | @Transactional 21 | public class MailJobServiceImpl extends BaseJPAServiceImpl implements MailJobService { 22 | private static Logger LOG = LoggerFactory.getLogger(MailJobServiceImpl.class); 23 | 24 | protected @Autowired 25 | JobRepository jobRepository; 26 | 27 | @PostConstruct 28 | public void setupService() { 29 | LOG.info("setting up mailJobService..."); 30 | this.baseJpaRepository = jobRepository; 31 | this.entityClass = Job.class; 32 | this.baseJpaRepository.setupEntityClass(Job.class); 33 | LOG.info("mailJobService created..."); 34 | } 35 | 36 | @Override 37 | public void sendConfirmationMail(User user) { 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.service.impl; 2 | 3 | import yourwebproject2.framework.data.BaseJPAServiceImpl; 4 | import yourwebproject2.framework.exception.EmailNotFoundException; 5 | import yourwebproject2.model.entity.User; 6 | import yourwebproject2.model.repository.UserRepository; 7 | import yourwebproject2.service.UserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | import javax.annotation.PostConstruct; 13 | import javax.servlet.http.HttpServletRequest; 14 | import java.util.Date; 15 | 16 | /** 17 | * Service impl class to implement services for accessing the User object entity. 18 | * This class acts as an interface between the outer world and the UserRepository 19 | * 20 | * @author: kameshr 21 | */ 22 | @Service 23 | @Transactional 24 | public class UserServiceImpl extends BaseJPAServiceImpl implements UserService { 25 | private @Autowired UserRepository userRepository; 26 | 27 | @PostConstruct 28 | public void setupService() { 29 | this.baseJpaRepository = userRepository; 30 | this.entityClass = User.class; 31 | this.baseJpaRepository.setupEntityClass(User.class); 32 | } 33 | 34 | 35 | @Override 36 | public boolean isValidPass(User user, String rawPass) { 37 | return User.doesPasswordMatch(rawPass, user.getPassword()); 38 | } 39 | 40 | 41 | @Override 42 | public User registerUser(User user, HttpServletRequest request) { 43 | user.setPassword(User.hashPassword(user.getPassword())); 44 | user.setCurrentLoginAt(new Date()); 45 | user.setCurrentLoginIp(request.getRemoteHost()); 46 | user.setLoginCount(0); 47 | return userRepository.insert(user); 48 | } 49 | 50 | 51 | @Override 52 | public User loginUser(final User user, final HttpServletRequest request) { 53 | user.setLastLoginAt(user.getCurrentLoginAt()); 54 | user.setLastLoginIp(user.getCurrentLoginIp()); 55 | user.setCurrentLoginAt(new Date()); 56 | user.setCurrentLoginIp(request.getRemoteHost()); 57 | user.setLoginCount(user.getLoginCount() + 1); 58 | user.setUpdatedAt(new Date()); 59 | 60 | return userRepository.update(user); 61 | } 62 | 63 | @Override 64 | public boolean isEmailExists(String email) { 65 | if (userRepository.findByEmail(email) != null) { 66 | return true; 67 | } else 68 | return false; 69 | } 70 | 71 | 72 | @Override 73 | public User findByEmail(String email) throws EmailNotFoundException { 74 | User user = userRepository.findByEmail(email); 75 | 76 | if(user != null) { 77 | return user; 78 | } else { 79 | throw new EmailNotFoundException("User not found for email: "+email); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/servlet/YourWebAppDispatcherServlet.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.servlet; 2 | 3 | 4 | import yourwebproject2.framework.servlet.BaseDispatcherServlet; 5 | 6 | /** 7 | * @author: Kamesh Rao Yeduvakula 8 | * @date: 08/02/2015 9 | */ 10 | public class YourWebAppDispatcherServlet extends BaseDispatcherServlet { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/CSRFHeaderFilter.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | import org.springframework.security.web.csrf.CsrfToken; 4 | import org.springframework.web.filter.OncePerRequestFilter; 5 | import org.springframework.web.util.WebUtils; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.Cookie; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | 14 | /** 15 | * @author: kameshr 16 | */ 17 | public class CSRFHeaderFilter extends OncePerRequestFilter { 18 | @Override 19 | protected void doFilterInternal(HttpServletRequest request, 20 | HttpServletResponse response, FilterChain filterChain) 21 | throws ServletException, IOException { 22 | CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class 23 | .getName()); 24 | if (csrf != null) { 25 | Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); 26 | String token = csrf.getToken(); 27 | if (cookie == null || token != null && !token.equals(cookie.getValue())) { 28 | cookie = new Cookie("XSRF-TOKEN", token); 29 | cookie.setPath("/"); 30 | response.addCookie(cookie); 31 | } 32 | } 33 | filterChain.doFilter(request, response); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/RESTAuthFilter.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | import yourwebproject2.service.UserService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.filter.OncePerRequestFilter; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | 13 | /** 14 | * @author: kameshr 15 | */ 16 | public class RESTAuthFilter extends OncePerRequestFilter { 17 | @Autowired 18 | private UserService userService; 19 | 20 | @Override 21 | protected void doFilterInternal(HttpServletRequest request, 22 | HttpServletResponse response, FilterChain filterChain) 23 | throws ServletException, IOException { 24 | 25 | // TODO: Authenticate the request here 26 | filterChain.doFilter(request, response); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/RESTAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.security.core.AuthenticationException; 6 | import org.springframework.security.web.AuthenticationEntryPoint; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | 13 | /** 14 | * @author: kameshr 15 | */ 16 | @Component 17 | public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint { 18 | 19 | private static Logger LOG = LoggerFactory.getLogger(RESTAuthenticationEntryPoint.class); 20 | 21 | public void commence(HttpServletRequest request, HttpServletResponse response, 22 | AuthenticationException authException) throws IOException { 23 | LOG.debug("<--- Inside authentication entry point --->"); 24 | // this is very important for a REST based API login. 25 | // WWW-Authenticate header should be set as FormBased , else browser will show login dialog with realm 26 | response.setHeader("WWW-Authenticate", "FormBased"); 27 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | /** 4 | * @author: kameshr 5 | */ 6 | public interface UserDetailsService extends org.springframework.security.core.userdetails.UserDetailsService { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | import yourwebproject2.framework.exception.EmailNotFoundException; 4 | import yourwebproject2.model.entity.User; 5 | import yourwebproject2.model.repository.UserRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import java.util.*; 15 | 16 | /** 17 | * @author: kameshr 18 | */ 19 | @Service 20 | @Transactional 21 | public class UserDetailsServiceImpl implements UserDetailsService { 22 | private @Autowired UserRepository userRepository; 23 | 24 | @Override 25 | @Transactional(readOnly=true) 26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 27 | return loadUserByEmail(username); 28 | } 29 | 30 | private UserDetails loadUserByEmail(final String email) 31 | throws EmailNotFoundException { 32 | 33 | //User user = userRepository.findByEmail(email); 34 | //List authorities = 35 | // buildUserAuthority(user.getUserRole()); 36 | 37 | //return buildUserForAuthentication(user, authorities); 38 | 39 | 40 | return new UserDetails() { 41 | @Override 42 | public Collection getAuthorities() { 43 | return null; 44 | } 45 | 46 | @Override 47 | public String getPassword() { 48 | return null; 49 | } 50 | 51 | @Override 52 | public String getUsername() { 53 | return null; 54 | } 55 | 56 | @Override 57 | public boolean isAccountNonExpired() { 58 | return false; 59 | } 60 | 61 | @Override 62 | public boolean isAccountNonLocked() { 63 | return false; 64 | } 65 | 66 | @Override 67 | public boolean isCredentialsNonExpired() { 68 | return false; 69 | } 70 | 71 | @Override 72 | public boolean isEnabled() { 73 | return false; 74 | } 75 | }; 76 | } 77 | 78 | // Converts yourwebproject2.model.entity..User user to org.springframework.security.core.userdetails.User 79 | private org.springframework.security.core.userdetails.User buildUserForAuthentication(User user, 80 | List authorities) { 81 | 82 | return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), 83 | user.isEnabled(), true, true, true, authorities); 84 | } 85 | 86 | private List buildUserAuthority(Set userRoles) { 87 | Set setAuths = new HashSet<>(); 88 | 89 | // Build user's authorities 90 | for (UserRole userRole : userRoles) { 91 | setAuths.add(new SimpleGrantedAuthority(userRole.getRole())); 92 | } 93 | 94 | List Result = new ArrayList<>(setAuths); 95 | 96 | return Result; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/UserRole.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity; 2 | 3 | import yourwebproject2.model.entity.User; 4 | 5 | import javax.persistence.*; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * @author: kameshr 10 | */ 11 | //@Entity 12 | //@Table(indexes = { @Index(name="email_fk_idx", columnList = "email", unique = true) }) 13 | public class UserRole implements Serializable { 14 | private Integer userRoleId; 15 | private User user; 16 | private String role; 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | @Column(name = "user_role_id", 21 | unique = true, nullable = false) 22 | public Integer getUserRoleId() { 23 | return this.userRoleId; 24 | } 25 | 26 | public void setUserRoleId(Integer userRoleId) { 27 | this.userRoleId = userRoleId; 28 | } 29 | 30 | @ManyToOne(fetch = FetchType.LAZY) 31 | @JoinColumn(name = "email", nullable = false) 32 | public User getUser() { 33 | return this.user; 34 | } 35 | 36 | public void setUser(User user) { 37 | this.user = user; 38 | } 39 | 40 | @Column(name = "role", nullable = false, length = 45) 41 | public String getRole() { 42 | return this.role; 43 | } 44 | 45 | public void setRole(String role) { 46 | this.role = role; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/appContext-security.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | DBA > ADMIN > USER 42 | 43 | 44 | 45 | 46 | 47 | 48 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/token/StatelessAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity.token; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.context.SecurityContextHolder; 5 | import org.springframework.web.filter.GenericFilterBean; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import java.io.IOException; 13 | 14 | /** 15 | * @author: kameshr 16 | */ 17 | public class StatelessAuthenticationFilter extends GenericFilterBean { 18 | private TokenAuthenticationService authenticationService; 19 | 20 | public StatelessAuthenticationFilter() { 21 | } 22 | 23 | @Override 24 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 25 | throws IOException, ServletException { 26 | HttpServletRequest httpRequest = (HttpServletRequest) request; 27 | Authentication authentication = authenticationService.getAuthentication(httpRequest); 28 | SecurityContextHolder.getContext().setAuthentication(authentication); 29 | filterChain.doFilter(request, response); 30 | SecurityContextHolder.getContext().setAuthentication(null); 31 | } 32 | 33 | public TokenAuthenticationService getAuthenticationService() { 34 | return authenticationService; 35 | } 36 | 37 | public void setAuthenticationService(TokenAuthenticationService authenticationService) { 38 | this.authenticationService = authenticationService; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/token/TokenAuthenticationService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity.token; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.userdetails.User; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | /** 11 | * @author: kameshr 12 | */ 13 | @Component 14 | public class TokenAuthenticationService { 15 | private static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN"; 16 | 17 | private TokenHandler tokenHandler; 18 | 19 | public void addAuthentication(HttpServletResponse response, TokenUserAuthentication authentication) { 20 | final User user = authentication.getDetails(); 21 | response.addHeader(AUTH_HEADER_NAME, tokenHandler.createTokenForUser(user)); 22 | } 23 | 24 | public Authentication getAuthentication(HttpServletRequest request) { 25 | final String token = request.getHeader(AUTH_HEADER_NAME); 26 | if (token != null) { 27 | final User user = tokenHandler.parseUserFromToken(token); 28 | if (user != null) { 29 | return new TokenUserAuthentication(user); 30 | } 31 | } 32 | return null; 33 | } 34 | 35 | public TokenHandler getTokenHandler() { 36 | return tokenHandler; 37 | } 38 | 39 | public void setTokenHandler(TokenHandler tokenHandler) { 40 | this.tokenHandler = tokenHandler; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/token/TokenHandler.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity.token; 2 | 3 | import io.jsonwebtoken.Jwts; 4 | import io.jsonwebtoken.SignatureAlgorithm; 5 | import org.apache.commons.lang.StringUtils; 6 | import org.apache.commons.lang.Validate; 7 | import org.springframework.beans.factory.InitializingBean; 8 | import org.springframework.security.core.userdetails.User; 9 | 10 | /** 11 | * @author: kameshr 12 | */ 13 | public final class TokenHandler implements InitializingBean { 14 | private String secret; 15 | private TokenUserService tokenUserService; 16 | 17 | @Override 18 | public void afterPropertiesSet() throws Exception { 19 | Validate.isTrue(StringUtils.isNotBlank(secret), "secret is blank"); 20 | Validate.notNull(tokenUserService, "tokenUserService is null"); 21 | } 22 | 23 | public User parseUserFromToken(String token) { 24 | String username = Jwts.parser() 25 | .setSigningKey(secret) 26 | .parseClaimsJws(token) 27 | .getBody() 28 | .getSubject(); 29 | return tokenUserService.loadUserByUsername(username); 30 | } 31 | 32 | public String createTokenForUser(User user) { 33 | return Jwts.builder() 34 | .setSubject(user.getUsername()) 35 | .signWith(SignatureAlgorithm.HS512, secret) 36 | .compact(); 37 | } 38 | 39 | public String getSecret() { 40 | return secret; 41 | } 42 | 43 | public void setSecret(String secret) { 44 | this.secret = secret; 45 | } 46 | 47 | public TokenUserService getTokenUserService() { 48 | return tokenUserService; 49 | } 50 | 51 | public void setTokenUserService(TokenUserService tokenUserService) { 52 | this.tokenUserService = tokenUserService; 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/token/TokenUserAuthentication.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity.token; 2 | 3 | import org.springframework.security.core.Authentication; 4 | import org.springframework.security.core.GrantedAuthority; 5 | import org.springframework.security.core.userdetails.User; 6 | 7 | import java.util.Collection; 8 | 9 | public class TokenUserAuthentication implements Authentication { 10 | 11 | private final User user; 12 | private boolean authenticated = true; 13 | 14 | public TokenUserAuthentication(User user) { 15 | this.user = user; 16 | } 17 | 18 | @Override 19 | public String getName() { 20 | return user.getUsername(); 21 | } 22 | 23 | @Override 24 | public Collection getAuthorities() { 25 | return user.getAuthorities(); 26 | } 27 | 28 | @Override 29 | public Object getCredentials() { 30 | return user.getPassword(); 31 | } 32 | 33 | @Override 34 | public User getDetails() { 35 | return user; 36 | } 37 | 38 | @Override 39 | public Object getPrincipal() { 40 | return user.getUsername(); 41 | } 42 | 43 | @Override 44 | public boolean isAuthenticated() { 45 | return authenticated; 46 | } 47 | 48 | @Override 49 | public void setAuthenticated(boolean authenticated) { 50 | this.authenticated = authenticated; 51 | } 52 | } -------------------------------------------------------------------------------- /src/main/java/yourwebproject2/unusedspringsecurity/token/TokenUserService.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2.unusedspringsecurity.token; 2 | 3 | import org.springframework.security.authentication.AccountStatusUserDetailsChecker; 4 | import org.springframework.security.core.userdetails.User; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | 7 | import java.util.HashMap; 8 | 9 | public class TokenUserService implements org.springframework.security.core.userdetails.UserDetailsService { 10 | 11 | private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker(); 12 | private final HashMap userMap = new HashMap<>(); 13 | 14 | @Override 15 | public final User loadUserByUsername(String username) throws UsernameNotFoundException { 16 | final User user = userMap.get(username); 17 | if (user == null) { 18 | throw new UsernameNotFoundException("user not found"); 19 | } 20 | detailsChecker.check(user); 21 | return user; 22 | } 23 | 24 | public void addUser(User user) { 25 | userMap.put(user.getUsername(), user); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/config/database/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | org.hibernate.dialect.MySQLDialect 10 | 11 | 12 | true 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/resources/config/database/test-hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | org.hibernate.dialect.H2Dialect 10 | 11 | 12 | true 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-auth.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-interceptor.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-jdbc-test.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.hibernate.dialect.H2Dialect 39 | update 40 | true 41 | 20 42 | 5 43 | 50 44 | 600 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-jdbc.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.hibernate.dialect.MySQLDialect 39 | update 40 | true 41 | 20 42 | 5 43 | 50 44 | 600 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-repository.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-scheduler.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-service.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-servlet.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/main/resources/config/spring/appContext-ywp2.xml: -------------------------------------------------------------------------------- 1 | 15 | 16 | 17 | 18 | 19 | 20 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 5 | 6 | 7 | 8 | 9 | log/yourwebproject2.log 10 | 11 | 12 | %date %level [%thread] %logger{10} [%file:%line] %msg%n 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/error.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

Internal Server Error

5 | 6 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | Your Web Project 2 9 | 10 | 11 | 12 | contextConfigLocation 13 | 14 | classpath:config/spring/appContext-interceptor.xml, 15 | classpath:config/spring/appContext-jdbc-test.xml, 16 | classpath:config/spring/appContext-repository.xml, 17 | classpath:config/spring/appContext-service.xml, 18 | classpath:config/spring/appContext-scheduler.xml, 19 | classpath:config/spring/appContext-auth.xml, 20 | classpath:config/spring/appContext-servlet.xml 21 | 22 | 23 | 24 | 25 | 26 | 27 | encodingFilter 28 | 29 | org.springframework.web.filter.CharacterEncodingFilter 30 | 31 | 32 | encoding 33 | UTF-8 34 | 35 | 36 | 37 | encodingFilter 38 | /* 39 | 40 | 41 | 42 | 43 | jwtTokenAuthFilter 44 | org.springframework.web.filter.DelegatingFilterProxy 45 | 46 | 47 | 48 | jwtTokenAuthFilter 49 | /* 50 | 51 | 52 | 53 | 54 | 55 | webAppDispatcherServlet 56 | 57 | yourwebproject2.servlet.YourWebAppDispatcherServlet 58 | 59 | 60 | contextConfigLocation 61 | classpath:config/spring/appContext-ywp2.xml 62 | 63 | 1 64 | 65 | 66 | 67 | webAppDispatcherServlet 68 | /api/* 69 | 70 | 71 | 72 | 73 | org.springframework.web.context.ContextLoaderListener 74 | 75 | 76 | 77 | index.html 78 | 79 | 80 | 81 | java.lang.Throwable 82 | /api/error 83 | 84 | 85 | 86 | 400 87 | /api/error 88 | 89 | 90 | 91 | 401 92 | /api/error 93 | 94 | 95 | 96 | 402 97 | /api/error 98 | 99 | 100 | 101 | 403 102 | /api/error 103 | 104 | 105 | 106 | 404 107 | /api/error 108 | 109 | 110 | 111 | 500 112 | /api/error 113 | 114 | 115 | 116 | 501 117 | /api/error 118 | 119 | -------------------------------------------------------------------------------- /src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | YourWebProject2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
34 | 35 | -------------------------------------------------------------------------------- /src/main/webapp/res/css/app.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/src/main/webapp/res/css/app.css -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular-animate/index.js: -------------------------------------------------------------------------------- 1 | require('./angular-animate'); 2 | module.exports = 'ngAnimate'; 3 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular-cookies/angular-cookies.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | AngularJS v1.3.15 3 | (c) 2010-2014 Google, Inc. http://angularjs.org 4 | License: MIT 5 | */ 6 | (function(p,f,n){'use strict';f.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(e,b){var c={},g={},h,k=!1,l=f.copy,m=f.isUndefined;b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,l(a,g),l(a,c),k&&e.$apply())})();k=!0;e.$watch(function(){var a,d,e;for(a in g)m(c[a])&&b.cookies(a,n);for(a in c)d=c[a],f.isString(d)||(d=""+d,c[a]=d),d!==g[a]&&(b.cookies(a,d),e=!0);if(e)for(a in d=b.cookies(),c)c[a]!==d[a]&&(m(d[a])?delete c[a]:c[a]=d[a])});return c}]).factory("$cookieStore", 7 | ["$cookies",function(e){return{get:function(b){return(b=e[b])?f.fromJson(b):b},put:function(b,c){e[b]=f.toJson(c)},remove:function(b){delete e[b]}}}])})(window,window.angular); 8 | //# sourceMappingURL=angular-cookies.min.js.map 9 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular-cookies/angular-cookies.min.js.map: -------------------------------------------------------------------------------- 1 | { 2 | "version":3, 3 | "file":"angular-cookies.min.js", 4 | "lineCount":7, 5 | "mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAmBtCD,CAAAE,OAAA,CAAe,WAAf,CAA4B,CAAC,IAAD,CAA5B,CAAAC,QAAA,CA0BW,UA1BX,CA0BuB,CAAC,YAAD,CAAe,UAAf,CAA2B,QAAQ,CAACC,CAAD,CAAaC,CAAb,CAAuB,CAAA,IACvEC,EAAU,EAD6D,CAEvEC,EAAc,EAFyD,CAGvEC,CAHuE,CAIvEC,EAAU,CAAA,CAJ6D,CAKvEC,EAAOV,CAAAU,KALgE,CAMvEC,EAAcX,CAAAW,YAGlBN,EAAAO,UAAA,CAAmB,QAAQ,EAAG,CAC5B,IAAIC,EAAiBR,CAAAC,QAAA,EACjBE,EAAJ,EAA0BK,CAA1B,GACEL,CAGA,CAHqBK,CAGrB,CAFAH,CAAA,CAAKG,CAAL,CAAqBN,CAArB,CAEA,CADAG,CAAA,CAAKG,CAAL,CAAqBP,CAArB,CACA,CAAIG,CAAJ,EAAaL,CAAAU,OAAA,EAJf,CAF4B,CAA9B,CAAA,EAUAL,EAAA,CAAU,CAAA,CAKVL,EAAAW,OAAA,CASAC,QAAa,EAAG,CAAA,IACVC,CADU,CAEVC,CAFU,CAIVC,CAGJ,KAAKF,CAAL,GAAaV,EAAb,CACMI,CAAA,CAAYL,CAAA,CAAQW,CAAR,CAAZ,CAAJ,EACEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBhB,CAAvB,CAKJ,KAAKgB,CAAL,GAAaX,EAAb,CACEY,CAKA,CALQZ,CAAA,CAAQW,CAAR,CAKR,CAJKjB,CAAAoB,SAAA,CAAiBF,CAAjB,CAIL,GAHEA,CACA,CADQ,EACR,CADaA,CACb,CAAAZ,CAAA,CAAQW,CAAR,CAAA,CAAgBC,CAElB,EAAIA,CAAJ,GAAcX,CAAA,CAAYU,CAAZ,CAAd,GACEZ,CAAAC,QAAA,CAAiBW,CAAjB,CAAuBC,CAAvB,CACA,CAAAC,CAAA,CAAU,CAAA,CAFZ,CAOF,IAAIA,CAAJ,CAIE,IAAKF,CAAL,GAFAI,EAEaf,CAFID,CAAAC,QAAA,EAEJA,CAAAA,CAAb,CACMA,CAAA,CAAQW,CAAR,CAAJ,GAAsBI,CAAA,CAAeJ,CAAf,CAAtB,GAEMN,CAAA,CAAYU,CAAA,CAAeJ,CAAf,CAAZ,CAAJ,CACE,OAAOX,CAAA,CAAQW,CAAR,CADT,CAGEX,CAAA,CAAQW,CAAR,CAHF,CAGkBI,CAAA,CAAeJ,CAAf,CALpB,CAhCU,CAThB,CAEA,OAAOX,EA1BoE,CAA1D,CA1BvB,CAAAH,QAAA,CAoIW,cApIX;AAoI2B,CAAC,UAAD,CAAa,QAAQ,CAACmB,CAAD,CAAW,CAErD,MAAO,CAWLC,IAAKA,QAAQ,CAACC,CAAD,CAAM,CAEjB,MAAO,CADHN,CACG,CADKI,CAAA,CAASE,CAAT,CACL,EAAQxB,CAAAyB,SAAA,CAAiBP,CAAjB,CAAR,CAAkCA,CAFxB,CAXd,CA0BLQ,IAAKA,QAAQ,CAACF,CAAD,CAAMN,CAAN,CAAa,CACxBI,CAAA,CAASE,CAAT,CAAA,CAAgBxB,CAAA2B,OAAA,CAAeT,CAAf,CADQ,CA1BrB,CAuCLU,OAAQA,QAAQ,CAACJ,CAAD,CAAM,CACpB,OAAOF,CAAA,CAASE,CAAT,CADa,CAvCjB,CAF8C,CAAhC,CApI3B,CAnBsC,CAArC,CAAD,CAwMGzB,MAxMH,CAwMWA,MAAAC,QAxMX;", 6 | "sources":["angular-cookies.js"], 7 | "names":["window","angular","undefined","module","factory","$rootScope","$browser","cookies","lastCookies","lastBrowserCookies","runEval","copy","isUndefined","addPollFn","currentCookies","$apply","$watch","push","name","value","updated","isString","browserCookies","$cookies","get","key","fromJson","put","toJson","remove"] 8 | } 9 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular-cookies/index.js: -------------------------------------------------------------------------------- 1 | require('./angular-cookies'); 2 | module.exports = 'ngCookies'; 3 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular-messages/angular-messages.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | AngularJS v1.3.15 3 | (c) 2010-2014 Google, Inc. http://angularjs.org 4 | License: MIT 5 | */ 6 | (function(r,f,s){'use strict';f.module("ngMessages",[]).directive("ngMessages",["$compile","$animate","$templateRequest",function(q,k,l){return{restrict:"AE",controller:function(){this.$renderNgMessageClasses=f.noop;var b=[];this.registerMessage=function(d,a){for(var c=0;c").html(a);f.forEach(a.children(), 8 | function(a){a=f.element(a);h?h.after(a):d.prepend(a);h=a;q(a)(b)});c.renderMessages(e,g)})}}}]).directive("ngMessage",["$animate",function(f){return{require:"^ngMessages",transclude:"element",terminal:!0,restrict:"AE",link:function(k,l,b,d,a){for(var c,g,e=l[0],n=e.parentNode,h=0,p=0;h 4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped 5 | 6 | declare module ng.ui { 7 | 8 | interface IState { 9 | name?: string; 10 | template?: string; 11 | templateUrl?: any; // string || () => string 12 | templateProvider?: any; // () => string || IPromise 13 | controller?: any; 14 | controllerAs?: string; 15 | controllerProvider?: any; 16 | resolve?: {}; 17 | url?: string; 18 | params?: any; 19 | views?: {}; 20 | abstract?: boolean; 21 | onEnter?: (...args: any[]) => void; 22 | onExit?: (...args: any[]) => void; 23 | data?: any; 24 | reloadOnSearch?: boolean; 25 | } 26 | 27 | interface ITypedState extends IState { 28 | data?: T; 29 | } 30 | 31 | interface IStateProvider extends IServiceProvider { 32 | state(name: string, config: IState): IStateProvider; 33 | state(config: IState): IStateProvider; 34 | decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; 35 | } 36 | 37 | interface IUrlMatcher { 38 | concat(pattern: string): IUrlMatcher; 39 | exec(path: string, searchParams: {}): {}; 40 | parameters(): string[]; 41 | format(values: {}): string; 42 | } 43 | 44 | interface IUrlMatcherFactory { 45 | compile(pattern: string): IUrlMatcher; 46 | isMatcher(o: any): boolean; 47 | } 48 | 49 | interface IUrlRouterProvider extends IServiceProvider { 50 | when(whenPath: RegExp, handler: Function): IUrlRouterProvider; 51 | when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; 52 | when(whenPath: RegExp, toPath: string): IUrlRouterProvider; 53 | when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; 54 | when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; 55 | when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; 56 | when(whenPath: string, handler: Function): IUrlRouterProvider; 57 | when(whenPath: string, handler: any[]): IUrlRouterProvider; 58 | when(whenPath: string, toPath: string): IUrlRouterProvider; 59 | otherwise(handler: Function): IUrlRouterProvider; 60 | otherwise(handler: any[]): IUrlRouterProvider; 61 | otherwise(path: string): IUrlRouterProvider; 62 | rule(handler: Function): IUrlRouterProvider; 63 | rule(handler: any[]): IUrlRouterProvider; 64 | } 65 | 66 | interface IStateOptions { 67 | location?: any; 68 | inherit?: boolean; 69 | relative?: IState; 70 | notify?: boolean; 71 | reload?: boolean; 72 | } 73 | 74 | interface IHrefOptions { 75 | lossy?: boolean; 76 | inherit?: boolean; 77 | relative?: IState; 78 | absolute?: boolean; 79 | } 80 | 81 | interface IStateService { 82 | go(to: string, params?: {}, options?: IStateOptions): IPromise; 83 | transitionTo(state: string, params?: {}, updateLocation?: boolean): void; 84 | transitionTo(state: string, params?: {}, options?: IStateOptions): void; 85 | includes(state: string, params?: {}): boolean; 86 | is(state:string, params?: {}): boolean; 87 | is(state: IState, params?: {}): boolean; 88 | href(state: IState, params?: {}, options?: IHrefOptions): string; 89 | href(state: string, params?: {}, options?: IHrefOptions): string; 90 | get(state: string): IState; 91 | get(): IState[]; 92 | current: IState; 93 | params: any; 94 | reload(): void; 95 | } 96 | 97 | interface IStateParamsService { 98 | [key: string]: any; 99 | } 100 | 101 | interface IStateParams { 102 | [key: string]: any; 103 | } 104 | 105 | interface IUrlRouterService { 106 | /* 107 | * Triggers an update; the same update that happens when the address bar 108 | * url changes, aka $locationChangeSuccess. 109 | * 110 | * This method is useful when you need to use preventDefault() on the 111 | * $locationChangeSuccess event, perform some custom logic (route protection, 112 | * auth, config, redirection, etc) and then finally proceed with the transition 113 | * by calling $urlRouter.sync(). 114 | * 115 | */ 116 | sync(): void; 117 | } 118 | 119 | interface IUiViewScrollProvider { 120 | /* 121 | * Reverts back to using the core $anchorScroll service for scrolling 122 | * based on the url anchor. 123 | */ 124 | useAnchorScroll(): void; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular/angular-csp.css: -------------------------------------------------------------------------------- 1 | /* Include this file in your html if you are using the CSP mode. */ 2 | 3 | @charset "UTF-8"; 4 | 5 | [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], 6 | .ng-cloak, .x-ng-cloak, 7 | .ng-hide:not(.ng-hide-animate) { 8 | display: none !important; 9 | } 10 | 11 | ng\:form { 12 | display: block; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular/angular.min.js.gzip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/src/main/webapp/res/js/angular/angular.min.js.gzip -------------------------------------------------------------------------------- /src/main/webapp/res/js/angular/index.js: -------------------------------------------------------------------------------- 1 | quire('./angular'); 2 | module.exports = angular; 3 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework/a38cbd855f449ce45470931345d62ee1c9f976d6/src/main/webapp/res/js/bootstrap/dist/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /src/main/webapp/res/js/cryptojs/rollups/hmac-sha1.js: -------------------------------------------------------------------------------- 1 | /* 2 | CryptoJS v3.1.2 3 | code.google.com/p/crypto-js 4 | (c) 2009-2013 by Jeff Mott. All rights reserved. 5 | code.google.com/p/crypto-js/wiki/License 6 | */ 7 | var CryptoJS=CryptoJS||function(g,l){var e={},d=e.lib={},m=function(){},k=d.Base={extend:function(a){m.prototype=this;var c=new m;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, 8 | p=d.WordArray=k.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||n).stringify(this)},concat:function(a){var c=this.words,q=a.words,f=this.sigBytes;a=a.sigBytes;this.clamp();if(f%4)for(var b=0;b>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((f+b)%4);else if(65535>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=k.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(f%4)&255;b.push((d>>>4).toString(16));b.push((d&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>3]|=parseInt(a.substr(f, 10 | 2),16)<<24-4*(f%8);return new p.init(b,c/2)}},j=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f>>2]>>>24-8*(f%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new p.init(b,c)}},h=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(j.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return j.parse(unescape(encodeURIComponent(a)))}}, 11 | r=d.BufferedBlockAlgorithm=k.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,f=c.sigBytes,d=this.blockSize,e=f/(4*d),e=a?g.ceil(e):g.max((e|0)-this._minBufferSize,0);a=e*d;f=g.min(4*a,f);if(a){for(var k=0;ka;a++){if(16>a)m[a]=d[e+a]|0;else{var c=m[a-3]^m[a-8]^m[a-14]^m[a-16];m[a]=c<<1|c>>>31}c=(n<<5|n>>>27)+l+m[a];c=20>a?c+((j&h|~j&g)+1518500249):40>a?c+((j^h^g)+1859775393):60>a?c+((j&h|j&g|h&g)-1894007588):c+((j^h^ 15 | g)-899497514);l=g;g=h;h=j<<30|j>>>2;j=n;n=c}b[0]=b[0]+n|0;b[1]=b[1]+j|0;b[2]=b[2]+h|0;b[3]=b[3]+g|0;b[4]=b[4]+l|0},_doFinalize:function(){var d=this._data,e=d.words,b=8*this._nDataBytes,g=8*d.sigBytes;e[g>>>5]|=128<<24-g%32;e[(g+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(g+64>>>9<<4)+15]=b;d.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=d.clone.call(this);e._hash=this._hash.clone();return e}});g.SHA1=d._createHelper(l);g.HmacSHA1=d._createHmacHelper(l)})(); 16 | (function(){var g=CryptoJS,l=g.enc.Utf8;g.algo.HMAC=g.lib.Base.extend({init:function(e,d){e=this._hasher=new e.init;"string"==typeof d&&(d=l.parse(d));var g=e.blockSize,k=4*g;d.sigBytes>k&&(d=e.finalize(d));d.clamp();for(var p=this._oKey=d.clone(),b=this._iKey=d.clone(),n=p.words,j=b.words,h=0;h>>2]|=(f[g>>>2]>>>24-8*(g%4)&255)<<24-8*((b+g)%4);else if(65535>>2]=f[g>>>2];else d.push.apply(d,f);this.sigBytes+=a;return this},clamp:function(){var a=this.words,d=this.sigBytes;a[d>>>2]&=4294967295<< 9 | 32-8*(d%4);a.length=j.ceil(d/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var d=[],f=0;f>>2]>>>24-8*(b%4)&255;f.push((g>>>4).toString(16));f.push((g&15).toString(16))}return f.join("")},parse:function(a){for(var d=a.length,f=[],b=0;b>>3]|=parseInt(a.substr(b, 10 | 2),16)<<24-4*(b%8);return new r.init(f,d/2)}},n=s.Latin1={stringify:function(a){var d=a.words;a=a.sigBytes;for(var f=[],b=0;b>>2]>>>24-8*(b%4)&255));return f.join("")},parse:function(a){for(var d=a.length,f=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(f,d)}},h=s.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(d){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, 11 | u=e.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var d=this._data,f=d.words,b=d.sigBytes,g=this.blockSize,c=b/(4*g),c=a?j.ceil(c):j.max((c|0)-this._minBufferSize,0);a=c*g;b=j.min(4*a,b);if(a){for(var e=0;en;){var h;a:{h=l;for(var u=j.sqrt(h),t=2;t<=u;t++)if(!(h%t)){h=!1;break a}h=!0}h&&(8>n&&(m[n]=s(j.pow(l,0.5))),r[n]=s(j.pow(l,1/3)),n++);l++}var a=[],c=c.SHA256=p.extend({_doReset:function(){this._hash=new e.init(m.slice(0))},_doProcessBlock:function(d,f){for(var b=this._hash.words,g=b[0],c=b[1],e=b[2],j=b[3],h=b[4],p=b[5],m=b[6],n=b[7],q=0;64>q;q++){if(16>q)a[q]= 15 | d[f+q]|0;else{var k=a[q-15],l=a[q-2];a[q]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[q-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[q-16]}k=n+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&p^~h&m)+r[q]+a[q];l=((g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22))+(g&c^g&e^c&e);n=m;m=p;p=h;h=j+k|0;j=e;e=c;c=g;g=k+l|0}b[0]=b[0]+g|0;b[1]=b[1]+c|0;b[2]=b[2]+e|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+p|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,c=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; 16 | c[e>>>5]|=128<<24-e%32;c[(e+64>>>9<<4)+14]=j.floor(b/4294967296);c[(e+64>>>9<<4)+15]=b;a.sigBytes=4*c.length;this._process();return this._hash},clone:function(){var a=p.clone.call(this);a._hash=this._hash.clone();return a}});k.SHA256=p._createHelper(c);k.HmacSHA256=p._createHmacHelper(c)})(Math); 17 | (function(){var j=CryptoJS,k=j.lib.WordArray,c=j.algo,e=c.SHA256,c=c.SHA224=e.extend({_doReset:function(){this._hash=new k.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var c=e._doFinalize.call(this);c.sigBytes-=4;return c}});j.SHA224=e._createHelper(c);j.HmacSHA224=e._createHmacHelper(c)})(); 18 | (function(){var j=CryptoJS,k=j.enc.Utf8;j.algo.HMAC=j.lib.Base.extend({init:function(c,e){c=this._hasher=new c.init;"string"==typeof e&&(e=k.parse(e));var j=c.blockSize,m=4*j;e.sigBytes>m&&(e=c.finalize(e));e.clamp();for(var r=this._oKey=e.clone(),s=this._iKey=e.clone(),l=r.words,n=s.words,h=0;h>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, 10 | 2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, 11 | u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;gn;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]= 15 | c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; 16 | d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math); 17 | (function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j>>2]|=(p[b>>>2]>>>24-8*(b%4)&255)<<24-8*((f+b)%4);else if(65535>>2]=p[b>>>2];else c.push.apply(c,p);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=n.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(f%4)&255;b.push((d>>>4).toString(16));b.push((d&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>3]|=parseInt(a.substr(f, 10 | 2),16)<<24-4*(f%8);return new q.init(b,c/2)}},k=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f>>2]>>>24-8*(f%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new q.init(b,c)}},h=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}}, 11 | u=d.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,f=b.sigBytes,l=this.blockSize,e=f/(4*l),e=a?g.ceil(e):g.max((e|0)-this._minBufferSize,0);a=e*l;f=g.min(4*a,f);if(a){for(var h=0;ha;a++){if(16>a)m[a]=d[e+a]|0;else{var c=m[a-3]^m[a-8]^m[a-14]^m[a-16];m[a]=c<<1|c>>>31}c=(l<<5|l>>>27)+j+m[a];c=20>a?c+((k&h|~k&g)+1518500249):40>a?c+((k^h^g)+1859775393):60>a?c+((k&h|k&g|h&g)-1894007588):c+((k^h^ 15 | g)-899497514);j=g;g=h;h=k<<30|k>>>2;k=l;l=c}b[0]=b[0]+l|0;b[1]=b[1]+k|0;b[2]=b[2]+h|0;b[3]=b[3]+g|0;b[4]=b[4]+j|0},_doFinalize:function(){var d=this._data,e=d.words,b=8*this._nDataBytes,l=8*d.sigBytes;e[l>>>5]|=128<<24-l%32;e[(l+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(l+64>>>9<<4)+15]=b;d.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=d.clone.call(this);e._hash=this._hash.clone();return e}});g.SHA1=d._createHelper(j);g.HmacSHA1=d._createHmacHelper(j)})(); 16 | (function(){var g=CryptoJS,j=g.enc.Utf8;g.algo.HMAC=g.lib.Base.extend({init:function(e,d){e=this._hasher=new e.init;"string"==typeof d&&(d=j.parse(d));var g=e.blockSize,n=4*g;d.sigBytes>n&&(d=e.finalize(d));d.clamp();for(var q=this._oKey=d.clone(),b=this._iKey=d.clone(),l=q.words,k=b.words,h=0;h>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=e.ceil(c/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(d%4)&255;b.push((f>>>4).toString(16));b.push((f&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],d=0;d>>3]|=parseInt(a.substr(d, 10 | 2),16)<<24-4*(d%8);return new n.init(b,c/2)}},g=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d>>2]>>>24-8*(d%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new n.init(b,c)}},r=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(g.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return g.parse(unescape(encodeURIComponent(a)))}}, 11 | k=j.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new n.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=r.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,d=c.sigBytes,f=this.blockSize,h=d/(4*f),h=a?e.ceil(h):e.max((h|0)-this._minBufferSize,0);a=h*f;d=e.min(4*a,d);if(a){for(var g=0;ga;a++){if(16>a)l[a]=f[n+a]|0;else{var c=l[a-3]^l[a-8]^l[a-14]^l[a-16];l[a]=c<<1|c>>>31}c=(h<<5|h>>>27)+j+l[a];c=20>a?c+((g&e|~g&k)+1518500249):40>a?c+((g^e^k)+1859775393):60>a?c+((g&e|g&k|e&k)-1894007588):c+((g^e^ 15 | k)-899497514);j=k;k=e;e=g<<30|g>>>2;g=h;h=c}b[0]=b[0]+h|0;b[1]=b[1]+g|0;b[2]=b[2]+e|0;b[3]=b[3]+k|0;b[4]=b[4]+j|0},_doFinalize:function(){var f=this._data,e=f.words,b=8*this._nDataBytes,h=8*f.sigBytes;e[h>>>5]|=128<<24-h%32;e[(h+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(h+64>>>9<<4)+15]=b;f.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=j.clone.call(this);e._hash=this._hash.clone();return e}});e.SHA1=j._createHelper(m);e.HmacSHA1=j._createHmacHelper(m)})(); 16 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/cryptojs/rollups/sha224.js: -------------------------------------------------------------------------------- 1 | /* 2 | CryptoJS v3.1.2 3 | code.google.com/p/crypto-js 4 | (c) 2009-2013 by Jeff Mott. All rights reserved. 5 | code.google.com/p/crypto-js/wiki/License 6 | */ 7 | var CryptoJS=CryptoJS||function(g,l){var f={},k=f.lib={},h=function(){},m=k.Base={extend:function(a){h.prototype=this;var c=new h;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, 8 | q=k.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||s).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, 10 | 2),16)<<24-4*(b%8);return new q.init(d,c/2)}},n=t.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},j=t.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, 11 | w=k.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?g.ceil(f):g.max((f|0)-this._minBufferSize,0);a=f*e;b=g.min(4*a,b);if(a){for(var u=0;un;){var j;a:{j=s;for(var w=g.sqrt(j),v=2;v<=w;v++)if(!(j%v)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=t(g.pow(s,0.5))),q[n]=t(g.pow(s,1/3)),n++);s++}var a=[],f=f.SHA256=h.extend({_doReset:function(){this._hash=new k.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],k=b[3],h=b[4],l=b[5],m=b[6],n=b[7],p=0;64>p;p++){if(16>p)a[p]= 15 | c[d+p]|0;else{var j=a[p-15],r=a[p-2];a[p]=((j<<25|j>>>7)^(j<<14|j>>>18)^j>>>3)+a[p-7]+((r<<15|r>>>17)^(r<<13|r>>>19)^r>>>10)+a[p-16]}j=n+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&l^~h&m)+q[p]+a[p];r=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);n=m;m=l;l=h;h=k+j|0;k=g;g=f;f=e;e=j+r|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+k|0;b[4]=b[4]+h|0;b[5]=b[5]+l|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; 16 | d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=g.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=h.clone.call(this);a._hash=this._hash.clone();return a}});l.SHA256=h._createHelper(f);l.HmacSHA256=h._createHmacHelper(f)})(Math); 17 | (function(){var g=CryptoJS,l=g.lib.WordArray,f=g.algo,k=f.SHA256,f=f.SHA224=k.extend({_doReset:function(){this._hash=new l.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var f=k._doFinalize.call(this);f.sigBytes-=4;return f}});g.SHA224=k._createHelper(f);g.HmacSHA224=k._createHmacHelper(f)})(); 18 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/cryptojs/rollups/sha256.js: -------------------------------------------------------------------------------- 1 | /* 2 | CryptoJS v3.1.2 3 | code.google.com/p/crypto-js 4 | (c) 2009-2013 by Jeff Mott. All rights reserved. 5 | code.google.com/p/crypto-js/wiki/License 6 | */ 7 | var CryptoJS=CryptoJS||function(h,s){var f={},t=f.lib={},g=function(){},j=t.Base={extend:function(a){g.prototype=this;var c=new g;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, 8 | q=t.WordArray=j.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||u).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 9 | 32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, 10 | 2),16)<<24-4*(b%8);return new q.init(d,c/2)}},k=v.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},l=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}}, 11 | x=t.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=l.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var m=0;mk;){var l;a:{l=u;for(var x=h.sqrt(l),w=2;w<=x;w++)if(!(l%w)){l=!1;break a}l=!0}l&&(8>k&&(j[k]=v(h.pow(u,0.5))),q[k]=v(h.pow(u,1/3)),k++);u++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new t.init(j.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],m=b[2],h=b[3],p=b[4],j=b[5],k=b[6],l=b[7],n=0;64>n;n++){if(16>n)a[n]= 15 | c[d+n]|0;else{var r=a[n-15],g=a[n-2];a[n]=((r<<25|r>>>7)^(r<<14|r>>>18)^r>>>3)+a[n-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[n-16]}r=l+((p<<26|p>>>6)^(p<<21|p>>>11)^(p<<7|p>>>25))+(p&j^~p&k)+q[n]+a[n];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&m^f&m);l=k;k=j;j=p;p=h+r|0;h=m;m=f;f=e;e=r+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+m|0;b[3]=b[3]+h|0;b[4]=b[4]+p|0;b[5]=b[5]+j|0;b[6]=b[6]+k|0;b[7]=b[7]+l|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; 16 | d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=g._createHelper(f);s.HmacSHA256=g._createHmacHelper(f)})(Math); 17 | -------------------------------------------------------------------------------- /src/main/webapp/res/js/spring-security-csrf-token-interceptor/dist/spring-security-csrf-token-interceptor.min.js: -------------------------------------------------------------------------------- 1 | !function(){"use strict";angular.module("spring-security-csrf-token-interceptor",[]).factory("csrfInterceptor",["$injector","$q",function($injector){var $q=$injector.get("$q"),csrf=$injector.get("csrf"),csrfService=csrf.init();return{request:function(config){return csrfService.settings.httpTypes.indexOf(config.method.toUpperCase())>-1&&(config.headers[csrfService.settings.csrfTokenHeader]=csrfService.token),config||$q.when(config)},responseError:function(response){var $http,newToken=response.headers(csrfService.settings.csrfTokenHeader);return 403===response.status&&csrfService.numRetries -1) { 84 | $location.path('/admin.login'); 85 | } else if($location.path().indexOf('app') > -1) { 86 | $location.path('/login'); 87 | } else { 88 | $location.path('/home'); 89 | } 90 | } 91 | }); 92 | } 93 | ]); -------------------------------------------------------------------------------- /src/main/webapp/webui/controllers/AdminController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/8/2015. 3 | */ 4 | angular.module('App.Admin') 5 | .controller('AdminController', ['$rootScope', '$location', AdminController]); 6 | 7 | function AdminController($rootScope, $location) { 8 | var admin = this; 9 | admin.currentUser = null; 10 | }; -------------------------------------------------------------------------------- /src/main/webapp/webui/controllers/AppController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/8/2015. 3 | */ 4 | angular.module('App') 5 | .controller('AppController', AppController); 6 | 7 | AppController.$inject = ['$location', '$scope', '$rootScope', 'AuthService', 'FlashMessage']; 8 | function AppController($location, $scope, $rootScope, AuthService, FlashMessage) { 9 | var app = this; 10 | console.log("app controller"); 11 | 12 | app.logout = function () { 13 | console.log('received the logout event for user: '+$scope.currentUser.email); 14 | AuthService.clearCredentials(); 15 | $location.path('/'); 16 | }; 17 | }; -------------------------------------------------------------------------------- /src/main/webapp/webui/controllers/HomeController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/13/2015. 3 | */ 4 | angular.module('App') 5 | .controller('HomeController', HomeController); 6 | 7 | function HomeController($scope, $location) { 8 | var home = this; 9 | home.currentUser = null; 10 | }; -------------------------------------------------------------------------------- /src/main/webapp/webui/controllers/LoginController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/12/2015. 3 | */ 4 | angular.module('App.Auth') 5 | .controller('LoginController', ['$scope', '$rootScope', '$location', 'AuthService', LoginController]); 6 | 7 | function LoginController($scope, $rootScope, $location, AuthService) { 8 | var lc = this; 9 | 10 | (function initController() { 11 | // reset login status 12 | AuthService.clearCredentials(); 13 | })(); 14 | 15 | lc.login = function () { 16 | console.log('received the login event for user: '+lc.user.email); 17 | lc.dataLoading = true; 18 | $rootScope.isSubmitted = true; 19 | AuthService.login(lc.user.email, lc.user.password, function (response) { 20 | if (response.code==200) { 21 | AuthService.createJWTToken(response.result.user, response.result.token); 22 | AuthService.setCredentials(); 23 | $location.path('/app'); 24 | } else { 25 | lc.error = response.result; 26 | lc.details = response.details; 27 | lc.dataLoading = false; 28 | $rootScope.isSubmitted = false; 29 | } 30 | }); 31 | }; 32 | }; -------------------------------------------------------------------------------- /src/main/webapp/webui/controllers/RegisterController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/12/2015. 3 | */ 4 | angular.module('App.Auth') 5 | .controller('RegisterController', RegisterController); 6 | 7 | RegisterController.$inject = ['$location', '$scope', '$rootScope', 'AuthService', 'FlashMessage']; 8 | function RegisterController($location, $scope, $rootScope, AuthService, FlashMessage) { 9 | var rc = this; 10 | console.log('register controller'); 11 | rc.register = function (admin) { 12 | console.log('received the register event for user: '+rc.user.username); 13 | $rootScope.isSubmitted = true; 14 | rc.dataLoading = true; 15 | rc.user.admin = admin; 16 | AuthService.register(rc.user, function (response) { 17 | if (response.code==200) { 18 | AuthService.createJWTToken(response.result.user, response.result.token); 19 | AuthService.setCredentials(); 20 | $location.path('/app'); 21 | } else { 22 | rc.error = response.result; 23 | rc.details = response.details; 24 | rc.dataLoading = false; 25 | $rootScope.isSubmitted = false; 26 | } 27 | }); 28 | }; 29 | }; -------------------------------------------------------------------------------- /src/main/webapp/webui/modules/Admin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/6/2015. 3 | */ 4 | angular.module('App.Admin', []) -------------------------------------------------------------------------------- /src/main/webapp/webui/modules/App.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/8/2015. 3 | */ 4 | angular.module('App', []) 5 | -------------------------------------------------------------------------------- /src/main/webapp/webui/modules/Auth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/13/2015. 3 | */ 4 | angular.module('App.Auth', []) -------------------------------------------------------------------------------- /src/main/webapp/webui/modules/Common.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/14/2015. 3 | */ 4 | var commonModule = angular.module('App.Common', []); 5 | 6 | commonModule.constant('BackendCfg', { 7 | url: 'http://localhost:8080', 8 | setupHttp: function(http) { 9 | http.defaults.useXDomain = true; 10 | http.defaults.withCredentials = true; 11 | } 12 | }); 13 | 14 | var compareTo = function() { 15 | return { 16 | require: "ngModel", 17 | scope: { 18 | otherModelValue: "=compareTo" 19 | }, 20 | link: function(scope, element, attributes, ngModel) { 21 | 22 | ngModel.$validators.compareTo = function(modelValue) { 23 | return modelValue == scope.otherModelValue; 24 | }; 25 | 26 | scope.$watch("otherModelValue", function() { 27 | ngModel.$validate(); 28 | }); 29 | } 30 | }; 31 | }; 32 | commonModule.directive('compareTo', compareTo); 33 | -------------------------------------------------------------------------------- /src/main/webapp/webui/modules/FlashMessage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/22/2015. 3 | */ 4 | (function () { 5 | 'use strict'; 6 | 7 | angular 8 | .module('App.Common') 9 | .factory('FlashMessage', FlashMessage); 10 | 11 | FlashMessage.$inject = ['$rootScope']; 12 | function FlashMessage($rootScope) { 13 | var service = {}; 14 | 15 | service.success = success; 16 | service.error = error; 17 | 18 | initService(); 19 | 20 | return service; 21 | 22 | function initService() { 23 | $rootScope.$on('$locationChangeStart', function () { 24 | clearFlashMessage(); 25 | }); 26 | 27 | function clearFlashMessage() { 28 | var flash = $rootScope.flash; 29 | if (flash) { 30 | if (!flash.keepAfterLocationChange) { 31 | delete $rootScope.flash; 32 | } else { 33 | // only keep for a single location change 34 | flash.keepAfterLocationChange = false; 35 | } 36 | } 37 | } 38 | } 39 | 40 | function success(message, keepAfterLocationChange) { 41 | $rootScope.flash = { 42 | message: message, 43 | type: 'success', 44 | keepAfterLocationChange: keepAfterLocationChange 45 | }; 46 | } 47 | 48 | function error(message, keepAfterLocationChange) { 49 | $rootScope.flash = { 50 | message: message, 51 | type: 'error', 52 | keepAfterLocationChange: keepAfterLocationChange 53 | }; 54 | } 55 | } 56 | 57 | })(); -------------------------------------------------------------------------------- /src/main/webapp/webui/services/AppService.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Y.Kamesh on 4/12/2015. 3 | */ 4 | -------------------------------------------------------------------------------- /src/main/webapp/webui/templates/admin.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/webapp/webui/views/access-denied.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Access Denied

5 |

 

6 |

Something is wrong with your authentication headers.

7 |

 

8 |
9 | 10 |
11 |
-------------------------------------------------------------------------------- /src/main/webapp/webui/views/common/footer.html: -------------------------------------------------------------------------------- 1 |
2 |

 

 

3 |
4 | © 2015, Kaleidosoft Labs 5 |
-------------------------------------------------------------------------------- /src/main/webapp/webui/views/common/header.html: -------------------------------------------------------------------------------- 1 | 25 |
26 |

 

 

 

-------------------------------------------------------------------------------- /src/main/webapp/webui/views/common/nfooter.html: -------------------------------------------------------------------------------- 1 |
2 |

 

 

3 |
4 | © 2015, Kaleidosoft Labs 5 |
-------------------------------------------------------------------------------- /src/main/webapp/webui/views/common/nheader.html: -------------------------------------------------------------------------------- 1 | 8 |
9 |

 

 

 

-------------------------------------------------------------------------------- /src/main/webapp/webui/views/dashboard.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 |

Dashboard

5 | 6 |
7 |
8 | -------------------------------------------------------------------------------- /src/main/webapp/webui/views/home.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

YourWebProject2

5 |

 

6 |

Your awesome motto goes here.

7 |

 

8 |

Learn more

9 |
10 | 11 |
12 |
-------------------------------------------------------------------------------- /src/main/webapp/webui/views/login.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Login

5 |
{{lc.error}}
6 |
7 |
8 |
9 | 10 | 11 | Email is required 12 | Email is invalid 13 |
14 |
15 | 16 | 17 | Password is required 18 |
19 |
20 | 21 | 22 | Register 23 |
24 |
25 |
26 |
27 |
28 |
29 | -------------------------------------------------------------------------------- /src/main/webapp/webui/views/register.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Register

5 |
{{rc.error}}
6 |
7 |
8 |
9 | 10 | 11 | Display Name is required 12 |
13 |
14 | 15 | 16 | Email is required 17 | Email is invalid 18 |
19 |
20 | 21 | 22 | Password is required 23 |
24 |
25 | 26 | 27 | Password don't match 28 |
29 |
30 | 31 | 32 | Cancel 33 |
34 |
35 |
36 |
37 |
38 |
-------------------------------------------------------------------------------- /src/test/java/yourwebproject2/BCryptPaswordEncoderTester.java: -------------------------------------------------------------------------------- 1 | package yourwebproject2; 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 4 | import org.springframework.util.Assert; 5 | 6 | /** 7 | * @author: kameshr 8 | */ 9 | public class BCryptPaswordEncoderTester { 10 | private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | String encoded = passwordEncoder.encode("Test1234"); 14 | Thread.sleep(5L * 1000L); 15 | Assert.isTrue(passwordEncoder.matches("Test1234", encoded)); 16 | Assert.isTrue(!passwordEncoder.matches("Test123ss", encoded)); 17 | Assert.isTrue(passwordEncoder.matches("Test1234", encoded)); 18 | 19 | System.out.println("Test 1: "+passwordEncoder.matches("Test1234", encoded)); 20 | System.out.println("Test 2: "+passwordEncoder.matches("Test123ss", encoded)); 21 | System.out.println("Test 3: "+passwordEncoder.matches("Test1234", encoded)); 22 | } 23 | } 24 | --------------------------------------------------------------------------------