<file_sep>package ir.saafta.repo;

import ir.saafta.model.Feedback;
import ir.saafta.model.User;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by reza on 11/14/16.
 */
public interface FeedbackRepository extends PagingAndSortingRepository<Feedback, Long> {
    void deleteAllByUser(User user);
}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.config(config);
	
	/** @ngInject */
    function config($qProvider, $logProvider, $httpProvider, $provide,
                    ADMdtpProvider, moment) {
		// Enable log
		$logProvider.debugEnabled(true);

        console.log('$qProvider.errorOnUnhandledRejections', $qProvider.errorOnUnhandledRejections);
        $qProvider.errorOnUnhandledRejections(false);
		//  @desc add $http Interceptor
		// $httpProvider.interceptors.push('authInterceptor');
		$httpProvider.defaults.withCredentials = true;
		// disable # in url
		// $locationProvider.html5Mode(true);
		
		/////////////////////////////////
		// Set options third-party lib //
		/////////////////////////////////
		
		ADMdtpProvider.setOptions({
			autoClose: true,
			calType: 'jalali',
			dtpType: 'date',
			format: 'YYYY-MM-DD'
		});
		
		// Set toastr options
		/*angular.extend(toastrConfig, {
			allowHtml: true,
			closeButton: true,
			closeHtml: '<button class="pull-left">&times;</button>',
			extendedTimeOut: 500,
			positionClass: 'toast-top-right',
			preventDuplicates: true,
			progressBar: true,
			tapToDismiss: true,
			target: 'body',
			timeOut: 3000
		});
		 */
		
		//moment
		moment.loadPersian();

        $provide.decorator('uibTabsetDirective', function ($delegate) {
            $delegate[0].templateUrl = "assets/tpl/uib-tabset-app-kit.html";
            $delegate[0].scope['tabsetClass'] = '@';
            return $delegate;
        });

        $provide.decorator('uibTabDirective', function ($delegate) {
            $delegate[0].templateUrl = "assets/tpl/uib-tab-app-kit.html";
            $delegate[0].scope['tabIconClass'] = '@';
            return $delegate;
        });

        $provide.decorator('uibAlertDirective', function ($delegate) {
            $delegate[0].templateUrl = "assets/tpl/uib-alert-app-kit.html";
            return $delegate;
        });
		
	}
	
})();
<file_sep>(function () {
	
	'use strict';
	
	/**
	 * @ngdoc directive
	 * @name app.directive:sidebar
	 * @description
	 * # sidebar
	 */
	
	angular
		.module('app')
		.directive('sidebar', sidebar);
	
	/** @ngInject */
	function sidebar() {
		return {
			templateUrl: 'app/main/sidebar/sidebar.html',
			restrict: 'E',
			replace: true,
			controller: SidebarCtrl,
			controllerAs: 'vm',
			bindToController: true // because the scope is isolated
		};
		
		/** @ngInject */
		function SidebarCtrl(sidebarService, $log, principal) {
			/* jshint validthis: true */
			var vm = this;
			vm.selectedMenu = 'dashboard';
			vm.collapseVar = 0;
			vm.multiCollapseVar = 0;
            var user = {};
            principal.identity().then(function (data) {
                user = data;
                vm.user = data;
            });
			vm.check = check;
			vm.multiCheck = multiCheck;
			vm.hasAccess = hasAccess;
			
			activate();
			
			function activate() {
                $log.info('Sidebar module activated');
				sidebarService.getSidebar().then(
					function (data) {
						vm.data = data;
					}
				);
			}
			
			function check(x) {
				if (x === vm.collapseVar) {
					vm.collapseVar = 0;
				}
				else {
					vm.collapseVar = x;
				}
			}
			
			function multiCheck(y) {
				if (y === vm.multiCollapseVar) {
					vm.multiCollapseVar = 0;
				}
				else {
					vm.multiCollapseVar = y;
				}
			}
			
			function hasAccess(authorities) {
				if (!authorities || !authorities.length) {
					return true;
				}
				else if (!user.authorities || !user.authorities.length) {
					return false;
				}
				for (var i = 0; i < authorities.length; i++) {
					for (var j = 0; j < user.authorities.length; j++) {
						if (authorities[i] === user.authorities[j].authority) {
							return true;
						}
					}
				}
				return false;
			}
			
		}
	}
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('AccessController', AccessController);
	
	/** @ngInject */
    function AccessController($log, NgTableParams, accessService, toastr, $ngConfirm, $scope) {
		var vm = this;
		vm.title = 'AccessController';
        vm.accessTable = new NgTableParams({
            page: 1,
			count: 20
		}, {
			getData: getAccesses
		});
        vm.delete = Delete;
		
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('Access module activated');

		}
		
		function getAccesses(tabelparams) {
			var params = {
                page: tabelparams.page() - 1,
				size: tabelparams.count()
			};
			return accessService.getAccesses(params).then(function (data) {
                tabelparams.total(data.totalElements);
				return data.content;
			});
		}

        function Delete(id) {
            $ngConfirm({
                title: 'حذف دسترسی',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            accessService.deleteAccess(id)
                                .then(function () {
                                    toastr.success('دسترسی با موفقیت حذف شد.');
                                    vm.accessTable.reload();
                                }, function () {
                                    toastr.error('خطا در حذف دسترسی!');
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }
		
	}
	
})();<file_sep>package ir.saafta.repo;

import ir.saafta.model.Content;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by r.kashmir on 7/16/2017.
 */
public interface ContentRepository extends PagingAndSortingRepository<Content, Long> {
}
<file_sep>package ir.saafta.web;

import ir.saafta.model.Event;
import ir.saafta.repo.EventRepository;
import ir.saafta.repo.EventSpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Reza on 11/18/2016.
 */
@RestController
@RequestMapping("/event")
public class EventController {
    private final EventRepository eventRepository;

    @Autowired
    public EventController(EventRepository eventRepository) {
        this.eventRepository = eventRepository;
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Event getById(@PathVariable Long id) {
        return eventRepository.findOne(id);
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(method = RequestMethod.PUT)
    public Page<Event> getEvents(Pageable pageable, @RequestBody EventSpec eventSpec) {
        return eventRepository.findAll(eventSpec, pageable);
    }
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CategoryController', CategoryController);

    /** @ngInject */
    function CategoryController($log, homeService, host, $timeout, $uibModal) {
        var vm = this;
        vm.title = 'CategoryController';
        vm.dashboard = {};
        activate();
        vm.slides = [
            {id: 0},
            {id: 1},
            {id: 2},
            {id: 3},
            {id: 4},
            {id: 5},
            {id: 6}
        ];
        vm.host = host;
        vm.getStarClass = getStarClass;
        vm.myInterval = 3000;
        vm.noWrapSlides = false;
        vm.responsiveSetting = [
            {
                breakpoint: 964,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: true
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: true
                }
            }
        ];
        ////////////////

        function activate() {
            $log.debug('Category module activated');
            getSpecifics();
        }

        function getSpecifics() {
            homeService.getSpecificApps().then(function (data) {
                vm.specificApps = data;
                //TODO: remove it before commit
                if (vm.specificApps.length < 7)
                    vm.specificApps = vm.specificApps.concat(data);
                if (vm.specificApps.length < 7)
                    vm.specificApps = vm.specificApps.concat(data);

                $timeout(function () {
                    var width = $('.slick-slide').css("width");
                    /*if(width) {
                     width = parseInt(width.substring(0, width.length - 2));
                     console.log(width);
                     if (width < 80) {
                     $('.slick-slide').css("width", "80px")
                     }
                     }*/
                }, 5000)
            })
        }

        function getStarClass(app, index) {
            if (app.rating - index > 1) {
                return "star";
            }
            else if (app.rating - index > 0) {
                return "star-half-o";
            } else {
                return "star-o";
            }
        }


    }

})();<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
    'use strict';

    angular
        .module('app')
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('root.comment', {
                controller: 'CommentController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/comment/list-comment.html',
                url: '/comment'
            })
            .state('root.createUpdateComment', {
                controller: 'CreateUpdateCommentController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/comment/create-update-comment.html',
                url: '/comment/:method?id'
            })

        ;
    }

})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.run(runBlock);
	
	/** @ngInject */
	function runBlock($log, $confirmModalDefaults, $window, $rootScope, ngTableDefaults, principal, $transitions) {
		
		//set confirm default
		$confirmModalDefaults.templateUrl = 'app/directives/confirm/confirm-tpl.html';
		$confirmModalDefaults.defaultLabels.title = '';
		$confirmModalDefaults.defaultLabels.ok = 'بله';
		$confirmModalDefaults.defaultLabels.cancel = 'خیر';
		$confirmModalDefaults.size = 'sm';
		
		//ng-table default
		ngTableDefaults.params.count = 20;
		ngTableDefaults.settings.counts = [10, 20, 40, 60, 80, 100];
		ngTableDefaults.settings.paginationMaxBlocks = 5;
		ngTableDefaults.settings.paginationMinBlocks = 2;


        $transitions.onStart({to: '**'}, function (trans) {
            console.log('stateChangeStart:', trans.$to());
            if (trans.$to().name !== 'login') {
                // principal.authorize();
            }
        });

        $transitions.onSuccess({to: '**'}, function (trans) {
            console.log('sstateChangeSuccess;');
            $window.scrollTo(0, 0);
        });


		
		$log.debug('runBlock end');
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.directive('fileUpload', fileUpload);
	
	/** @ngInject */
	function fileUpload() {
		var directive = {
			restrict: 'E',
			scope: {
				accept: '@',
				file: '=',
				label: '@',
				uploading: '='
			},
			templateUrl: 'app/directives/file-upload/file-upload.html'
		};
		return directive;
	}
	
})();
<file_sep>package ir.saafta.web;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import ir.saafta.model.Category;
import ir.saafta.model.Picture;
import ir.saafta.repo.CategoryRepository;
import ir.saafta.repo.PictureRepository;
import org.omg.SendingContext.RunTimeOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;

/**
 * Created by reza on 11/12/16.
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final CategoryRepository categoryRepository;
    private final PictureRepository pictureRepository;
    @Autowired
    public CategoryController(CategoryRepository categoryRepository, PictureRepository pictureRepository) {
        this.categoryRepository = categoryRepository;
        this.pictureRepository = pictureRepository;
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/", method = RequestMethod.POST, consumes = "multipart/*")
    public Category create(MultipartFile pic, String name) throws IOException, ParseException {
        if (pic == null) {
            logger.error("no picture data");
            throw new HystrixBadRequestException("Picture can not be empty");
        }
        Picture picture = new Picture(pic.getBytes(), name, "category", pic.getOriginalFilename());
        picture = pictureRepository.save(picture);
        Category category = new Category();
        category.setName(name);
        category.setPicture(picture);
        return categoryRepository.save(category);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Category getOne(@PathVariable("id") Long id) {
        return categoryRepository.findOne(id);
    }


    @RequestMapping(method = RequestMethod.GET)
    public Page<Category> getCategoriesList(Pageable pageable) {
        return categoryRepository.findAll(pageable);
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    public Iterable<Category> getAllCategories(){
        return categoryRepository.findAll();
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = "multipart/*")
    public Category update(@PathVariable Long id, MultipartFile pic, String name) throws IOException, ParseException {

        Category category = categoryRepository.findOne(id);
        Picture picture;
        if (pic != null) {
            if (category.getPicture() != null) {
                picture = pictureRepository.findOne(category.getPicture().getId());
                picture.setData(pic.getBytes());
                picture.setLabel(name);
                picture.setFormat(pic.getOriginalFilename());
            } else {
                picture = new Picture(pic.getBytes(), name, "category", pic.getOriginalFilename());
            }
            picture = pictureRepository.save(picture);
            if (category.getPicture() == null) {
                category.setPicture(picture);
            }
        }
        category.setName(name);
        return categoryRepository.save(category);
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Long id) {
        try {
            Picture picture = categoryRepository.findOne(id).getPicture();
            categoryRepository.delete(id);
            pictureRepository.delete(picture);
        } catch (org.springframework.dao.DataIntegrityViolationException exception) {
            throw new RuntimeException("Category can not be deleted due to depended information");
        }
    }
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('UserGroupController', UserGroupController);

    /** @ngInject */
    function UserGroupController($log, NgTableParams, userGroupService, util, $ngConfirm, $scope) {
        var vm = this;
        vm.title = 'UserGroupController';
        vm.userGroupTable = new NgTableParams({
            page: 1,
            count: 20
        }, {
            getData: getUserGroups
        });
        vm.delete = Delete;
        vm.update = update;
        vm.create = create;

        activate();

        ////////////////

        function activate() {
            $log.debug('UserGroup module activated');

        }

        function getUserGroups(tabelparams) {
            var params = {
                page: tabelparams.page() - 1,
                size: tabelparams.count()
            };
            angular.forEach(tabelparams.sorting(), function (value, key) {
                params.sort = key + ',' + value;
            });
            return userGroupService.getUserGroups(params).then(function (data) {
                tabelparams.total(data.totalElements);
                return data.content;
            }, function (error) {

            });
        }

        function Delete(id) {
            $ngConfirm({
                title: 'حذف گروه کاربری',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            userGroupService.deleteUserGroup(id)
                                .then(function () {
                                    util.toast('success', 'APP.MODULES.USER.MESSAGE.SUCCESS.DELETE_GROUP');
                                    vm.userGroupTable.reload();
                                    vm.loading = false;
                                }, function () {
                                    util.toast('error', 'APP.MODULES.USER.MESSAGE.FAIL.DELETE_GROUP');
                                    vm.loading = false;
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }

        function update(userGroup) {
            vm.loading = true;
            userGroupService.updateUserGroup(userGroup).then(function () {
                util.toast('success', 'APP.MODULES.USER.MESSAGE.SUCCESS.UPDATE_GROUP');
                vm.toggleEdit[userGroup.id] = false;
                vm.loading = false;
            }, function () {
                util.toast('error', 'APP.MODULES.USER.MESSAGE.FAIL.UPDATE_GROUP');
                vm.loading = false;
            })
        }

        function create() {
            vm.loading = true;
            userGroupService.createUserGroup(vm.userGroup).then(function () {
                util.toast('success', 'APP.MODULES.USER.MESSAGE.SUCCESS.CREATE_GROUP');
                vm.toggleCreate = false;
                vm.loading = false;
                vm.userGroupTable.reload();
            }, function () {
                util.toast('error', 'APP.MODULES.USER.MESSAGE.FAIL.CREATE_GROUP');
                vm.loading = false;
            })
        }

    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('UserController', UserController);
	
	/** @ngInject */
    function UserController($log, $stateParams, NgTableParams, userService, userGroupService, toastr, $uibModal,
                            util, principal, $ngConfirm, $scope) {
		var vm = this;
		vm.title = 'UserController';
        vm.groups = [];
        vm.delete = Delete;
        vm.getCaption = getCaption;
        vm.getAuthorityClass = getAuthorityClass;
        vm.showSessions = showSessions;
        vm.addUserToGroup = addUserToGroup;
        vm.remove = remove;
		activate();
		
		////////////////
		
		function activate() {
            $log.debug('User module activated', $stateParams);
            getAuthorities();
            getAllUserGroups().then(function (data) {
                data.forEach(function (group) {
                    if ($stateParams.groupId && parseInt(group.id) === parseInt($stateParams.groupId)) {
                        vm.group = group;
                        getAllUsers();
                    }
                    vm.groups.push({
                        id: group.id,
                        title: group.title
                    })
                });
                console.log(vm.groups);
                vm.userTable = new NgTableParams({
                    page: 1,
                    count: 20
                }, {
                    getData: getUsers
                });
            });
            principal.identity().then(function (data) {
                vm.me = data;
            });

		}

        function getAuthorities() {
            return userService.getAuthorities().then(function (data) {
                vm.authorities = data;
            });
        }

        function getAllUserGroups() {
            return userGroupService.getAllUserGroups();
        }

        function getAuthorityClass(authority) {
            if (authority === 'admin') {
                return "btn-success";
            }
            return "btn-default";
        }

        function getCaption(authority) {
            if (vm.authorities) {
                for (var i = 0; i < vm.authorities.length; i++) {
                    if (vm.authorities[i].authority === authority) {
                        return vm.authorities[i].caption;
                }
                }
            }
        }

        function getUsers(tabelparams) {
			var params = {
                page: tabelparams.page() - 1,
				size: tabelparams.count()
			};
            if (tabelparams.filter().username) {
                params.username = tabelparams.filter().username;
            }
            if (tabelparams.filter().name) {
                params.name = tabelparams.filter().name;
            }
            if (tabelparams.filter().family) {
                params.family = tabelparams.filter().family;
            }

            if (tabelparams.filter().enabled !== undefined) {
                params.enabled = tabelparams.filter().enabled;
            }
            // console.log('tabelparams.sorting()', tabelparams.sorting());
            if (tabelparams.filter().group !== undefined) {
                params.groupId = tabelparams.filter().group;
            } else if ($stateParams.groupId) {
                params.groupId = $stateParams.groupId;
            }

            angular.forEach(tabelparams.sorting(), function (value, key) {
                params.sort = key + ',' + value;
            });
            return userService.getUsers(params).then(function (data) {
                tabelparams.total(data.totalElements);
                vm.users = data.content;
				return data.content;
			}, function () {
                vm.users = [];
            });
		}

        function Delete(username) {
            $ngConfirm({
                title: 'حذف کاربر',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function(scope, button){
                            vm.loading = true;
                            userService.deleteUser(username).then(function () {
                                util.toast('success','APP.MODULES.USER.MESSAGE.SUCCESS.DELETE');
                                vm.userTable.reload();
                                vm.loading = false;
                            }, function (error) {
                                if(error.data.exception === 'java.lang.ArrayStoreException')
                                    util.toast('error', error.data.message);
                                else
                                    util.toast('error', 'APP.MODULES.USER.MESSAGE.FAIL.DELETE');
                                vm.loading = false;
                            });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function(scope, button){
                            return true;
                        }
                    }
                }
            });
            /*userService.deleteUser(username).then(function () {
                toastr.success('APP.MODULES.USER.MESSAGE.SUCCESS.DELETE');
                vm.userTable.reload();
            }, function () {
                toastr.error('APP.MODULES.USER.MESSAGE.FAIL.DELETE');
            });*/
        }

        function showSessions(user) {
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'app/components/user/session/sessions.html',
                controller: 'SessionsController',
                controllerAs: 'sm',
                backdrop: 'static',
                size: 'lg',
                resolve: {
                    user: function () {
                        return user;
                    }
                }
            });

            modalInstance.result.then(function () {

            });

        }

        function getAllUsers() {
            userGroupService.getNonGroupUsers($stateParams.groupId).then(function (data) {
                vm.allUsers = data;
            })
        }

        function addUserToGroup() {
            userGroupService.addUserToGroup(vm.group.id, vm.user.username).then(function (data) {
                vm.user = undefined;
                vm.allUsers = data;
                vm.userTable.reload();
            })
        }

        function remove(username) {
            if (vm.group) {
                $ngConfirm({
                    title: 'حذف کاربر از گروه',
                    content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                    scope: $scope,
                    buttons: {
                        sayBoo: {
                            text: 'بله',
                            btnClass: 'btn-blue',
                            action: function (scope, button) {
                                vm.loading = true;
                                userGroupService.removeUserFromGroup(vm.group.id, username).then(function (data) {
                                    util.toast('success', 'APP.MODULES.USER.MESSAGE.SUCCESS.REMOVE_USER_FROM_GROUP');
                                    vm.allUsers = data;
                                    vm.userTable.reload();
                                    vm.loading = false;
                                }, function () {
                                    util.toast('error', 'APP.MODULES.USER.MESSAGE.FAIL.REMOVE_USER_FROM_GROUP');
                                    vm.loading = false;
                                });
                                return true;
                            }
                        },
                        somethingElse: {
                            text: 'خیر',
                            btnClass: 'btn-orange',
                            action: function (scope, button) {
                                return true;
                            }
                        }
                    }
                });

            }
        }

	}
	
})();<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
	'use strict';
	
	angular
		.module('app')
		.config(routeConfig);
	
	/** @ngInject */
	function routeConfig($stateProvider) {
		$stateProvider
            .state('root.access', {
				controller: 'AccessController',
				controllerAs: 'vm',
				data: {
					roles: [
						"admin"
					]
				},
				resolve: {},
                templateUrl: 'app/components/access/list-access.html',
                url: '/access'
            })
            .state('root.createUpdateAccess', {
                controller: 'CreateUpdateAccessController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/access/create-update-access.html',
                url: '/access/:method?id'
			})
		
		;
	}
	
})();
<file_sep>package ir.saafta.repo;

import ir.saafta.model.Attempt;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface AttemptRepository extends PagingAndSortingRepository<Attempt, String> {
}
<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
	'use strict';
	
	angular
		.module('app')
		.config(routeConfig);
	
	/** @ngInject */
	function routeConfig($stateProvider) {
		$stateProvider
			.state('root.user', {
				controller: 'UserController',
				controllerAs: 'vm',
				data: {
					roles: [
						"admin"
					]
				},
				resolve: {},
				templateUrl: 'app/components/user/list-user.html',
				url: '/user'
			})
			.state('root.createUpdateUser', {
				controller: 'CreateUpdateUserController',
				controllerAs: 'vm',
				data: {
					roles: [
						"admin"
					]
				},
				resolve: {},
				templateUrl: 'app/components/user/create-update-user.html',
				url: '/user/:method/:username'
			})
		
		;
	}
	
})();
<file_sep>package ir.saafta.model;

import java.io.Serializable;

/**
 * User: <NAME>
 */

@SuppressWarnings("unused")
public class AuthorityPK implements Serializable {
    private String username;
    private String authority;

    public AuthorityPK(String username, String authority) {
        this.username = username;
        this.authority = authority;
    }

    public AuthorityPK() {
    }
}
<file_sep>apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'application'
mainClassName = 'ir.saafta.SbazaarApplication'
jar {
	baseName = 'sbazaar'
	version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
//	mavenLocal()
}

dependencies {
	compile('org.springframework.boot:spring-boot-starter-data-jpa:1.4.2.RELEASE')
	compile('org.springframework.boot:spring-boot-starter-web:1.4.2.RELEASE')
	compile('org.springframework.boot:spring-boot-starter-security:1.4.2.RELEASE')
	compile('com.github.mkopylec:recaptcha-spring-boot-starter:1.3.8')
	compile('io.jsonwebtoken:jjwt:0.7.0')
	compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.40'
	compile 'io.springfox:springfox-swagger2:2.6.1'
	compile 'io.springfox:springfox-swagger-ui:2.6.1'
	compile 'org.springframework.cloud:spring-cloud-starter-zuul:1.2.2.RELEASE'
	compile 'org.apache.tika:tika:0.3'
	compile group: 'org.apache.tika', name: 'tika-core', version: '1.15'
	compile group: 'com.github.cage', name: 'cage', version: '1.0'
	compile group: 'org.springframework.session', name: 'spring-session', version: '1.3.3.RELEASE'
	compile group: 'com.hazelcast', name: 'hazelcast', version: '3.9.4'
	compile group: 'com.github.ulisesbocchio', name: 'jasypt-spring-boot-starter', version: '1.16'

	testCompile('org.springframework.boot:spring-boot-starter-test:1.4.2.RELEASE')
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateCategoryController', CreateUpdateCategoryController);

    /** @ngInject */
    function CreateUpdateCategoryController($log, $timeout, categoryService, $stateParams, toastr, $state, host) {
        var vm = this;
        vm.title = 'CreateUpdateUserController';
        vm.host = host;
        vm.method = $stateParams.method;
        vm.category = {
            id: $stateParams.id
        };

        vm.save = save;
        vm.reset = reset;
        vm.date = new Date();
        activate();

        ////////////////

        function activate() {
            $log.debug('Category module activated');
            getCategory();
        }

        function save() {

            switch (vm.method) {
                case 'create':
                    categoryService.createCategory(vm.category.name, vm.cropper.croppedImage)
                        .then(function (data) {
                            $timeout(function () {
                                $state.go('root.category');
                            }, 3000);
                            toastr.success('دسته‌بندی با موفقیت افزوده شد.');
                        }, function () {
                            toastr.error('خطا در ایجاد دسته‌بندی!');
                        });
                    break;
                case 'update':
                    console.log('save ', vm.category);
                    var croppedImage = vm.cropper ? vm.cropper.croppedImage : null;
                    categoryService.updateCategory(vm.category.id, vm.category.name, croppedImage)
                        .then(function (data) {
                            vm.category = data;
                            toastr.success('دسته‌بندی با موفقیت ویرایش شد.');
                            vm.date = new Date();
                            vm.cropper = null;
                        }, function () {
                            toastr.error('خطا در ویرایش دسته‌بندی!');
                        });
                    break;
            }
        }



        function reset() {
            switch (vm.method) {
                case 'create':
                    vm.category = {};
                    break;
                case 'update':
                    getCategory();
            }
        }

        function getCategory() {
            if (vm.category.id) {
                categoryService.getCategory(vm.category.id).then(function (data) {
                    vm.category = data;
                });
            }
        }


    }

})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('ApplicationController', ApplicationController);

    /** @ngInject */
    function ApplicationController($log, $q, $stateParams, NgTableParams, applicationService, util, categoryService,
                                   ownerService, userService, userGroupService, host, $ngConfirm, $scope) {
        var vm = this;
        vm.title = 'ApplicationController';
        vm.host = host;
        vm.delete = Delete;
        vm.statuses = [
            {'id': 'DEACTIVATED', 'title': 'غیرفعال'},
            {'id': 'PUBLIC', 'title': 'عمومی'},
            {'id': 'LAUNCHER', 'title': 'پوسته امن'},
            {'id': 'NON_LAUNCHER', 'title': 'پوسته عادی'}
        ];
        activate();

        ////////////////

        function activate() {
            $log.debug('Application module activated');
            $q.all([getCategories(), getOwners(), getUsers()]).then(function (data) {
                vm.categories = data[0];
                vm.owners = data[1];
                vm.users = data[2];

                vm.categories.forEach(function (category) {
                    category.title = category.name;
                });
                // vm.categories.push({title: 'انتخاب و جستجو بر اساس دسته‌بندی...'});
                vm.owners.forEach(function (owner) {
                    owner.title = owner.name;
                });
                // vm.owners.push({title: 'انتخاب و جستجو بر اساس شرکت...'});
                vm.users.forEach(function (user) {
                    user.title = user.completeName + ' (' + user.username + ')';
                    user.id = user.username;
                });
                // vm.users.push({title: 'انتخاب و جستجو بر اساس کاربر...'});

                console.log('vm.categories', vm.categories);
                vm.applicationTable = new NgTableParams({
                    page: 1,
                    count: 20
                }, {
                    getData: getApplications
                });
            });
            getGroup();
        }

        function getApplications(tabelparams) {
            // console.log(tabelparams.filter());
            var params = {
                page: tabelparams.page() - 1,
                size: tabelparams.count()
            };
            var data = {};
            if(tabelparams.filter().name)
                data.name = tabelparams.filter().name;
            if (tabelparams.filter().status)
                data.statuses = [tabelparams.filter().status];
            if(tabelparams.filter().appPackage)
                data.appPackage = tabelparams.filter().appPackage;
            if(tabelparams.filter().fee)
                data.fee = tabelparams.filter().fee;
            if(tabelparams.filter().category)
                data.category = {id: tabelparams.filter().category};
            if (tabelparams.filter().owner)
                data.ownerId = tabelparams.filter().owner;
            if(tabelparams.filter().user)
                data.username = tabelparams.filter().user;
            if (tabelparams.filter().disabled !== undefined)
                data.disabled = tabelparams.filter().disabled;
            if ($stateParams.groupId)
                data.group = {id: $stateParams.groupId}
            return applicationService.getApplications(data, params).then(function (data) {
                data.content.forEach(function (app) {
                    app.user = vm.users.filter(function (user) {
                        return user.username === app.userId;
                    })[0];
                    app.owner = vm.owners.filter(function (owner) {
                        return owner.id === app.ownerId;
                    })[0];
                    app.installationCount = app.installationCount || 0;
                });
                tabelparams.total(data.totalElements);
                return data.content;
            });
        }

        function Delete(id) {
            $ngConfirm({
                title: 'حذف برنامه',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            applicationService.deleteApplication(id).then(function () {
                                vm.applicationTable.reload();
                                util.toast('success', 'برنامه با موفقیت حذف شد.');
                                vm.loading = false;
                            }, function (error) {
                                if (error.data && error.data.message)
                                    util.toast('error', error.data.message);
                                else
                                    util.toast('error', 'خطا در حذف برنامه!');
                                vm.loading = false;
                            });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }

        function getCategories() {
            return categoryService.getAllCategories();
        }

        function getOwners() {
            return ownerService.getAllOwners();
        }

        function getUsers() {
            return userService.getAllUsers();
        }

        function getGroup() {
            if ($stateParams.groupId)
                userGroupService.getUserGroup($stateParams.groupId).then(function (data) {
                    vm.group = data;
                }, function (error) {
                    util.toast('error', 'گروه مورد نظر یافت نشد!');
                });
        }

    }

})();<file_sep>/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.10-log : Database - sbazaar
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`sbazaar` /*!40100 DEFAULT CHARACTER SET utf8 */;

/*Table structure for table `access` */

DROP TABLE IF EXISTS `access`;

CREATE TABLE `access` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(50) DEFAULT NULL,
  `description` text,
  `label` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `access_file` */

DROP TABLE IF EXISTS `access_file`;

CREATE TABLE `access_file` (
  `id` bigint(20) unsigned NOT NULL,
  `access_id` bigint(20) NOT NULL,
  `file_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_access_file_file` (`file_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `advertisement` */

DROP TABLE IF EXISTS `advertisement`;

CREATE TABLE `advertisement` (
  `id`         BIGINT(20) NOT NULL,
  `url`        VARCHAR(50) DEFAULT NULL,
  `picture_id` BIGINT(20)  DEFAULT NULL,
  `user_id`    VARCHAR(50) DEFAULT NULL,
  `fromDate`   DATETIME    DEFAULT NULL,
  `toDate`     DATETIME    DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `application` */

DROP TABLE IF EXISTS `application`;

CREATE TABLE `application` (
  `id`           bigint(20) unsigned NOT NULL,
  `app_package`  varchar(255)        DEFAULT NULL,
  `fee`          int(11)             DEFAULT NULL,
  `name`         varchar(255)        DEFAULT NULL,
  `category_id`  bigint(20) unsigned DEFAULT NULL,
  `company_id`   bigint(20) unsigned DEFAULT NULL,
  `logo_id`      bigint(20) unsigned DEFAULT NULL,
  `user_id`      varchar(50)         DEFAULT NULL,
  `create_date`  datetime            DEFAULT NULL,
  `last_update`  datetime            DEFAULT NULL,
  `specific_app` binary(1)           DEFAULT '0',
  `banner_id`    bigint(20) unsigned DEFAULT NULL,
  `new_app`      BINARY(1)           DEFAULT '0',
  `last_file_id` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unque` (`app_package`),
  KEY `foreign_key_application_picture` (`logo_id`),
  KEY `foreign_key_application_company` (`company_id`),
  KEY `foreign_key_application_category` (`category_id`),
  KEY `foreign_key_application_picture_2` (`banner_id`),
  KEY `foreign_key_application_file` (`last_file_id`),
  CONSTRAINT `foreign_key_application_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_company` FOREIGN KEY (`company_id`) REFERENCES `owner` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_picture` FOREIGN KEY (`logo_id`) REFERENCES `picture` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_picture_2` FOREIGN KEY (`banner_id`) REFERENCES `picture` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `authorities` */

DROP TABLE IF EXISTS `authorities`;

CREATE TABLE `authorities` (
  `username` varchar(50) NOT NULL,
  `authority` varchar(45) NOT NULL,
  PRIMARY KEY (`username`,`authority`),
  KEY `fk_authoroties_1_idx` (`username`),
  CONSTRAINT `fk_authoroties_1` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `category` */

DROP TABLE IF EXISTS `category`;

CREATE TABLE `category` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `picture_id` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_category_picture` (`picture_id`),
  CONSTRAINT `foreign_key_category_picture` FOREIGN KEY (`picture_id`) REFERENCES `picture` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Table structure for table `comment` */

DROP TABLE IF EXISTS `comment`;

CREATE TABLE `comment` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `content` varchar(255) DEFAULT NULL,
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `user_id` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_comment_contetn` (`content_id`),
  CONSTRAINT `foreign_key_comment_contetn` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `owner` */

DROP TABLE IF EXISTS `owner`;

CREATE TABLE `owner` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Table structure for table `content` */

DROP TABLE IF EXISTS `content`;

CREATE TABLE `content` (
  `id`          BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `description` text,
  `seen_count`  INT(11) UNSIGNED             DEFAULT '0',
  `title`       VARCHAR(255)                 DEFAULT NULL,
  `type`        VARCHAR(255)                 DEFAULT NULL,
  `DTYPE`       VARCHAR(45)                  DEFAULT NULL,
  `rating`      DOUBLE                       DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Table structure for table `feedback` */

DROP TABLE IF EXISTS `feedback`;

CREATE TABLE `feedback` (
  `id`         BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `date`       DATETIME                     DEFAULT NULL,
  `liked`      TINYINT(1)                   DEFAULT '0',
  `disliked`   TINYINT(1)                   DEFAULT '0',
  `rate`       INT(11)                      DEFAULT '0',
  `content_id` BIGINT(20) UNSIGNED          DEFAULT NULL,
  `username`   VARCHAR(50)                  DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_feedback_content` (`content_id`),
  KEY `foreign_key_feedback_user` (`username`),
  CONSTRAINT `foreign_key_feedback_content` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_feedback_user` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `file` */

DROP TABLE IF EXISTS `file`;

CREATE TABLE `file` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `application_id` bigint(20) DEFAULT NULL,
  `data` longblob,
  `description` text,
  `name` varchar(255) DEFAULT NULL,
  `registration_date` datetime DEFAULT NULL,
  `size` int(11) DEFAULT NULL,
  `version` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 23
  DEFAULT CHARSET = utf8;

/*Table structure for table `news` */

DROP TABLE IF EXISTS `news`;

CREATE TABLE `news` (
  `id` bigint(20) unsigned NOT NULL,
  `context` text,
  `main_picture_id` bigint(20) DEFAULT NULL,
  `date` datetime NOT NULL,
  `content_id` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `picture` */

DROP TABLE IF EXISTS `picture`;

CREATE TABLE `picture` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `data` longblob,
  `label` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `published` tinyint(1) DEFAULT NULL,
  `format` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_picture_content` (`content_id`),
  CONSTRAINT `foreign_key_picture_content` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 27
  DEFAULT CHARSET = utf8;

/*Table structure for table `role` */

DROP TABLE IF EXISTS `role`;

CREATE TABLE `role` (
  `authority` VARCHAR(50) NOT NULL,
  `caption`   VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY (`authority`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

/*Table structure for table `transaction` */

DROP TABLE IF EXISTS `transaction`;

CREATE TABLE `transaction` (
  `id`             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `date`           DATETIME                     DEFAULT NULL,
  `amount`         INT(11)                      DEFAULT NULL,
  `type`           VARCHAR(20)                  DEFAULT NULL,
  `app_id`         BIGINT(20) UNSIGNED          DEFAULT NULL,
  `transaction_id` BIGINT(20) UNSIGNED          DEFAULT NULL,
  `reference_id`   BIGINT(20) UNSIGNED          DEFAULT NULL,
  `username`       VARCHAR(50)                  DEFAULT NULL,
  `comment`        VARCHAR(1024)                DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `transaction_fk1_username` (`username`),
  KEY `transaction_fk2_appId` (`app_id`),
  CONSTRAINT `transaction_fk1_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
    ON DELETE NO ACTION
    ON UPDATE CASCADE,
  CONSTRAINT `transaction_fk2_appId` FOREIGN KEY (`app_id`) REFERENCES `content` (`id`)
    ON DELETE NO ACTION
    ON UPDATE CASCADE
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 11
  DEFAULT CHARSET = utf8;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `username`           VARCHAR(50) NOT NULL,
  `password`           VARCHAR(60) NOT NULL,
  `enabled`            TINYINT(4)          DEFAULT '1',
  `name`               VARCHAR(45)         DEFAULT NULL,
  `family`             VARCHAR(45)         DEFAULT NULL,
  `address`            VARCHAR(45)         DEFAULT NULL,
  `mobile_phone`       VARCHAR(13)         DEFAULT NULL,
  `mobile_phone_two`   VARCHAR(13)         DEFAULT NULL,
  `mobile_phone_three` VARCHAR(13)         DEFAULT NULL,
  `phone`              VARCHAR(14)         DEFAULT NULL,
  `postal_code`        VARCHAR(45)         DEFAULT NULL,
  `email`              VARCHAR(45)         DEFAULT NULL,
  `profile_id`         BIGINT(20) UNSIGNED DEFAULT NULL,
  `credit`             INT(11)             DEFAULT '0',
  `score`              INT(11)             DEFAULT '0',
  `imei`               VARCHAR(40)         DEFAULT NULL,
  PRIMARY KEY (`username`),
  KEY `user_fk1_profile_pic` (`profile_id`),
  CONSTRAINT `user_fk1_profile_pic` FOREIGN KEY (`profile_id`) REFERENCES `picture` (`id`)
    ON DELETE NO ACTION
    ON UPDATE CASCADE
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

/*Table structure for table `user_app` */

DROP TABLE IF EXISTS `user_app`;

CREATE TABLE `user_app` (
  `id`              BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `username`        VARCHAR(50)                  DEFAULT NULL,
  `app_id`          BIGINT(20) UNSIGNED          DEFAULT NULL,
  `install_date`    DATETIME                     DEFAULT NULL,
  `uninstall_date`  DATETIME                     DEFAULT NULL,
  `phone_number`    VARCHAR(14)                  DEFAULT NULL,
  `current_version` VARCHAR(255)                 DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_app_fk1_username` (`username`),
  KEY `user_app_fk2_app_id` (`app_id`),
  CONSTRAINT `user_app_fk1_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `user_app_fk2_app_id` FOREIGN KEY (`app_id`) REFERENCES `content` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 2
  DEFAULT CHARSET = utf8;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>package ir.saafta.model;

import ir.saafta.dto.ApplicationStatus;
import ir.saafta.dto.SessionStatus;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Value;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DefaultValue;
import java.util.*;

/**
 * Created by reza on 11/12/16.
 */
@Entity
public class Application extends Content {

    @OneToMany(mappedBy = "applicationId")
    private Collection<File> files;
    @NotNull
    private String appPackage;
    @DefaultValue("0")
    private Integer fee;
    private Boolean inAppPayment;
    @NotNull
    private String name;
    private Date createDate;
    private Date lastUpdate;
    private Boolean specificApp;
    private Boolean newApp;
    private Boolean recentlyUpdated;
    @Value("${suggestedApp:false}")
    private Boolean suggestedApp;
    private Integer suggestionPriority;
    /*@ManyToOne
    @JoinColumn(name = "suggestionPriority")
    private SuggestionPriority suggestionPriority;*/
    @ManyToOne
    @JoinColumn(name = "categoryId")
    private Category category;
    @ManyToOne
    @JoinColumn(name = "ownerId")
    private Owner owner;
    @OneToOne
    @JoinColumn(name = "logoId")
    private Picture logo;
    @OneToOne
    @JoinColumn(name = "bannerId")
    private Picture banner;
    @ManyToOne
    @JoinColumn(name = "userId")
    private User user;
    private Long lastFileId;
    private Integer installationCount;
    @Transient
    private Double userRating;
    @Transient
    private Boolean userBookmarked;
    @Transient
    private Boolean isMine;
    private String originalName;
    @Enumerated(EnumType.ORDINAL)
    private ApplicationStatus status;

    public Boolean checkIncomplete() {
        return this.logo == null || this.getPictures() == null || this.getPictures().size() == 0;
    }

    public String getAppPackage() {
        return appPackage;
    }

    public void setAppPackage(String appPackage) {
        this.appPackage = appPackage;
    }

    public Integer getFee() {
        return fee;
    }

    public void setFee(Integer fee) {
        this.fee = fee;
    }

    public Boolean getInAppPayment() {
        return inAppPayment;
    }

    public void setInAppPayment(Boolean inAppPayment) {
        this.inAppPayment = inAppPayment;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        super.setTitle(name);
    }

    public Category getCategory() {
        return category;
    }

    @Required
    public void setCategory(Category category) {
        this.category = category;
    }

    public Picture getLogo() {
        return logo;
    }

    public void setLogo(Picture logo) {
        this.logo = logo;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Owner getOwner() {
        return owner;
    }

    public void setOwner(Owner owner) {
        this.owner = owner;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Date lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public Collection<File> getFiles() {
        return files;
    }

    public void setFiles(Collection<File> files) {
        this.files = files;
    }

    @Override
    public Collection<Picture> getPictures() {
        if (super.getPictures() == null || super.getPictures().size() == 0)
            return null;
        ArrayList<Picture> sPictures = new ArrayList<>(super.getPictures());
        sPictures.removeIf(pic -> !pic.getType().matches("app"));
        return sPictures;
    }

    public Boolean getSpecificApp() {
        return specificApp;
    }

    public void setSpecificApp(Boolean specificApp) {
        this.specificApp = specificApp;
    }

    public Picture getBanner() {
        return banner;
    }

    public void setBanner(Picture banner) {
        this.banner = banner;
    }

    public Boolean getNewApp() {
        return newApp;
    }

    public void setNewApp(Boolean newApp) {
        this.newApp = newApp;
    }

    public Long getLastFileId() {
        return lastFileId;
    }

    public void setLastFileId(Long lastFileId) {
        this.lastFileId = lastFileId;
    }

    @Transient
    public File getLastFile() {
        if (this.lastFileId != null) {
            for (File file : this.files) {
                if (file.getId().equals(this.lastFileId))
                    return file;
            }
            return null;
        } else {
            return calculateLastFile(null);
        }
        /*List<File> files = (List<File>) this.files;
        if (files == null || files.size() == 0)
            return null;
        files.sort(Comparator.comparing(File::getRegistrationDate).reversed());
        if (files.size() > 0)
            return files.get(0);
        return null;*/
    }

    @Transient
    public File calculateLastFile(Long removedFileId) {
        List<File> files = (List<File>) this.files;
        if (files == null || files.size() == 0)
            return null;
        files.sort(Comparator.comparing(File::getRegistrationDate).reversed());

        for (File file : files) {
            if (!file.getId().equals(removedFileId))
                return file;
        }

        return null;
    }

    public Boolean getRecentlyUpdated() {
        return recentlyUpdated;
    }

    public void setRecentlyUpdated(Boolean recentlyUpdated) {
        this.recentlyUpdated = recentlyUpdated;
    }

    public Integer getInstallationCount() {
        return installationCount;
    }

    public void setInstallationCount(Integer installationCount) {
        this.installationCount = installationCount;
    }

    public Boolean getSuggestedApp() {
        return suggestedApp;
    }

    public void setSuggestedApp(Boolean suggestedApp) {
        this.suggestedApp = suggestedApp;
    }

    public Integer getSuggestionPriority() {
        return suggestionPriority;
    }

    public void setSuggestionPriority(Integer suggestionPriority) {
        this.suggestionPriority = suggestionPriority;
    }

    public void decreaseSuggestionPriority() {
        if (this.suggestionPriority != null)
            this.suggestionPriority++;
    }

    @Transient
    public String getInstallUrl() {
        return "download/" + super.getId() + "/" + this.appPackage + ".apk";
    }

    @Transient
    public Double getUserRating() {
        return userRating;
    }

    public void setUserRating(Double userRating) {
        this.userRating = userRating;
    }

    @Transient
    public Boolean getUserBookmarked() {
        return userBookmarked;
    }

    public void setUserBookmarked(Boolean userBookmarked) {
        this.userBookmarked = userBookmarked;
    }

    @Transient
    public boolean isMyApp(User user) {
        return user != null && this.user != null && this.user.equals(user);
    }

    @Transient
    public Boolean getMine() {
        return isMine;
    }

    public void setMine(Boolean mine) {
        isMine = mine;
    }

    public String getOriginalName() {
        return originalName;
    }

    public void setOriginalName(String originalName) {
        this.originalName = originalName;
    }

    public ApplicationStatus getStatus() {
        return status;
    }

    public void setStatus(ApplicationStatus status) {
        this.status = status;
    }
}
<file_sep>package ir.saafta.repo;


import ir.saafta.model.User;
import ir.saafta.model.UserGroup;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by reza on 11/12/16.
 */
public interface UserRepository extends PagingAndSortingRepository<User, String>, JpaSpecificationExecutor<User> {
    Iterable<User> findAllByUserGroupsIsNotContaining(UserGroup userGroup);
    User findByEmail(String email);

    User findByMobilePhone(String mobilePhone);

    User findByEmailAndUsernameIsNot(String email, String username);

    User findByMobilePhoneAndUsernameIsNot(String mobilePhone, String username);
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateNewsController', CreateUpdateNewsController);

    /** @ngInject */
    function CreateUpdateNewsController($log, $timeout, newsService, $stateParams, toastr, $state, host) {
        var vm = this;
        vm.title = 'CreateUpdateUserController';
        vm.host = host;
        vm.method = $stateParams.method;
        vm.news = {
            id: $stateParams.id
        };

        vm.save = save;
        vm.reset = reset;
        vm.mainPicture = mainPicture;
        vm.date = new Date();
        activate();

        ////////////////

        function activate() {
            $log.debug('News module activated');
            getNews();
        }

        function save() {
            vm.loading = true;
            switch (vm.method) {
                case 'create':
                    vm.news.seenCount = 0;
                    newsService.createNews(vm.news)
                        .then(function (response) {
                            console.log(response);
                            $timeout(function () {
                                $state.go('root.createUpdateNews', {method: 'update', id: response.data.id});
                                vm.loading = false;
                            }, 3000);
                            toastr.success('خبر با موفقیت افزوده شد.');
                        }, function () {
                            toastr.error('خطا در ایجاد خبر!');
                            vm.loading = false;
                        });
                    break;
                case 'update':
                    newsService.updateNews(vm.news)
                        .then(function (data) {
                            vm.news = data;
                            toastr.success('خبر با موفقیت ویرایش شد.');
                            vm.loading = false;
                        }, function () {
                            toastr.error('خطا در ویرایش خبر!');
                            vm.loading = false;
                        });
                    break;
                default:
                    vm.loading = false;
            }
        }

        function mainPicture() {
            vm.loading = true;
            newsService.mainPicture(vm.news.id, vm.cropper.croppedImage).then(
                function (data) {
                    vm.news = data;
                    vm.date = new Date();
                    vm.cropper = null;
                    vm.loading = false;
                    toastr.success('تصویر خبر با موفقیت به‌روزرسانی شد.');
                }
            );
        }

        function reset() {
            switch (vm.method) {
                case 'create':
                    vm.news = {};
                    break;
                case 'update':
                    getNews();
            }
        }

        function getNews() {
            if (vm.news.id) {
                vm.loading = true;
                newsService.getNews(vm.news.id).then(function (data) {
                    vm.loading = false;
                    vm.news = data;
                }, function () {
                    vm.loading = false;
                });
            }
        }


    }

})();<file_sep>package ir.saafta.web;

import ir.saafta.exception.HttpUnauthorizedException;
import ir.saafta.model.Application;
import ir.saafta.model.User;
import ir.saafta.repo.ApplicationRepository;
import ir.saafta.repo.CategoryRepository;
import ir.saafta.repo.OwnerRepository;
import ir.saafta.service.UserDetailManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by reza on 12/3/16.
 */
@RestController
@RequestMapping("/dashboard")
public class DashboardController {
    private final String simurghPackage = "ir.simorghmarket.simorgh";
    private ApplicationRepository applicationRepository;
    private CategoryRepository categoryRepository;
    private OwnerRepository ownerRepository;
    private UserDetailManager userDetailManager;

    @Autowired
    public DashboardController(ApplicationRepository applicationRepository, UserDetailManager userDetailManager,
                               CategoryRepository categoryRepository, OwnerRepository ownerRepository) {
        this.applicationRepository = applicationRepository;
        this.categoryRepository = categoryRepository;
        this.ownerRepository = ownerRepository;
        this.userDetailManager = userDetailManager;
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Object> dashboard() {
        Map result = new HashMap<String, Object>();
        int minus = 0;
        minus += applicationRepository.countApplicationsByAppPackage(simurghPackage);

        result.put("applications", applicationRepository.count() - minus);
        result.put("users", userDetailManager.count());
        result.put("categories", categoryRepository.count());
        result.put("owners", ownerRepository.count());
        return result;
    }

    @PreAuthorize("isAuthenticated()")
    @RequestMapping(value = "/me", method = RequestMethod.GET)
    public Map<String, Object> myDashboard(Authentication authentication) {
        if(authentication == null){
            throw new HttpUnauthorizedException();
        }
        User user = (User) userDetailManager.loadUserByUsername(authentication.getName());
        Map result = new HashMap<String, Object>();
        result.put("applications", applicationRepository.findAllByUser(user).size());
        result.put("credit", user.getCredit() == null ? 0 : user.getCredit());
        result.put("averageRating", getAverageRating(applicationRepository.findAllByUser(user)));
        return result;
    }

    Double getAverageRating(Collection<Application> apps) {
        if(apps.isEmpty())
            return 0.0;
        Double result = 0.0;
        for (Application app : apps) {
            app.setRating(app.getRating() == null ? 0 : app.getRating());
            result += app.getRating();
        }
        return  result/apps.size();
    }
}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('MainController', MainController);
	
	/** @ngInject */
	function MainController($document, $window) {
		var vm = this;
		var firstLogin = $document[0].cookie.replace(
			/(?:(?:^|.*;\s*)firstLogin\s*\=\s*([^;]*).*$)|^.*$/, '$1'
		);

		activate();
		
		function activate() {
			if (!firstLogin) {
				$document[0].cookie = 'firstLogin=true';
			}
			vm.isIE = detectIE();

		}
        function detectIE() {
            var ua = window.navigator.userAgent;

            // Test values; Uncomment to check result …

            // IE 10
            // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

            // IE 11
            // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

            // Edge 12 (Spartan)
            // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

            // Edge 13
            // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

            var msie = ua.indexOf('MSIE ');
            if (msie > 0) {
                // IE 10 or older => return version number
                return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
            }

            var trident = ua.indexOf('Trident/');
            if (trident > 0) {
                // IE 11 => return version number
                var rv = ua.indexOf('rv:');
                return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
            }

            var edge = ua.indexOf('Edge/');
            if (edge > 0) {
                // Edge (IE 12+) => return version number
                return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
            }

            // other browser
            return false;
        }
	}
})();
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('applicationService', applicationService);

    /** @ngInject */
    function applicationService($log, $http, host) {
        var base = host + 'application/';
        return {
            getApplication: getApplication,
            getSimurgh: getSimurgh
        };

        ////////////////

        function getApplication(id) {
            return $http.get(base + id);
        }

        function getSimurgh(params) {
            var url = base + 'simorgh';
            return $http.get(url, {params: {type: 'nonLuncher'}})
                .then(successCallback);
        }

        function successCallback(response) {
            return response.data;
        }
    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('auth')
		.controller('RegisterController', RegisterController);
	
	/** @ngInject */
	function RegisterController($log) {
		var vm = this;
		vm.title = 'RegisterController';
		
		activate();
		
		////////////////
		
		function activate() {
			$log.info('register module ativated.');
		}
	}
	
})();
<file_sep>package ir.saafta.component;

import ir.saafta.model.SpringSession;
import ir.saafta.model.User;
import ir.saafta.repo.SpringSessionRepository;
import ir.saafta.repo.UserRepository;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.properties.EncryptableProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Properties;

@Component
public class InitializingSessionRegistry implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(InitializingSessionRegistry.class);

    @Autowired
    private SpringSessionRepository springSessionRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    @Qualifier("sessionRegistry")
    private SessionRegistry sessionRegistry;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("Initializing session registry " + springSessionRepository.findAllByPrincipalNameIsNotNull().size());
        for (SpringSession springSession : springSessionRepository.findAllByPrincipalNameIsNotNull()) {
            if (sessionRegistry.getSessionInformation(springSession.getSessionId()) == null) {
                log.info(springSession.getSessionId() + " is not registered!");
                User user = userRepository.findOne(springSession.getPrincipalName());
                sessionRegistry.registerNewSession(springSession.getSessionId(), user);
            }
        }
        log.info(sessionRegistry.getAllPrincipals().toString());
    }
}
<file_sep>package ir.saafta.service;

import ir.saafta.model.UserGroup;
import ir.saafta.repo.UserGroupRepository;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by sft940026 on 14/09/2017.
 */
@Component
public class UserGroupService {

    private final UserGroupRepository userGroupRepository;

    @Autowired
    public UserGroupService(UserGroupRepository userGroupRepository) {
        this.userGroupRepository = userGroupRepository;
    }

    public UserGroup getPublicGroup() {
        return  userGroupRepository.findOne(1L);
    }

    public UserGroup getById(Long id) {
        return userGroupRepository.findOne(id);
    }
}
<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
    'use strict';

    angular
        .module('app')
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('root.event', {
                controller: 'EventController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/event/list-event.html',
                url: '/event?category'
            })
        ;
    }

})();
<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
    'use strict';

    angular
        .module('app')
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('root.news', {
                controller: 'NewsController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/news/list-news.html',
                url: '/news'
            })
            .state('root.createUpdateNews', {
                controller: 'CreateUpdateNewsController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/news/create-update-news.html',
                url: '/news/:method?id'
            })

        ;
    }

})();
<file_sep>(function () {
	
	'use strict';
	
	/**
	 * @ngdoc service
	 * @name app.service:sidebarService
	 * @description
	 * # sidebarService
	 */
	
	angular
		.module('app')
		.service('sidebarService', sidebarService);
	
	/** @ngInject */
	function sidebarService($http) {
		/* jshint validthis: true */
		this.getSidebar = getSidebar;
		
		//////////
		
		function getSidebar() {
			return $http.get('data/sidebar.json').then(successCallback)
		}
		
		function successCallback(response) {
			return response.data;
		}
	}
})();<file_sep>package ir.saafta.model;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by reza on 11/14/16.
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Feedback {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Date date;
    private Boolean liked;
    private Boolean disliked;
    private Double rate;
    private Long contentId;
    @ManyToOne
    @JoinColumn(name = "username")
    private User user;

    public Feedback() {
    }

    public Feedback(Date date, Boolean like, Boolean disliked, Double rate, Long contentId, User user) {
        this.date = date;
        this.liked = like;
        this.disliked = disliked;
        this.rate = rate;
        this.contentId = contentId;
        this.user = user;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Boolean getLiked() {
        return liked;
    }

    public void setLiked(Boolean liked) {
        this.liked = liked;
    }

    public Boolean getDisliked() {
        return disliked;
    }

    public void setDisliked(Boolean disliked) {
        this.disliked = disliked;
    }

    public Double getRate() {
        return rate;
    }

    public void setRate(Double rate) {
        this.rate = rate;
    }

    public Long getContentId() {
        return contentId;
    }

    public void setContentId(Long contentId) {
        this.contentId = contentId;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
<file_sep>package ir.saafta.conf;

import ir.saafta.dto.SessionStatus;
import ir.saafta.model.Session;
import ir.saafta.repo.MySessionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class CustomSessionAuthenticationStrategy extends ConcurrentSessionControlAuthenticationStrategy {

    private final SessionRegistry sessionRegistry;
    private final MySessionRepository sessionRepository;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @param sessionRegistry the session registry which should be updated when the
     *                        authenticated session is changed.
     */
    public CustomSessionAuthenticationStrategy(SessionRegistry sessionRegistry) {
        super(sessionRegistry);
        this.sessionRegistry = sessionRegistry;
        this.sessionRepository = null;
    }

    public CustomSessionAuthenticationStrategy(SessionRegistry sessionRegistry, MySessionRepository sessionRepository) {
        super(sessionRegistry);
        this.sessionRegistry = sessionRegistry;
        this.sessionRepository = sessionRepository;
    }

    @Override
    public void onAuthentication(Authentication authentication,
                                 HttpServletRequest request, HttpServletResponse response) {

        logger.info("onAuthentication `" + authentication.getName() + "`\tsession: " + request.getSession().getId());

        final List<SessionInformation> sessions = sessionRegistry.getAllSessions(
                authentication.getPrincipal(), false);

        int sessionCount = sessions.size();
        int allowedSessions = getMaximumSessionsForThisUser(authentication);

        if (sessionCount < allowedSessions) {
            // They haven't got too many login sessions running at present
            return;
        }

        if (allowedSessions == -1) {
            // We permit unlimited logins
            return;
        }

        if (sessionCount == allowedSessions) {
            HttpSession session = request.getSession(false);

            if (session != null) {
                // Only permit it though if this request is associated with one of the
                // already registered sessions
                for (SessionInformation si : sessions) {
                    logger.info("\t" + si.getSessionId());
                    Session storedSession = sessionRepository.findOne(si.getSessionId());
                    logger.info("\t" + storedSession.getDeviceInfo() + " vs " + request.getHeader("User-Agent"));
                    logger.info("\t\t" + storedSession.getDeviceInfo().compareTo(request.getHeader("User-Agent")));
                    if (storedSession.getDeviceInfo().compareTo(request.getHeader("User-Agent")) == 0/* && storedSession.getDeviceInfo().startsWith("_app")*/) {
                        si.expireNow();
                        storedSession.setStatus(SessionStatus.TERMINATED);
                        sessionRepository.save(storedSession);
                        return;
                    }
                    if (si.getSessionId().equals(session.getId())) {
                        return;
                    }
                }
            }
            // If the session is null, a new one will be created by the parent class,
            // exceeding the allowed number
        }

        allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);
    }
}
<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
	'use strict';
	
	angular
		.module('app')
		.config(routeConfig);
	
	/** @ngInject */
	function routeConfig($stateProvider) {
		$stateProvider
            .state('root.category', {
				controller: 'CategoryController',
				controllerAs: 'vm',
				data: {
					roles: [
						"admin"
					]
				},
				resolve: {},
                templateUrl: 'app/components/category/list-category.html',
                url: '/category'
            })
            .state('root.createUpdateCategory', {
                controller: 'CreateUpdateCategoryController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/category/create-update-category.html',
                url: '/category/:method?id'
			})
		
		;
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('auth')
		.controller('LoginController', LoginController);
	
	/** @ngInject */
	function LoginController($log, $http, $state, host, toastr) {
		var vm = this;
		vm.title = 'LoginController';
		vm.host = host;
		vm.login = login;
		activate();
		
		////////////////
		
		function activate() {
			$log.info('login module activated.');
		}
		
		function login() {
			var url = host + 'login';
			$http({
				method: 'POST',
				url: url,
				withCredentials: true,
				data: "username=" + vm.username + '&password=' + <PASSWORD>,
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function () {
				$log.debug('login successful');
				$state.go('root.home');
			}, function () {
				toastr.error('نام کاربری یا کلمه عبور نادرست است.')
			});
		}
		
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.directive('backButton', backButton);
	
	/** @ngInject */
	function backButton() {
		var directive = {
			link: link,
			replace: true,
			restrict: 'E',
			templateUrl: 'app/directives/back-button/back-button.html'
		};
		return directive;
		
		function link(scope, element) {
			element.bind('click', goBack);
			function goBack() {
				history.back();
				scope.$apply();
			}
		}
	}
	
})();

<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateApplicationController', CreateUpdateApplicationController);

    /** @ngInject */
    function CreateUpdateApplicationController($log, $q, $state, applicationService, categoryService, ownerService, $scope,
                                               host, $stateParams, userService, $ngConfirm, $uibModal, util, $window,
                                               accessService, userGroupService) {
        var vm = this;
        var applicationTmp = null;
        vm.host = host;
        vm.croppedDataUrl = '';
        vm.cropper = {};
        vm.cropper.sourceImage = null;
        vm.cropper.croppedImage = null;
        vm.cropperWidth = $window.innerWidth * 0.4;
        vm.bounds = {
            left: 0,
            right: vm.cropperWidth * 0.5,
            top: vm.cropperWidth * 0.4,
            bottom: 0
        };
        vm.bannerBounds = {
            left: 0,
            right: 20,
            top: 20,
            bottom: 0
        };
        vm.resultImage = '';
        vm.title = 'CreateUpdateUserController';
        vm.method = $stateParams.method;
        vm.application = {
            id: $stateParams.id,
            seenCount: 0,
            newApp: false,
            specificApp: false,
            launcher: false,
            nonLauncher: false,
            rating: 0
        };
        vm.file = {};
        vm.tmpData = 'nothing';
        vm.errors = [];
        vm.error = {};
        vm.fileLoading = true;
        vm.statuses = [
            {'id': 'DEACTIVATED', 'title': 'غیرفعال'},
            {'id': 'PUBLIC', 'title': 'عمومی'},
            {'id': 'LAUNCHER', 'title': 'پوسته امن'},
            {'id': 'NON_LAUNCHER', 'title': 'پوسته عادی'}
        ];
        vm.save = save;
        vm.reset = reset;
        vm.uploadLogo = uploadLogo;
        vm.uploadBanner = uploadBanner;
        vm.uploadPic = uploadPic;
        vm.deletePic = deletePic;
        vm.addFileModal = addFileModal;
        vm.deleteFile = deleteFile;
        vm.initiateSuggestion = initiateSuggestion;
        vm.getRatioDiff = getRatioDiff;
        vm.deleteBanner = deleteBanner;
        vm.setActiveVersion = setActiveVersion;
        vm.addGroup = addGroup;
        vm.removeGroup = removeGroup;

        activate();

        ////////////////

        $scope.$watch(angular.bind(this, function () {
            return this.cropper.croppedImage;
        }), function (newVal) {
            // console.log('cropper changed to ', newVal);
            if (document.getElementById('source-image')) {
                var w = document.getElementById('source-image').clientWidth;
                var h = document.getElementById('source-image').clientHeight;
                console.log(w, h);
            }

        });

        function activate() {
            $log.debug('Application module activated', $stateParams.id);
            vm.simorgh = $stateParams.id === 'simorgh';
            if (vm.simorgh) {
                $log.debug('This is is simorgh');
                if (vm.method === 'create') {
                    vm.application.appPackage = 'ir.simorghmarket.simorgh';
                    vm.application.id = null;
                    vm.application.fee = 0;
                }
            } else {
                if (vm.method === 'create') {
                    vm.application.fee = 0;
                }
            }
            vm.loading = true;
            getUserGroups();
            $q.all(getCategories(), getOwners(), getUsers(), getAccesses()).then(getApplication);
        }

        function save() {
            vm.errors = [];
            if (!vm.application.name)
                vm.errors.push('APP.MODULES.APPLICATION.ERRORS.NAME');
            if (!vm.application.appPackage || !util.isEnglish(vm.application.appPackage))
                vm.errors.push('APP.MODULES.APPLICATION.ERRORS.APP_PACKAGE');
            if ((isNaN(parseInt(vm.application.fee)) || parseInt(vm.application.fee) < 0) && !vm.simorgh)
                vm.errors.push('APP.MODULES.APPLICATION.ERRORS.FEE');
            console.log(vm.application.category, !vm.application.category);
            if ((!vm.application.category || vm.application.category.id === 0) && !vm.simorgh)
                vm.errors.push('APP.MODULES.APPLICATION.ERRORS.CATEGORY');
            if (vm.errors.length)
                return;
            vm.loading = true;
            switch (vm.method) {
                case 'create':
                    if ($stateParams.type)
                        vm.application.launcher = $stateParams.type === 'launcher';
                    applicationService.createApplication(vm.application)
                        .then(function (data) {
                            util.toast('success', 'برنامه با موفقیت ایجاد شد. می‌توانید برای تکیمل آن، در همین صفحه نسبت به افزودن تصاویر و نسخه‌های آن اقدام نمایید.');
                            var id = vm.simorgh ? 'simorgh' : data.id;
                            vm.error = {};
                            $state.go('root.createUpdateApplication', {method: 'update', id: id});
                            vm.loading = false;
                        }, errorCallback);
                    break;
                case 'update':
                    applicationService.updateApplication(vm.application)
                        .then(function (data) {
                            util.toast('success', 'برنامه با موفقیت بروزرسانی شد.');
                            vm.error = {};
                            vm.name = data.name;
                            vm.loading = false;
                        }, errorCallback);
                    break;
                default:
                    vm.loading = false;
            }
            function errorCallback(error) {
                console.error(error);
                if(error.data.message === "Application package should be unique") {
                    vm.error['appPackage'] = true;
                }
                util.toast('error', error.data.message);
                vm.loading = false;
            }
        }

        function reset() {
            vm.errors = [];
            switch (vm.method) {
                case 'create':
                    vm.application = {
                        seenCount: 0,
                        newApp: false,
                        specificApp: false,
                        rating: 0
                    };
                    break;
                case 'update':
                    loadTmp();
            }
        }

        function getApplication() {
            vm.loading = true;
            if (vm.simorgh) {
                return applicationService.getSimurgh($stateParams.type).then(
                    function (data) {
                        vm.application = data;
                        applicationTmp = angular.copy(data);
                        vm.name = data.name;
                        vm.loading = false;
                        getActiveVersion();
                    }, function (error) {
                        /*console.log('get simorgh');
                        vm.method = 'create';
                        vm.application = {
                            id: null,
                         seenCount: 0,
                         rating:0,
                            appPackage: "ir.simorghmarket.simorgh"
                         };*/
                        vm.loading = false;
                        $state.go('root.createUpdateApplication', {method: 'create', id: 'simorgh'});
                    });
            } else if (vm.application.id) {
                return applicationService.getApplication(vm.application.id).then(function (data) {
                    vm.application = data;
                    applicationTmp = angular.copy(data);
                    vm.name = data.name;
                    vm.loading = false;
                    getActiveVersion();
                });
            } else {
                vm.loading = false;
            }
        }

        function loadTmp() {
            vm.application = angular.copy(applicationTmp);
        }
        function getCategories() {
            return categoryService.getAllCategories().then(function (data) {
                vm.categories = data;
            })
        }

        function getOwners() {
            return ownerService.getAllOwners().then(function (data) {
                vm.owners = data;
            })
        }

        function getUsers() {
            return userService.getAllUsers().then(function (data) {
                vm.users = data;
            })
        }

        function getUserGroups() {
            userGroupService.getAllUserGroups().then(function (data) {
                vm.groups = data;
            })
        }

        function getAccesses() {
            accessService.getAllAccesses().then(
                function (data) {
                    vm.accesses = data;
                }
            )
        }

        function uploadLogo(dataUrl) {
            vm.loading = true;
            applicationService.updateLogo(vm.application.id, dataUrl)
                .then(
                    function (response) {
                        vm.application.logo = response;
                        vm.appFile = null;
                        vm.tmpData = new Date();
                        util.toast('success', 'نشان با موفقیت به روزرسانی شد.');
                        vm.cropper = {};
                        vm.cropper.sourceImage = null;
                        vm.cropper.croppedImage = null;
                        vm.loading = false;
                    },
                    function (response) {
                        if (response.status > 0) {
                            vm.errorMsg = response.status + ': ' + response.data;
                        }
                        util.toast('error', 'خطا در بارگذاری تصویر!');
                        vm.loading = false;
                    },
                    function (evt) {
                        vm.progress = parseInt(100.0 * evt.loaded / evt.total);
                        vm.loading = false;
                    });
        }

        function uploadBanner(dataUrl) {
            vm.loading = true;
            applicationService.updateBanner(vm.application.id, dataUrl)
                .then(
                    function (response) {
                        vm.application.banner = response;
                        vm.appFile = null;
                        vm.tmpData = new Date();
                        util.toast('success', 'بنر با موفقیت به روزرسانی شد.');
                        vm.cropperBanner = {};
                        vm.cropperBanner.sourceImage = null;
                        vm.cropperBanner.croppedImage = null;
                        vm.loading = false;
                    },
                    function (response) {
                        if (response.status > 0) {
                            vm.errorMsg = response.status + ': ' + response.data;
                        }
                        util.toast('error', 'خطا در بارگذاری بنر!');
                        vm.loading = false;
                    },
                    function (evt) {
                        vm.progress = parseInt(100.0 * evt.loaded / evt.total);
                        vm.loading = false;
                    });
        }

        function uploadPic(dataUrl) {
            vm.loading = true;
            applicationService.addPic(vm.application.id, dataUrl, vm.picLabel)
                .then(
                    function (response) {
                        vm.application.pictures = response;
                        vm.picLabel = '';
                        util.toast('success', 'تصویر با موفقیت اضافه شد.');
                        vm.picCropper = {};
                        vm.picCropper.sourceImage = null;
                        vm.picCropper.croppedImage = null;
                        vm.loading = false;
                    },
                    function (response) {
                        if (response.status > 0) {
                            vm.errorMsg = response.status + ': ' + response.data;
                        }
                        util.toast('error', 'خطا در بارگذاری تصویر!');
                        vm.loading = false;
                    },
                    function (evt) {
                        vm.progress = parseInt(100.0 * evt.loaded / evt.total);
                        vm.loading = false;
                    });
        }

        function deletePic(id) {
            vm.loading = true;
            applicationService.deletePic(vm.application.id, id)
                .then(
                    function (response) {
                        vm.application.pictures = response;
                        util.toast('success', 'تصویر با موفقیت حذف شد.');
                        vm.picCropper = {};
                        vm.picCropper.sourceImage = null;
                        vm.picCropper.croppedImage = null;
                        vm.loading = false;
                    },
                    function (response) {
                        if (response.status > 0) {
                            vm.errorMsg = response.status + ': ' + response.data;
                        }
                        util.toast('error', 'خطا در حذف تصویر!');
                        vm.loading = false;
                    },
                    function (evt) {
                        vm.progress = parseInt(100.0 * evt.loaded / evt.total);
                        vm.loading = false;
                    });
        }

        function addFileModal(file) {
            file = file || {
                    description: '',
                    version: ''
                };
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'app/components/application/file/create-update-file.html',
                controller: CreateUpdateFileController,
                controllerAs: 'fmodal',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    file: function () {
                        return file;
                    },
                    application: function () {
                        return vm.application;
                    }
                }
            });

            modalInstance.result.then(function () {
                applicationService.getFiles(vm.application.id).then(function (data) {
                    vm.application.files = data;
                });
            });

            function CreateUpdateFileController(host, file, application, $timeout,
                                                $uibModalInstance, Upload) {
                var fmodal = this;
                fmodal.application = application;
                fmodal.accesses = vm.accesses;
                fmodal.file = file;
                fmodal.method = file.id ? 'PUT' : 'POST';
                var id = file.id || application.id;
                fmodal.uploadFile = uploadFile;
                fmodal.cancel = function () {
                    loadTmp();
                    $uibModalInstance.dismiss();
                };
                function uploadFile(dataFile) {
                    fmodal.loading = true;
                    var accessesStr = '';
                    if (fmodal.file.accesses) {
                        for (var i = 0; i < fmodal.file.accesses.length; i++) {
                            accessesStr += fmodal.file.accesses[i].id;
                            if (i < fmodal.file.accesses.length) {
                                accessesStr += ',';
                            }
                        }
                    }

                    fmodal.upload =
                        Upload.upload({
                            url: host + 'application/' + id + '/file',
                            method: fmodal.method,
                            data: {
                                data: dataFile,
                                description: fmodal.file.description,
                                version: fmodal.file.version,
                                minimumAndroidVersion: fmodal.file.minimumAndroidVersion,
                                accessesStr: accessesStr
                            }
                        });

                    vm.loading = true;
                    fmodal.upload.then(function (response) {
                        $timeout(function () {
                            console.log('file added');
                            $uibModalInstance.close();
                            fmodal.result = response.data;
                            vm.loading = false;
                            fmodal.loading = false;
                        });
                        util.toast('success', 'APP.MESSAGES.SUCCESS');
                    }, function (response) {
                        if (response && response.data) {
                            fmodal.errorMsg = response.status + ': ' + response.data;
                            util.toast('error', response.data.message);
                        } else {
                            util.toast('erorr', 'APP.MESSAGES.FAIL');
                        }

                        vm.loading = false;
                        fmodal.loading = false;
                    }, function (evt) {
                        // Math.min is to fix IE which reports 200% sometimes
                        fmodal.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                        // vm.loading = false;
                        // fmodal.loading = false;
                    });
                }
            }
        }

        function deleteFile(id) {
            $ngConfirm({
                title: 'حذف فایل',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            applicationService.deleteFile(vm.application.id, id)
                                .then(function () {
                                    util.toast('success', 'فایل با موفقیت حذف شد.');
                                    applicationService.getFiles(vm.application.id)
                                        .then(function (data) {
                                            vm.application.files = data;
                                            vm.loading = false;
                                        });
                                }, function () {
                                    util.toast('error', 'خطا در حذف فایل');
                                    vm.loading = false;
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }

        function deleteBanner() {
            $ngConfirm({
                title: 'حذف بنر',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            applicationService.deleteBanner(vm.application.id)
                                .then(function () {
                                    util.toast('success', 'بنر با موفقیت حذف شد.');
                                    applicationService.getFiles(vm.application.id)
                                        .then(function () {
                                            vm.application.banner = null;
                                            vm.loading = false;
                                        });
                                }, function () {
                                    util.toast('error', 'خطا در حذف بنر');
                                    vm.loading = false;
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }

        $scope.$watch(angular.bind(this, function () {
            return this.picCropper;
        }), function (newVal, oldVal) {

            if(newVal) {
                if(!oldVal || newVal.sourceImage !== oldVal.sourceImage){
                    console.log('Name changed to ',  newVal , ' from ' , oldVal);
                    vm.sourceImage = new Image;
                    vm.sourceImage.onload = function () {
                        console.log('loaded');
                    };
                    vm.sourceImage.scr = newVal.sourceImage;

                }

            }
        });

        function initiateSuggestion() {
            if(!vm.application.suggestionPriority){
                vm.application.suggestionPriority = {appId : vm.application.id, priority: 0}
            }
        }

        function getRatioDiff() {
            return Math.abs((vm.bannerBounds.right - vm.bannerBounds.left) / (vm.bannerBounds.top - vm.bannerBounds.bottom) - (880 / 300));
        }

        function getActiveVersion() {
            applicationService.getActiveVersion(vm.application.id).then(function (data) {
                console.log('last version is', data.version);
                vm.activeVersion = data.version;
                vm.fileLoading = false;
            }, function (failure) {
                console.log(failure);
                vm.fileLoading = false;
            })
        }

        function setActiveVersion(file) {
            vm.fileLoading = true;
            if (file.version !== vm.activeVersion)
                applicationService.setActiveVersion(vm.application.id, file.id).then(function () {
                    getActiveVersion();
                })
        }

        function addGroup() {
            if (!vm.group)
                return;
            applicationService.addGroup(vm.application.id, vm.group.id).then(function () {
                if (!vm.application.groups)
                    vm.application.groups = [];
                vm.application.groups.push(angular.copy(vm.group));
                vm.group = null;
            }, function (error) {
                console.log(error);
                if (error.data.exception === 'org.springframework.dao.DataIntegrityViolationException')
                    util.toast('error', "Group already exists for the application");
                else
                    util.toast('error', "Error in adding group to application");
            });
        }

        function removeGroup(group) {
            if (!group)
                return;
            applicationService.removeGroup(vm.application.id, group.id).then(function () {
                if (!vm.application.groups)
                    vm.application.groups = [];
                var i = 0;
                for (i; i < vm.application.groups.length; i++) {
                    if (vm.application.groups[i].id === group.id)
                        break;
                }
                vm.application.groups.splice(i, 1);
            }, function (error) {
                util.toast('error', "Error in removing group to application");
            });
        }
    }

})();<file_sep># sbazaar
This is an Android App Store server which can support an Android app with the same goal with several features including varied searches, tagging, account management, rating and etc. 
Springboot framework has been used as server side framework to implement logics and communincation with MySql database, and AngularJs is front-end framework to build a user friendly administration pannel.
<file_sep>package ir.saafta.web;

import ir.saafta.model.Advertisement;
import ir.saafta.model.Picture;
import ir.saafta.model.User;
import ir.saafta.repo.AdvertisementRepository;
import ir.saafta.repo.PictureRepository;
import ir.saafta.service.UserDetailManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by reza on 11/14/16.
 */
@RestController
@RequestMapping("/ad")
public class AdvertisementController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final AdvertisementRepository advertisementRepository;
    private final PictureRepository pictureRepository;
    private final UserDetailManager userDetailManager;

    @Autowired
    public AdvertisementController(AdvertisementRepository advertisementRepository, PictureRepository pictureRepository,
                                   UserDetailManager userDetailManager) {
        this.advertisementRepository = advertisementRepository;
        this.pictureRepository = pictureRepository;
        this.userDetailManager = userDetailManager;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Page<Advertisement> get(Pageable pageable) {
        return advertisementRepository.findAll(pageable);
    }

    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Iterable<Advertisement> getCurrent() {
        return advertisementRepository.findCurrentAdvertisement();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Advertisement get(@PathVariable Long id) {
        return advertisementRepository.findOne(id);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = "multipart/*")
    public Advertisement create(MultipartFile file, String label,
                                @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate,
                                @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate, String url, String username)
            throws IOException, ParseException {
        Advertisement advertisement = new Advertisement();
        advertisement.setFromDate(fromDate);
        advertisement.setToDate(toDate);
        Picture picture = new Picture(file.getBytes(), label, "ad", file.getOriginalFilename());
        pictureRepository.save(picture);
        advertisement.setPicture(picture);
        advertisement.setUrl(url);
        advertisement.setSeenCount(0);
        if (username != null) {
            User user = (User) userDetailManager.loadUserByUsername(username);
            advertisement.setUser(user);
        }
        return advertisementRepository.save(advertisement);
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = "multipart/*")
    public Advertisement setPicture(@PathVariable Long id, MultipartFile file, String label,
                                    @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate,
                                    @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate, String url, String username) throws IOException, ParseException {
        Advertisement advertisement = advertisementRepository.findOne(id);
        advertisement.setFromDate(fromDate);
        advertisement.setToDate(toDate);
        if (advertisement.getPicture() != null) {
            advertisement.getPicture().setLabel(label);
            pictureRepository.save(advertisement.getPicture());
        }
        advertisement.setUrl(url);
        if (username != null) {
            User user = (User) userDetailManager.loadUserByUsername(username);
            advertisement.setUser(user);
        }
        if (file != null && file.getBytes() != null) {
            if (advertisement.getPicture() != null) {
                Picture picture = advertisement.getPicture();
                picture.setData(file.getBytes());
                picture.setFormat(file.getOriginalFilename());
                pictureRepository.save(picture);
            } else {
                Picture picture = new Picture(advertisement.getId(), file.getBytes(), advertisement.getTitle(), "ad", file.getOriginalFilename());
                pictureRepository.save(picture);
            }
        }
        return advertisementRepository.findOne(id);
    }

    @RequestMapping(value = "/seen/{id}", method = RequestMethod.PUT)
    public Advertisement seenAd(@PathVariable Long id) {
        Advertisement advertisement = advertisementRepository.findOne(id);
        logger.info("Advertisement being seen with id " + id);
        if (advertisement != null) {
            Integer seenCount = advertisement.getSeenCount();
            if (seenCount == null)
                seenCount = 0;
            seenCount++;
            logger.info("seenCount is " + seenCount);
            advertisement.setSeenCount(seenCount);
        } else {
            logger.info("Ad not found by id " + id);
        }
        return advertisementRepository.save(advertisement);
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Long id) {
        pictureRepository.delete(advertisementRepository.findOne(id).getPicture());
        advertisementRepository.delete(id);
    }
}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.config(config);
	
	/** @ngInject */
	function config($locationProvider, $logProvider, $httpProvider,
                    ADMdtpProvider, moment, toastrConfig, $uibTooltipProvider) {
		// Enable log
		$logProvider.debugEnabled(true);
		
		//  @desc add $http Interceptor
        $httpProvider.interceptors.push('authInterceptor');
		$httpProvider.defaults.withCredentials = true;
        $httpProvider.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
		// disable # in url
		// $locationProvider.html5Mode(true);
		
		/////////////////////////////////
		// Set options third-party lib //
		/////////////////////////////////
		
		ADMdtpProvider.setOptions({
			autoClose: true,
			calType: 'jalali',
			dtpType: 'date',
            format: 'YYYY-MM-DD',
            freezeInput: true
		});
		
		// Set toastr options
		angular.extend(toastrConfig, {
			allowHtml: true,
			closeButton: true,
			closeHtml: '<button class="pull-left">&times;</button>',
			extendedTimeOut: 500,
			positionClass: 'toast-top-right',
            preventDuplicates: false,
            preventOpenDuplicates: true,
			progressBar: true,
			tapToDismiss: true,
            // target: 'body',
			timeOut: 2000
		});
		
		
		//moment
		moment.loadPersian();

        var parser = new UAParser();
        var result = parser.getResult();
        var touch = result.device && (result.device.type === 'tablet' || result.device.type === 'mobile');
        console.log(result, touch);
        if (touch) {
            var options = {
                trigger: 'dontTrigger' // default dummy trigger event to show tooltips
            };

            $uibTooltipProvider.options(options);
        } else {
            $uibTooltipProvider.options({
                'appendToBody': true
            })
        }
	}
	
})();
<file_sep>/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.10-log : Database - simorgh
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`simorgh` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `simorgh`;

/*Table structure for table `access` */

DROP TABLE IF EXISTS `access`;

CREATE TABLE `access` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(50) DEFAULT NULL,
  `description` text,
  `label` varchar(50) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;

/*Table structure for table `access_file` */

DROP TABLE IF EXISTS `access_file`;

CREATE TABLE `access_file` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `access_id` bigint(20) unsigned NOT NULL,
  `file_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Unique_file_access` (`access_id`,`file_id`),
  KEY `foreign_key_access_file_file` (`file_id`),
  CONSTRAINT `access_file_access_to_access` FOREIGN KEY (`access_id`) REFERENCES `access` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8;

/*Table structure for table `advertisement` */

DROP TABLE IF EXISTS `advertisement`;

CREATE TABLE `advertisement` (
  `id` bigint(20) NOT NULL,
  `url` varchar(50) DEFAULT NULL,
  `picture_id` bigint(20) DEFAULT NULL,
  `user_id` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `from_date` datetime DEFAULT NULL,
  `to_date` datetime DEFAULT NULL,
  `seen_count` binary(1) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `application` */

DROP TABLE IF EXISTS `application`;

CREATE TABLE `application` (
  `id` bigint(20) unsigned NOT NULL,
  `app_package` varchar(255) NOT NULL,
  `fee` int(11) DEFAULT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `category_id` bigint(20) unsigned DEFAULT NULL,
  `owner_id` bigint(20) unsigned DEFAULT NULL,
  `logo_id` bigint(20) unsigned DEFAULT NULL,
  `user_id` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  `last_update` datetime DEFAULT NULL,
  `specific_app` binary(1) DEFAULT '0',
  `banner_id` bigint(20) unsigned DEFAULT NULL,
  `new_app` binary(1) DEFAULT '0',
  `last_file_id` bigint(20) unsigned DEFAULT NULL,
  `recently_updated` binary(1) DEFAULT '0',
  `installation_count` int(11) DEFAULT '0',
  `in_app_payment` binary(1) DEFAULT '0',
  `suggestion_priority` bigint(20) unsigned DEFAULT NULL,
  `suggested_app` bigint(1) DEFAULT '0',
  `disabled` binary(1) DEFAULT '0',
  `incomplete` binary(1) DEFAULT '0',
  `original_name` varchar(128) DEFAULT NULL,
  `status` int(1) DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `foreign_key_application_picture` (`logo_id`),
  KEY `foreign_key_application_category` (`category_id`),
  KEY `foreign_key_application_picture_2` (`banner_id`),
  KEY `foreign_key_application_file` (`last_file_id`),
  KEY `foreign_key_application_owner` (`owner_id`),
  KEY `unique` (`app_package`,`status`),
  CONSTRAINT `foreign_key_application_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_file_last_file` FOREIGN KEY (`last_file_id`) REFERENCES `file` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_owner` FOREIGN KEY (`owner_id`) REFERENCES `owner` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_picture` FOREIGN KEY (`logo_id`) REFERENCES `picture` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `foreign_key_application_picture_2` FOREIGN KEY (`banner_id`) REFERENCES `picture` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `attempt` */

DROP TABLE IF EXISTS `attempt`;

CREATE TABLE `attempt` (
  `session_id` varchar(100) NOT NULL,
  `time` datetime DEFAULT NULL,
  `username` varchar(50) DEFAULT NULL,
  `captcha_passed` tinyint(1) DEFAULT '0',
  `remote_address` varchar(30) DEFAULT NULL,
  `device_info` varchar(255) DEFAULT NULL,
  `captcha_value` varchar(30) DEFAULT NULL,
  `true_password` tinyint(1) DEFAULT '0',
  `count` int(8) unsigned DEFAULT '1',
  PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `authorities` */

DROP TABLE IF EXISTS `authorities`;

CREATE TABLE `authorities` (
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `authority` varchar(45) NOT NULL,
  PRIMARY KEY (`username`,`authority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `category` */

DROP TABLE IF EXISTS `category`;

CREATE TABLE `category` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `picture_id` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `category_name_unique` (`name`),
  KEY `foreign_key_category_picture` (`picture_id`),
  CONSTRAINT `foreign_key_category_picture` FOREIGN KEY (`picture_id`) REFERENCES `picture` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

/*Table structure for table `comment` */

DROP TABLE IF EXISTS `comment`;

CREATE TABLE `comment` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `content` varchar(255) DEFAULT NULL,
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `user_id` varchar(45) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `approved` binary(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `foreign_key_comment_contetn` (`content_id`),
  CONSTRAINT `foreign_key_comment_contetn` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

/*Table structure for table `content` */

DROP TABLE IF EXISTS `content`;

CREATE TABLE `content` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `description` text,
  `seen_count` int(11) unsigned NOT NULL DEFAULT '0',
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `DTYPE` varchar(45) DEFAULT NULL,
  `rating` double DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=utf8;

/*Table structure for table `content_group` */

DROP TABLE IF EXISTS `content_group`;

CREATE TABLE `content_group` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `group_id` bigint(20) unsigned NOT NULL,
  `content_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `content_group_unique` (`group_id`,`content_id`),
  KEY `content_id_fk` (`content_id`),
  CONSTRAINT `content_id_fk` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `group_id_fk` FOREIGN KEY (`group_id`) REFERENCES `user_group` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;

/*Table structure for table `deleted_user` */

DROP TABLE IF EXISTS `deleted_user`;

CREATE TABLE `deleted_user` (
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `deletion_date` datetime NOT NULL,
  `deleted_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `credit` int(11) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `event` */

DROP TABLE IF EXISTS `event`;

CREATE TABLE `event` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `time` datetime NOT NULL,
  `action` varchar(50) NOT NULL,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `remote_addr` varchar(30) DEFAULT NULL,
  `host` varchar(50) DEFAULT NULL,
  `session_id` varchar(100) DEFAULT NULL,
  `cookie` varchar(500) DEFAULT NULL,
  `method` varchar(10) DEFAULT NULL,
  `params` text,
  `body` text,
  `user_agent` text,
  `path` varchar(50) DEFAULT NULL,
  `status` varchar(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10046 DEFAULT CHARSET=utf8;

/*Table structure for table `feedback` */

DROP TABLE IF EXISTS `feedback`;

CREATE TABLE `feedback` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `date` datetime DEFAULT NULL,
  `liked` tinyint(1) DEFAULT '0',
  `disliked` tinyint(1) DEFAULT '0',
  `rate` double DEFAULT '0',
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `foreign_key_feedback_content` (`content_id`),
  CONSTRAINT `foreign_key_feedback_content` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

/*Table structure for table `file` */

DROP TABLE IF EXISTS `file`;

CREATE TABLE `file` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `application_id` bigint(20) DEFAULT NULL,
  `data` longblob,
  `description` text,
  `name` varchar(255) DEFAULT NULL,
  `registration_date` datetime DEFAULT NULL,
  `size` int(11) DEFAULT NULL,
  `version` varchar(255) DEFAULT NULL,
  `minimum_android_version` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

/*Table structure for table `news` */

DROP TABLE IF EXISTS `news`;

CREATE TABLE `news` (
  `id` bigint(20) unsigned NOT NULL,
  `body` text,
  `main_picture_id` bigint(20) DEFAULT NULL,
  `date` datetime NOT NULL,
  `writer` varchar(60) DEFAULT NULL,
  `lead` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `owner` */

DROP TABLE IF EXISTS `owner`;

CREATE TABLE `owner` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone_number` varchar(15) DEFAULT NULL,
  `type` int(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

/*Table structure for table `picture` */

DROP TABLE IF EXISTS `picture`;

CREATE TABLE `picture` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `data` longblob,
  `label` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `published` tinyint(1) DEFAULT NULL,
  `format` varchar(64) DEFAULT NULL,
  `application_status` int(1) DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `foreign_key_picture_content` (`content_id`),
  CONSTRAINT `foreign_key_picture_content` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=388 DEFAULT CHARSET=utf8;

/*Table structure for table `role` */

DROP TABLE IF EXISTS `role`;

CREATE TABLE `role` (
  `authority` varchar(50) NOT NULL,
  `caption` varchar(50) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  PRIMARY KEY (`authority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `session` */

DROP TABLE IF EXISTS `session`;

CREATE TABLE `session` (
  `session_id` varchar(100) NOT NULL,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `creation_time` datetime DEFAULT NULL,
  `finish_time` datetime DEFAULT NULL,
  `status` int(1) DEFAULT NULL,
  `last_request` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `remote_addr` varchar(30) DEFAULT NULL,
  `device_info` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `spring_session` */

DROP TABLE IF EXISTS `spring_session`;

CREATE TABLE `spring_session` (
  `PRIMARY_ID` char(36) DEFAULT NULL,
  `SESSION_ID` char(36) NOT NULL,
  `CREATION_TIME` bigint(20) NOT NULL,
  `LAST_ACCESS_TIME` bigint(20) NOT NULL,
  `MAX_INACTIVE_INTERVAL` int(11) NOT NULL,
  `EXPIRY_TIME` bigint(20) DEFAULT NULL,
  `PRINCIPAL_NAME` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`SESSION_ID`),
  UNIQUE KEY `SPRING_SESSION_IX1` (`SESSION_ID`),
  KEY `SPRING_SESSION_IX2` (`EXPIRY_TIME`),
  KEY `SPRING_SESSION_IX3` (`PRINCIPAL_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

/*Table structure for table `spring_session_attributes` */

DROP TABLE IF EXISTS `spring_session_attributes`;

CREATE TABLE `spring_session_attributes` (
  `SESSION_ID` char(36) NOT NULL,
  `ATTRIBUTE_NAME` varchar(200) NOT NULL,
  `ATTRIBUTE_BYTES` blob NOT NULL,
  PRIMARY KEY (`ATTRIBUTE_NAME`,`SESSION_ID`),
  KEY `SPRING_SESSION_ATTRIBUTES_FK` (`SESSION_ID`),
  CONSTRAINT `SPRING_SESSION_ATTRIBUTES_FK` FOREIGN KEY (`SESSION_ID`) REFERENCES `spring_session` (`SESSION_ID`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

/*Table structure for table `suggestion_priority` */

DROP TABLE IF EXISTS `suggestion_priority`;

CREATE TABLE `suggestion_priority` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `app_id` bigint(20) unsigned DEFAULT NULL,
  `priority` int(2) unsigned DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `suggestion_priority_application` (`app_id`),
  CONSTRAINT `suggestion_priority_application` FOREIGN KEY (`app_id`) REFERENCES `application` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `transaction` */

DROP TABLE IF EXISTS `transaction`;

CREATE TABLE `transaction` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `date` datetime DEFAULT NULL,
  `amount` int(11) DEFAULT NULL,
  `type` varchar(20) DEFAULT NULL,
  `app_id` bigint(20) unsigned DEFAULT NULL,
  `transaction_id` bigint(20) unsigned DEFAULT NULL,
  `reference_id` bigint(20) unsigned DEFAULT NULL,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `comment` varchar(1024) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `transaction_fk2_appId` (`app_id`),
  CONSTRAINT `transaction_fk2_appId` FOREIGN KEY (`app_id`) REFERENCES `content` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `password` varchar(60) NOT NULL,
  `enabled` tinyint(4) DEFAULT '1',
  `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `family` varchar(45) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `address` text,
  `mobile_phone` varchar(13) DEFAULT NULL,
  `mobile_phone_two` varchar(13) DEFAULT NULL,
  `mobile_phone_three` varchar(13) DEFAULT NULL,
  `phone` varchar(14) DEFAULT NULL,
  `postal_code` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `profile_id` bigint(20) unsigned DEFAULT NULL,
  `credit` int(11) DEFAULT '0',
  `score` int(11) DEFAULT '0',
  `imei` varchar(40) DEFAULT NULL,
  `user_group_id` bigint(20) unsigned DEFAULT NULL,
  PRIMARY KEY (`username`),
  KEY `user_fk1_profile_pic` (`profile_id`),
  KEY `user_fk2_group` (`user_group_id`),
  CONSTRAINT `user_fk1_profile_pic` FOREIGN KEY (`profile_id`) REFERENCES `picture` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `user_fk2_group` FOREIGN KEY (`user_group_id`) REFERENCES `user_group` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `user_app` */

DROP TABLE IF EXISTS `user_app`;

CREATE TABLE `user_app` (
  `id` bigint(20) unsigned NOT NULL,
  `install_date` datetime DEFAULT NULL,
  `uninstall_date` datetime DEFAULT NULL,
  `current_version` varchar(255) DEFAULT NULL,
  `bookmarked` binary(1) DEFAULT '0',
  KEY `user_app_user_content_id_fk` (`id`),
  CONSTRAINT `user_app_user_content_id_fk` FOREIGN KEY (`id`) REFERENCES `user_content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `user_content` */

DROP TABLE IF EXISTS `user_content`;

CREATE TABLE `user_content` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `content_id` bigint(20) unsigned DEFAULT NULL,
  `phone_number` varchar(14) DEFAULT NULL,
  `rating` double DEFAULT '-1',
  `install_date` datetime DEFAULT NULL,
  `uninstall_date` datetime DEFAULT NULL,
  `current_version` varchar(255) DEFAULT NULL,
  `bookmarked` binary(1) DEFAULT NULL,
  `bought` binary(1) DEFAULT '0',
  `session` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_content_session_unique` (`session`,`content_id`),
  KEY `user_content_content_id_fk` (`content_id`),
  CONSTRAINT `user_content_content_id_fk` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=137 DEFAULT CHARSET=utf8;

/*Table structure for table `user_group` */

DROP TABLE IF EXISTS `user_group`;

CREATE TABLE `user_group` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(50) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
  `logo_id` bigint(20) unsigned DEFAULT NULL,
  `default_group` binary(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_group_name_unique` (`title`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Table structure for table `user_user_group` */

DROP TABLE IF EXISTS `user_user_group`;

CREATE TABLE `user_user_group` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `group_id` bigint(20) unsigned NOT NULL,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_relation` (`group_id`,`username`),
  KEY `user_group_username_fk` (`username`),
  CONSTRAINT `user_group_groupId_fk` FOREIGN KEY (`group_id`) REFERENCES `user_group` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `user_group_username_fk` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>package ir.saafta.service;

import ir.saafta.model.Authority;
import ir.saafta.model.User;
import ir.saafta.repo.UserRepository;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

/**
 * Created by reza on 11/12/16.
 */
@Component
public class UserDetailManager implements UserDetailsManager {
    private final UserRepository userRepository;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LoginAttemptService loginAttemptService;

    @Autowired
    public UserDetailManager(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    @Override
    public void createUser(UserDetails user) {
        User theUser = (User) user;
        if (this.loadUserByUsername(user.getUsername()) == null)
            userRepository.save(theUser);
    }

    @Override
    public void updateUser(UserDetails user) {
        User theUser = (User) user;
        userRepository.save(theUser);
    }

    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteUser(String username) {
        userRepository.delete(username);
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return userRepository.findOne(username) != null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String ip = getClientIP();
        String dId = getDeviceId();
        if (loginAttemptService.isBlocked(ip + dId)) {
            throw new RuntimeException("blocked");
        }
        return userRepository.findOne(username);
    }

    public Long count() {
        return userRepository.count();
    }

    public UserDetails enableUser(String username) {
        User user = (User) loadUserByUsername(username);
        user.setEnabled(true);
        return userRepository.save(user);
    }

    public UserDetails disableUser(String username) {
        User user = (User) loadUserByUsername(username);
        user.setEnabled(false);
        return userRepository.save(user);
    }

    public boolean hasAuthority(UserDetails user, String authority) {
        for (GrantedAuthority auth : user.getAuthorities()) {
            if (auth.getAuthority().equals(authority))
                return true;
        }
        return false;
    }

    public boolean hasAuthority(Authentication authentication, String authority) {
        User user = (User) this.loadUserByUsername(authentication.getName());
        for (GrantedAuthority auth : user.getAuthorities()) {
            if (auth.getAuthority().equals(authority))
                return true;
        }
        return false;
    }

    public boolean hasAuthorities(UserDetails user, Iterable<String> authorities) {
        for (String auth : authorities) {
            if (hasAuthority(user, auth))
                return true;
        }
        return false;
    }

    public boolean hasAuthorities(Authentication authentication, Iterable<String> authorities) {
        User user = (User) this.loadUserByUsername(authentication.getName());
        for (String auth : authorities) {
            if (hasAuthority(user, auth))
                return true;
        }
        return false;
    }

    private String getClientIP() {
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0];
    }

    private String getDeviceId() {
        return request.getHeader("User-Agent");
    }


}
<file_sep>package ir.saafta.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * User: <NAME>
 */
@Profile("!production")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/.*"))
                .build()
                .apiInfo(new ApiInfo(
                        "Simorgh Market Application",
                        "Simorgh Market is an Android app-store which focuses on security apps",
                        "version 1.0.0",
                        "API TOS",
                        "<EMAIL>",
                        "API License",
                        "API License URL"
                ));
    }
}
<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
	'use strict';
	
	angular
		.module('app')
		.config(routeConfig);
	
	/** @ngInject */
	function routeConfig($stateProvider) {
		$stateProvider
			.state('root.userManagement', {
				controller: 'UserController',
				controllerAs: 'vm',
				data: {
					roles: [
						"admin"
					]
				},
				resolve: {},
				templateUrl: 'app/components/user/user.html',
				url: '/user-management'
			})
		
		;
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('homeService', homeService);
	
	/** @ngInject */
	function homeService($log, $http, host) {
        var base = host + 'dashboard/';
		var service = {
            getDashboard: getDashboard,
            getMyDashboard: getMyDashboard
		};
		return service;
		
		////////////////
		
		function getDashboard(params) {
			return $http.get(base, {params: params})
				.then(successCallback);
		}

        function getMyDashboard(params) {
            var url = base + 'me';
            return $http.get(url, {params: params})
                .then(successCallback);
        }
		function successCallback(response) {
			return response.data;
		}
		
	}
	
})();<file_sep>/**
 * Created by Reza on 11/30/2016.
 */
(function () {
    'use strict';

    angular
        .module('app')
        .factory('fileService', fileService);

    /** @ngInject */
    function fileService($log, $http, host) {
        var base = host + 'file/';
        var service = {
            updateFile: updateFile,
            deleteFile: deleteFile
        };
        return service;

        function successCallback(response) {
            return response.data;
        }

        ////////////////

        function updateFile(file) {
            return $http.put(base, file)
                .then(successCallback);
        }

        function deleteFile(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }


    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('auth')
		.controller('ForgetPassController', ForgetPassController);
	
	/** @ngInject */
	function ForgetPassController($log) {
		var vm = this;
		vm.title = 'ForgetPassController';
		
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('forget pass module ativated.');
		}
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('CreateUpdateUserController', CreateUpdateUserController);
	
	/** @ngInject */
	function CreateUpdateUserController($log, toastr, userService, $stateParams, $scope, $timeout, $state) {
		var vm = this;
		vm.title = 'CreateUpdateUserController';
		vm.method = $stateParams.method;
		vm.user = {
			username: $stateParams.username,
			authorities: []
		};
		
		vm.save = save;
		vm.reset = reset;
		vm.resetPassword = <PASSWORD>;
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('User module activated');
			getAuthorities().then(getUser);
		}
		
		function save() {
			vm.user.authorities = [];
			vm.userAuthorities.forEach(function (authority) {
				vm.user.authorities.push({
					authority: authority.authority,
					username: vm.user.username
				})
			});
			switch (vm.method) {
				case 'create':
					userService.createUser(vm.user).then(function () {
						toastr.success('کاربر با موفقیت  ایجاد شد.');
						$timeout(function () {
							$state.go('root.user');
						}, 3000);
					}, function () {
						toastr.error('خطا در ایجاد کاربر!');
					});
					break;
				case 'update':
					userService.updateUser(vm.user).then(function () {
						toastr.success('کابر با موفقیت به روزرسانی شد.')
					}, function () {
						toastr.error('خطا در به روزرسانی کاربر!');
					});
			}
		}
		
		function getAuthorities() {
			return userService.getAuthorities().then(function (data) {
				vm.authorities = data;
			})
		}
		
		function getCaption(authority) {
			for (var i = 0; i < vm.authorities.length; i++) {
				if (vm.authorities[i].authority == authority)
					return vm.authorities[i].caption;
			}
		}
		
		function reset() {
			switch (vm.method) {
				case 'create':
					vm.user = {
						authorities: []
					};
					console.log('method');
					break;
				case 'update':
					getUser();
			}
		}
		
		function getUser() {
			vm.userAuthorities = [];
			if (vm.user.username) {
				userService.getUser(vm.user.username).then(function (data) {
					vm.user = data;
					// console.log(data);
					vm.passwordCheck = data.<PASSWORD>;
					vm.user.authorities.forEach(function (authority) {
						vm.userAuthorities.push({
							"authority": authority.authority,
							"caption": getCaption(authority.authority)
						})
					})
				});
			}
		}
		
		function resetPassword() {
			userService.resetPassword(vm.user.username, vm.user.password).then(function () {
				toastr.success('کلمه عبور با موفقیت به روزرسانی شد.')
			}, function () {
				toastr.error('خطا در به روزرسانی کلمه عبور!');
			});
		}
		
		
		var stillClearPassword = true;
		$scope.$watch(angular.bind(this, function () {
			return this.user.password;
		}), function (newVal) {
			if (stillClearPassword && newVal !== undefined && newVal !== null) {
				vm.user.password = '';
				stillClearPassword = false;
			}
		});
	}
	
})();<file_sep>angular.module('bootstrapWysiwyg', []).directive('bootstrapWysiwyg', function () {
    'use strict';

    return {
        restrict: 'AE',
        scope: {
            'toolbar': '=',
            'useLineBreaks': '=',
            'parserRules': '=',
            'locale': '=',
            'shortcuts': '='
        },
        link: function (scope, element) {
            if (typeof scope.toolbar === 'string') {
                scope.toolbar = JSON.parse(scope.toolbar);
            }
            if (typeof scope.parserRules === 'string') {
                scope.toolbar = JSON.parse(scope.toolbar);
            }
            if (typeof scope.shortcuts === 'string') {
                scope.toolbar = JSON.parse(scope.toolbar);
            }

            $.fn.wysihtml5.defaultOptions = {
                'toolbar': {
                    'fa': true
                }
            };

            $(element).wysihtml5(scope);
        }
    };
});
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('util', util);
	
	/** @ngInject */
	function util($log, $translate, toastr) {

        var colors = [
            "red",
            "blue",
            "cyan",
            "light-blue",
            "lime",
            "pink",
            "green",
            "purple",
            "yellow",
            "deep-purple",
            "indigo",
            "teal",
            "light-green",
            "blue-grey",
            "amber",
            "orange",
            "deep-orange",
            "brown",
            "grey",
            "shades"];
		var service = {
			compareObjects: compareObjects,
			toast: toast,
            transformRequest: transformRequest,
            colors: colors
		};
		return service;
		
		////////////////
		
		function compareObjects(object1, object2) {
			return angular.toJson(object1) === angular.toJson(object2);
		}
		
		function toast(type, text, title) {
			$translate(text).then(toaster, toaster);
			console.log('toast', type, text, title);
			function toaster(msg) {
				console.log('toaster', msg);
				switch (type) {
					case 'error':
						toastr.error(msg);
						$log.error(title);
						break;
					case 'info':
						toastr.info(msg);
						break;
					case 'success':
						toastr.success(msg);
						break;
					case 'warn':
						toastr.warning(msg);
						$log.warn(title);
						break;
					default:
						toastr.info(msg);
				}
			}
		}
		
		function transformRequest(data) {
			var formData = new FormData();
			angular.forEach(data, function (value, key) {
				formData.append(key, value);
			});
			
			return formData;
		}
		
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('categoryService', categoryService);
	
	/** @ngInject */
    function categoryService($log, $http, host, Upload) {
		var base = host + 'category/';
		var service = {
            getCategories: getCategories,
            getAllCategories: getAllCategories,
            getCategory: getCategory,
            createCategory: createCategory,
            updateCategory: updateCategory,
            deleteCategory: deleteCategory
		};
		return service;

        function successCallback(response) {
            return response.data;
        }
		////////////////

        function createCategory(name, dataUrl) {
            return Upload.upload({
                url: base,
                data: {
                    pic: Upload.dataUrltoBlob(dataUrl, 'image.png'),
                    name: name
                },
                method: 'POST'
            });
            // return $http.post(base, category)
            //     .then(successCallback);
        }


		
		function getCategories(params) {
			return $http.get(base, {params: params})
				.then(successCallback);
		}

		function getAllCategories() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getCategory(id) {
            var url = base + id;
            return $http.get(url)
                .then(successCallback);
        }


        function updateCategory(id, name, dataUrl) {
            console.log('updateCategory ', id);
            return Upload.upload({
                url: base + id,
                data: {
                    pic: dataUrl ? Upload.dataUrltoBlob(dataUrl, 'image.png') : null,
                    name: name
                },
                method: 'PUT'
            }).then(successCallback);
        }


        function deleteCategory(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }



	}
	
})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('bannerService', bannerService);

    /** @ngInject */
    function bannerService($log, $http, host, Upload) {
        var base = host + 'banner/';
        var service = {
            getBanners: getBanners,
            getAllBanners: getAllBanners,
            getBanner: getBanner,
            createBanner: createBanner,
            updateBanner: updateBanner,
            deleteBanner: deleteBanner,
            publishBanner: publishBanner
        };
        return service;

        function successCallback(response) {
            return response.data;
        }

        ////////////////

        function createBanner(label, dataUrl) {
            return Upload.upload({
                url: base,
                data: {
                    file: Upload.dataUrltoBlob(dataUrl, 'image.jpg'),
                    label: label
                },
                method: 'POST'
            });
            // return $http.post(base, banner)
            //     .then(successCallback);
        }


        function getBanners(params) {
            return $http.get(base, {params: params})
                .then(successCallback);
        }

        function getAllBanners() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getBanner(id) {
            var url = base + id;
            return $http.get(url)
                .then(successCallback);
        }


        function updateBanner(id, caption) {
            console.log('updateBanner ', id);
            var url = base + id;
            return $http.put(url, {}, {params: {caption: caption}}).then(successCallback);
        }


        function deleteBanner(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }

        function publishBanner(id, publish) {
            console.log('publishBanner', id, publish);
            var url = base + id + '/publish';
            return $http.put(url, {},
                {
                    params: {
                        'publish': publish
                    }
                });
        }

    }

})();<file_sep>package ir.saafta.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
public class Attempt {
    @Id
    private String sessionId;
    private Date time;
    private String username;
    private boolean captchaPassed;
    private String remoteAddress;
    private String deviceInfo;
    private String captchaValue;
    private boolean truePassword;
    private Integer count;

    public Attempt() {
        this.count = 1;
    }

    public Attempt(String captchaValue, String sessionId, String remoteAddress, String deviceInfo) {
        this.sessionId = sessionId;
        this.remoteAddress = remoteAddress;
        this.deviceInfo = deviceInfo;
        this.captchaValue = captchaValue;
        this.count = 1;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isCaptchaPassed() {
        return captchaPassed;
    }

    public void setCaptchaPassed(boolean captchaPassed) {
        this.captchaPassed = captchaPassed;
    }

    public String getRemoteAddress() {
        return remoteAddress;
    }

    public void setRemoteAddress(String remoteAddress) {
        this.remoteAddress = remoteAddress;
    }

    public String getDeviceInfo() {
        return deviceInfo;
    }

    public void setDeviceInfo(String deviceInfo) {
        this.deviceInfo = deviceInfo;
    }

    public String getCaptchaValue() {
        return captchaValue;
    }

    public void setCaptchaValue(String captchaValue) {
        this.captchaValue = captchaValue;
    }

    public boolean isTruePassword() {
        return truePassword;
    }

    public void setTruePassword(boolean truePassword) {
        this.truePassword = truePassword;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public void increaseCount() {
        if (this.count == null)
            this.count = 1;
        this.count++;
    }
}
<file_sep>package ir.saafta.repo;

import ir.saafta.model.Content;
import ir.saafta.model.User;
import ir.saafta.model.UserContent;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

/**
 * Created by Reza on 1/20/2017.
 */
public interface UserContentRepository extends PagingAndSortingRepository<UserContent, Long> {
    UserContent findByUserAndContent(User user, Content content);

    Iterable<UserContent> findByContent(Content content);

    @Modifying(clearAutomatically = true)
    @Query("update UserContent userContent set userContent.currentVersion =:currentVersion where userContent.currentVersion =:oldVersion")
    void updateVersions(@Param("currentVersion") String currentVersion, @Param("oldVersion") String oldVersion);
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('newsService', newsService);

    /** @ngInject */
    function newsService($log, $http, host, Upload) {
        var base = host + 'news/';
        var service = {
            getNewsList: getNewsList,
            getAllNewsList: getAllNewsList,
            getNews: getNews,
            createNews: createNews,
            mainPicture: mainPicture,
            updateNews: updateNews,
            deleteNews: deleteNews
        };
        return service;

        function successCallback(response) {
            return response.data;
        }

        ////////////////

        function createNews(news) {
            return $http.post(base, news);
        }

        function mainPicture(id, dataUrl) {
            var url = base + id + '/mainPicture';
            return Upload.upload({
                url: url,
                data: {
                    pic: Upload.dataUrltoBlob(dataUrl, 'image.png')
                },
                method: 'POST'
            }).then(successCallback);
        }


        function getNewsList(params) {
            return $http.get(base, {params: params})
                .then(successCallback);
        }

        function getAllNewsList() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getNews(id) {
            var url = base + id;
            var params = {
                manage: true
            };
            return $http.get(url, {params: params})
                .then(successCallback);
        }


        function updateNews(news) {
            var url = base + news.id;
            return $http.put(url, news).then(successCallback);
        }


        function deleteNews(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }


    }

})();<file_sep>package ir.saafta.repo;

import ir.saafta.dto.ApplicationStatus;
import ir.saafta.model.Picture;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by reza on 11/13/16.
 */
public interface PictureRepository extends PagingAndSortingRepository<Picture, Long> {
    Iterable<Picture> findByPublished(Boolean published);

//    ArrayList<Picture> findByPublishedAndLuncherAndNonLuncher(Boolean published, Boolean luncher, Boolean nonLuncher);
//
//    ArrayList<Picture> findByPublishedAndLuncher(Boolean published, Boolean luncher);
//
//    ArrayList<Picture> findByPublishedAndNonLuncher(Boolean published, Boolean nonLuncher);

    ArrayList<Picture> findByPublishedAndApplicationStatusIn(Boolean published, Collection<ApplicationStatus> statuses);

    Page<Picture> findByTypeEquals(String type, Pageable pageable);

}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('auth')
		.factory('authInterceptor', authInterceptor);
	
	/** @ngInject */
    function authInterceptor($log, $q, $window, $state, host) {
		var Authentication = {
            // request: onRequest,
            response: onResponse,
			responseError: onResponseError
		};
		
		return Authentication;
		
		////////////////
		
		function onRequest(config) {
			var deferred = $q.defer();
			// promise that should abort the request when resolved.
			config.timeout = deferred.promise;
			config.cancel = deferred;
			return config;
		}
		
		function onResponse(response) {
            var x = typeof response.data === 'string' &&
                response.data.indexOf('session has been expired') > -1;
            if (x) {
                location.reload();
                return response || $q.when(response);
            }
			return response || $q.when(response);
		}
		
		function onResponseError(response) {
			if (response.status === 401) {
				// user is not authenticated
                // console.error('user is not authenticated', response);
                // $window.location.href = '/#!/login';
                $state.go('login');
			}
			if (response.status === 403) {
				// user is not authenticated
                // $log.warn('operation forbidden', response);
			}
            if (response.status === 500) {
                // console.log('500', response);
                if (response.data.message === 'Invalid token.') {
                    // $state.go('login');
                    window.location.reload();
                }
            }
			// if (response.status === 404) {
			//     $log.error('request is not found', response);
			//     $window.location.href = '/#/404';
			// }
			
			return $q.reject(response);
		}
		
	}
	
})();
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('userService', userService);
	
	/** @ngInject */
	function userService($log, $http, host) {
		var base = host + 'user/';
		var service = {
			getUsers: getUsers
		};
		return service;
		
		////////////////
		
		function getUsers(params) {
			return $http.get(base, {params: params})
				.then(successCallback);
		}
		
		function successCallback(response) {
			return response.data;
		}
		
	}
	
})();<file_sep>package ir.saafta.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
public class DeletedUser {
    @Id
    private String username;
    private Integer credit;
    private Integer score;
    private Date deletionDate;
    private String deletedBy;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getCredit() {
        return credit;
    }

    public void setCredit(Integer credit) {
        this.credit = credit;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public Date getDeletionDate() {
        return deletionDate;
    }

    public void setDeletionDate(Date deletionDate) {
        this.deletionDate = deletionDate;
    }

    public String getDeletedBy() {
        return deletedBy;
    }

    public void setDeletedBy(String deletedBy) {
        this.deletedBy = deletedBy;
    }
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('EventController', EventController);

    /** @ngInject */
    function EventController($log, $ngConfirm, $scope, $stateParams, NgTableParams, eventService, userService, toastr, host, $q) {
        var vm = this;
        vm.title = 'EventController';
        vm.host = host;
        activate();
        vm.users = [];

        ////////////////

        function activate() {
            $log.debug('Event module activated');
            $q.all([getUsers()]).then(function (data) {
                data[0].forEach(function (user) {
                    vm.users.push({
                        id: user.username,
                        title: user.completeName
                    });
                });
                vm.eventTable = new NgTableParams({
                    page: 1,
                    count: 20
                }, {
                    getData: getEventList
                });
            });
        }

        function getEventList(tabelparams) {
            vm.loading = true;
            var params = {
                page: tabelparams.page() - 1,
                size: tabelparams.count(),
                sort: null
            };
            angular.forEach(tabelparams.sorting(), function (value, key) {
                params.sort = key + ',' + value;
            });
            if (!params.sort) params.sort = 'time,desc';
            var search = {
                content: tabelparams.filter().content ? tabelparams.filter().content : null,
                username: tabelparams.filter().user ? tabelparams.filter().user.id : null,
                contentId: tabelparams.filter().contentId ? tabelparams.filter().contentId.id : null,
                path: $stateParams.category ? $stateParams.category : null
            };
            return eventService.getEventList(params, search).then(function (data) {
                tabelparams.total(data.totalElements);
                vm.loading = false;
                return data.content;
            });
        }

        function getUsers() {
            return userService.getAllUsers();
        }

    }

})();<file_sep>angular.module('appKitFormValidationDemo', [
    'appKitCommon',
    'appKit'
]).controller('AppKitFormValidationDemo', function ($scope) {
    'use strict';

    $scope.hobbyOptions = ['skiing', 'runing', 'eating', 'sleeping', 'reading', 'coding'];
    $scope.hobbies = {};

    $scope.noneOrAtLeastSelected = function (object, minCount) {
        var count = 0;
        minCount = minCount || 1;

        count = object && Object.keys(object).filter(function (key) {
                return !!object[key];
            }).length;

        return !(count === 0 || count >= minCount);
    };
});
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('homeService', homeService);
	
	/** @ngInject */
	function homeService($log, $http, host) {
        var base = host + 'home/';
        var service = {
            getPublishedBanners: getPublishedBanners,
            getSuggestedApps: getSuggestedApps,
            getNewApps: getNewApps,
            getMostSeenApps: getMostSeenApps,
            getBestApps: getBestApps
        };
        return service;

        ////////////////

        function getPublishedBanners(params) {
            return $http.get(host + "banner/published", {params: params}).then(successCallback);
        }

        function getSuggestedApps() {
            return $http.get(host + "application/suggested").then(successCallback);
        }

        function getNewApps() {
            return $http.get(host + "application/new").then(successCallback)
        }

        function getMostSeenApps() {
            return $http.get(host + "application/mostSeen").then(successCallback);
        }

        function getBestApps() {
            return $http.get(host + "application/best").then(successCallback);
        }

        function successCallback(response) {
            return response.data;
        }
		
	}
	
})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('ApplicationController', ApplicationController);

    /** @ngInject */
    function ApplicationController($log, applicationService, host, $stateParams) {
        var vm = this;
        vm.title = 'ApplicationController';

        activate();
        vm.host = host;
        vm.getStarClass = getStarClass;
        vm.responsiveSetting = [
            {
                breakpoint: 964,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: true
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: true
                }
            }
        ];
        vm.slickConfig4 = {
            method: {},
            dots: true,
            infinite: true,
            speed: 300,
            slidesToShow: 1,
            centerMode: true,
            variableWidth: true
        };
        vm.number4 = [{label: 225}, {label: 125}, {label: 200}, {label: 175}, {label: 150}, {label: 180}, {label: 300}, {label: 400}];
        ////////////////

        function activate() {
            $log.debug('Application module activated');
            getApplication();
        }

        function getApplication() {
            if ($stateParams.id)
                applicationService.getApplication($stateParams.id).then(function (response) {
                    vm.application = response.data;
                })
        }

        function getStarClass(app, index) {
            if (app.rating - index > 1) {
                return "star";
            }
            else if (app.rating - index > 0) {
                return "star-half-o";
            } else {
                return "star-o";
            }
        }
    }

})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateBannerController', CreateUpdateBannerController);

    /** @ngInject */
    function CreateUpdateBannerController($log, $timeout, bannerService, $stateParams, toastr, $state,
                                          $window, host) {
        var vm = this;
        vm.title = 'CreateUpdateBannerController';
        vm.host = host;
        vm.method = $stateParams.method;
        vm.banner = {
            id: $stateParams.id
        };

        vm.bounds = {
            left: 0,
            right: 20,
            top: 0,
            bottom: 20
        };
        vm.cropperWidth = $window.innerWidth * 0.4;
        vm.save = save;
        vm.reset = reset;
        vm.getRatioDiff = getRatioDiff;
        vm.date = new Date();
        activate();

        ////////////////

        function activate() {
            $log.debug('Banner module activated');
            getBanner();
        }

        function save() {
            vm.loading = true;
            switch (vm.method) {
                case 'create':
                    bannerService.createBanner(vm.banner.label, vm.cropper.croppedImage)
                        .then(function (data) {
                            $timeout(function () {
                                vm.loading = false;
                                $state.go('root.banner');
                            }, 3000);
                            toastr.success('بنر با موفقیت افزوده شد.');
                        }, function () {
                            vm.loading = false;
                            toastr.error('خطا در ایجاد بنر!');
                        });
                    break;
                case 'update':
                    var croppedImage = vm.cropper ? vm.cropper.croppedImage : null;
                    bannerService.updateBanner(vm.banner.id, vm.banner.name, croppedImage)
                        .then(function (data) {
                            vm.loading = false;
                            vm.banner = data;
                            toastr.success('بنر با موفقیت ویرایش شد.');
                            vm.date = new Date();
                            vm.cropper = null;
                        }, function () {
                            vm.loading = false;
                            toastr.error('خطا در ویرایش بنر!');
                        });
                    break;
            }
        }


        function reset() {
            switch (vm.method) {
                case 'create':
                    vm.banner = {};
                    break;
                case 'update':
                    getBanner();
            }
        }

        function getBanner() {
            if (vm.banner.id) {
                vm.loading = true;
                bannerService.getBanner(vm.banner.id).then(function (data) {
                    vm.loading = false;
                    vm.banner = data;
                });
            }
        }

        function getRatioDiff() {
            return Math.abs((vm.bounds.right - vm.bounds.left) / (vm.bounds.top - vm.bounds.bottom) - (880 / 300));
        }

    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
        .factory('ownerService', ownerService);
	
	/** @ngInject */
    function ownerService($log, $http, host) {
        var base = host + 'owner/';
		var service = {
            getOwners: getOwners,
            getAllOwners: getAllOwners,
            getOwner: getOwner,
            createOwner: createOwner,
            updateOwner: updateOwner,
            deleteOwner: deleteOwner
		};
		return service;

        function successCallback(response) {
            return response.data;
        }
		////////////////

        function createOwner(owner) {
            return $http.post(base, owner)
                .then(successCallback);
        }


        function getOwners(params) {
			return $http.get(base, {params: params})
				.then(successCallback);
		}

        function getAllOwners() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getOwner(id) {
            var url = base + id;
            return $http.get(url)
                .then(successCallback);
        }


        function updateOwner(owner) {
            return $http.put(base, owner)
                .then(successCallback);
        }


        function deleteOwner(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }



	}
	
})();<file_sep>/**
 * Created by reza on 11/14/16.
 */

(function () {
    'use strict';

    angular
        .module('app')
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('root.banner', {
                controller: 'BannerController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/banner/list-banner.html',
                url: '/banner'
            })
            .state('root.createUpdateBanner', {
                controller: 'CreateUpdateBannerController',
                controllerAs: 'vm',
                data: {
                    roles: [
                        "admin"
                    ]
                },
                resolve: {},
                templateUrl: 'app/components/banner/create-update-banner.html',
                url: '/banner/:method?id'
            })

        ;
    }

})();
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CommentController', CommentController);

    /** @ngInject */
    function CommentController($log, $ngConfirm, $scope, NgTableParams, commentService, userService, contentService, toastr, host, $q) {
        var vm = this;
        vm.title = 'CommentController';
        vm.host = host;

        vm.delete = Delete;
        vm.approve = approve;
        vm.reject = reject;
        activate();
        vm.users = [];
        vm.contents = [];
        ////////////////

        function activate() {
            $log.debug('Comment module activated');
            $q.all([getUsers(), getContents()]).then(function (data) {
                data[0].forEach(function (user) {
                    vm.users.push({
                        id: user.username,
                        title: user.completeName
                    });
                });
                data[1].forEach(function (content) {
                    if (content.title && content.title !== "") {
                        console.log(content.title);
                        vm.contents.push({
                            id: content.id,
                            title: content.title
                        });
                    }
                });
                console.log(vm.users);
                vm.commentTable = new NgTableParams({
                    page: 1,
                    count: 20
                }, {
                    getData: getCommentList
                });
            });

        }

        function Delete(id) {
            $ngConfirm({
                title: 'حذف نظر',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            commentService.deleteComment(id)
                                .then(function () {
                                    toastr.success('نظر با موفقیت حذف شد.');
                                    vm.commentTable.reload();
                                    vm.loading = false;
                                }, function () {
                                    toastr.error('خطا در حذف نظر!');
                                    vm.loading = false;
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });

        }

        function getCommentList(tabelparams) {
            // console.log(tabelparams.filter());
            vm.loading = true;
            var params = {
                page: tabelparams.page() - 1,
                size: tabelparams.count(),
                sort: 'date,desc',
                content: tabelparams.filter().content ? tabelparams.filter().content : null,
                username: tabelparams.filter().user ? tabelparams.filter().user.id : null,
                contentId: tabelparams.filter().contentId ? tabelparams.filter().contentId.id : null
            };
            return commentService.getCommentList(params).then(function (data) {
                tabelparams.total(data.totalElements);
                vm.loading = false;
                return data.content;
            });
        }

        function approve(comment) {
            commentService.approveComment(comment.id).then(function () {
                toastr.success('نظر با موفقیت تائید شد.');
                vm.commentTable.reload();
            }, function () {
                toastr.error('خطا در تائید نظر!');
            });
        }

        function reject(comment) {
            commentService.rejectComment(comment.id).then(function () {
                toastr.success('نظر با موفقیت رد شد.');
                vm.commentTable.reload();
            }, function () {
                toastr.error('خطا در رد نظر!');
            });
        }

        function getUsers() {
            return userService.getAllUsers();
        }

        function getContents() {
            return contentService.getAllContents();
        }


    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.directive('commandButtons', commandButtons);
	
	/** @ngInject */
	function commandButtons() {
		var directive = {
			bindToController: true,
			controller: ButtonsController,
			controllerAs: 'vm',
			restrict: 'E',
			scope: {
				cancel: '&?',
				delete: '&?',
				disabled: '=?',
				edit: '&?',
				toggle: '=?'
			},
			templateUrl: 'app/directives/ng-table/command-buttons.html'
		};
		return directive;
		
	}
	
	/** @ngInject */
	function ButtonsController() {
		/* jshint validthis: true */
		var vm = this;
		vm.toggled = toggled;
		
		function toggled() {
			vm.toggle = !vm.toggle;
		}
	}
	
})();<file_sep>package ir.saafta.repo;

import ir.saafta.model.Category;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by reza on 11/12/16.
 */
public interface CategoryRepository extends PagingAndSortingRepository<Category, Long> {
}
<file_sep>package ir.saafta.conf;

import ir.saafta.service.LoginAttemptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationFailureListener
        implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginAttemptService loginAttemptService;

    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
        WebAuthenticationDetails auth = (WebAuthenticationDetails)
                e.getAuthentication().getDetails();
        logger.info("AuthenticationFailureListener " + auth.getRemoteAddress());
    }
}<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .directive('appKitMenu', appKitMenu);

    /** @ngInject */
    function appKitMenu() {
        'use strict';
        return {
            restrict: 'AE',
            link: function (scope, element) {
                $(element).metisMenu();
            }
        };
    }

})();

<file_sep>package ir.saafta.web;

import com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider;
import ir.saafta.dto.ApplicationStatus;
import ir.saafta.exception.HttpUnauthorizedException;
import ir.saafta.model.Application;
import ir.saafta.model.Transaction;
import ir.saafta.model.User;
import ir.saafta.model.UserApp;
import ir.saafta.repo.ApplicationRepository;
import ir.saafta.repo.TransactionRepository;
import ir.saafta.repo.UserAppRepository;
import ir.saafta.service.MultipartFileSender;
import ir.saafta.service.UserDetailManager;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by Reza on 1/20/2017.
 */
@RestController
@RequestMapping("/download")
public class DownloadController {
    private final String simorghPackage = "ir.simorghmarket.simorgh";

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ApplicationRepository applicationRepository;
    private UserDetailManager userDetailManager;
    private UserAppRepository userAppRepository;
    private TransactionRepository transactionRepository;

    @Autowired
    public DownloadController(ApplicationRepository applicationRepository, UserDetailManager userDetailManager,
                              UserAppRepository userAppRepository, TransactionRepository transactionRepository) {
        this.applicationRepository = applicationRepository;
        this.userDetailManager = userDetailManager;
        this.userAppRepository = userAppRepository;
        this.transactionRepository = transactionRepository;
    }

    @ResponseBody
    @RequestMapping(value = "/{appId}/*.apk", method = RequestMethod.GET)
    public void install(@PathVariable Long appId, String phoneNumber, Authentication authentication,
                        HttpServletRequest request, HttpServletResponse response) throws Exception {
        Application application = applicationRepository.findOne(appId);
        logger.info("Download application with id " + application.getId());
        logger.info("\tFile id is  " + application.getLastFile().getId());
        if(application.getFee() == null)
            application.setFee(0);

        //  if this is an anonymous user and app is free
        if(authentication == null && application.getFee() == 0) {
            //  check if it comes from application
            if (request.getHeader("User-Agent").startsWith("app_") || request.getHeader("User-Agent").startsWith("safeHome_")) {
                logger.info("Installing app anonymously with id " + application.getId());
                UserApp userApp = userAppRepository.findBySessionAndContent(request.getHeader("User-Agent"), application);
                if (userApp == null) {
                    userApp = new UserApp();
                    userApp.setContent(application);
                    userApp.setSession(request.getHeader("User-Agent"));
                    userApp.setInstallDate(new Date());
                    application.setInstallationCount(application.getInstallationCount() == null ? 1 : application.getInstallationCount() + 1);
                    userAppRepository.save(userApp);
                    applicationRepository.save(application);
                    logger.info("free ( " + request.getHeader("User-Agent") + " ): Application installation count updated to " + application.getInstallationCount());
                }
                MultipartFileSender.fromFile(application.getLastFile()).with(request).with(response).serveResource();
            }
            return;
        } else if (authentication == null) { //  if app is not free and user ins anonymous raise an exception
            throw new HttpUnauthorizedException();
        }
        String username = authentication.getName();
        User user = (User) userDetailManager.loadUserByUsername(username);
        if(user.getCredit() == null)
            user.setCredit(0);
        logger.info("username: " + username + ", application fee: " + application.getFee());
        UserApp userApp = userAppRepository.findByUserAndContent(user, application);
        //  if user in just installing the application
        if (userApp == null || userApp.getInstallDate() == null) {
            logger.info("First time download");
            //  if user has enough credit to get the app
            if (user.getCredit() >= application.getFee()) {
                //  register a transaction
                Transaction transaction = new Transaction(new Date(), application.getFee(),
                        "buy", null, application, username);
                transaction = transactionRepository.save(transaction);
                logger.info("Transaction saved( user: " + transaction.getUsername() +
                        ", appId:" + transaction.getApplication().getId() +
                        ", type:" + transaction.getType() +
                        ", amount:" + transaction.getAmount() +
                        ", id:" + transaction.getId() +
                        " @" + transaction.getDate()
                );
                //  update user credit
                logger.info("Update user credit from " + user.getCredit());
                user.setCredit(user.getCredit() - application.getFee());
                user = userDetailManager.save(user);
                logger.info("Update user credit to " + user.getCredit());
                //  register a new user-application object or update existing one
                if (userApp == null) {
                    userApp = new UserApp(user, application, new Date(), phoneNumber);
                }
                else
                    userApp.setInstallDate(new Date());
                userApp.setBought(application.getFee() != null && application.getFee() > 0);
                // now increment installation count of the application as it is getting installed by the user
                int installationCount = application.getInstallationCount() == null ? 1 : application.getInstallationCount() + 1;
                application.setInstallationCount(installationCount);
                application = applicationRepository.save(application);
                logger.info("Application installation count updated to " + application.getInstallationCount());
            } else {
                logger.info("User has not enough credit to buy the app");
                throw new AccessDeniedException("You should be logged in to download non-free applications");
            }
        }
        //  update the version that user has installed in the storage
        userApp.setCurrentVersion(application.getLastFile().getVersion());
        userApp = userAppRepository.save(userApp);
        logger.info("UserApp (id: " + userApp.getId() + ")");
        if (request.getHeader("User-Agent").startsWith("app_") || request.getHeader("User-Agent").startsWith("safeHome_"))
            MultipartFileSender.fromFile(application.getLastFile()).with(request).with(response).serveResource();
    }


    @ResponseBody
    @RequestMapping(value = "/simorgh/*.apk", method = RequestMethod.GET)
    public void installSimorgh(HttpServletResponse response, HttpServletRequest request) throws Exception {
        ApplicationStatus status = request.getHeader("User-Agent").startsWith("safeHome_") ?
                ApplicationStatus.LAUNCHER : ApplicationStatus.NON_LAUNCHER;
        Application simorgh = applicationRepository.findByAppPackageAndStatus(simorghPackage, status);
        if (simorgh == null || simorgh.getLastFile() == null)
            return;
        MultipartFileSender.fromFile(simorgh.getLastFile()).with(request).with(response).serveResource();
    }

    @ResponseBody
    @RequestMapping(value = "/{appId}", method = RequestMethod.DELETE)
    public void uninstall(@PathVariable Long appId, String username, String phoneNumber) {
        User user = (User) userDetailManager.loadUserByUsername(username);
        Application application = applicationRepository.findOne(appId);
        UserApp userApp = userAppRepository.findByUserAndContent(user, application);
        if (userApp != null) {
            userApp.setUninstallDate(new Date());
            userAppRepository.save(userApp);
        }
    }
}
<file_sep>package ir.saafta.repo;

import ir.saafta.model.Application;
import ir.saafta.model.Content;
import ir.saafta.model.User;
import ir.saafta.model.UserApp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;


/**
 * Created by Reza on 1/20/2017.
 */
public interface UserAppRepository extends PagingAndSortingRepository<UserApp, Long> {
    UserApp findByUserAndContent(User user, Content content);

    UserApp findByPhoneNumberAndContent(String phoneNumber, Content content);
    UserApp findBySessionAndContent(String session, Content content);

    Page<UserApp> findByUser(Pageable pageable, User user);
    Page<UserApp> findByUserAndBookmarked(Pageable pageable, User user, Boolean bookmarked);
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateUserController', CreateUpdateUserController);

    /** @ngInject */
    function CreateUpdateUserController($log, $ngConfirm, toastr, userService, userGroupService, $stateParams, host, util,
                                        $scope, $timeout, $state, principal) {
        var vm = this;
        vm.title = 'CreateUpdateUserController';
        vm.tmpData = new Date();    //  to display image content after change
        vm.host = host;
        vm.method = $stateParams.method;
        vm.user = {
            username: $stateParams.username,
            authority: null
        };
        vm.errors = [];

        vm.save = save;
        vm.reset = reset;
        vm.resetPassword = <PASSWORD>;
        vm.addCredit = addCredit;
        vm.reduceCredit = reduceCredit;
        vm.saveProfilePicture = saveProfilePicture;
        vm.deleteProfilePicture = deleteProfilePicture;
        vm.checkUsername = checkUsername;
        vm.checkEmail = checkEmail;
        vm.checkMobilePhone = checkMobilePhone;
        vm.getError = getError;
        vm.checkField = checkField;
        vm.checkErrors = checkErrors;
        vm.addGroup = addGroup;
        vm.removeGroup = removeGroup;
        vm.isAdmin = false;
        activate();

        ////////////////

        function activate() {
            $log.debug('User module activated', $stateParams.username);

            getUserGroups();
            principal.identity().then(function (currentUser) {
                vm.me = currentUser.username === vm.user.username;
                currentUser.authorities.forEach(function (auth) {
                    if (auth.authority === "admin") {
                        vm.isAdmin = true;
                    }
                });
                if (vm.method === 'update') {
                    if (vm.isAdmin && vm.user.username !== 'me') {
                        getAuthorities().then(getUser);
                    }
                    else if (vm.user.username === 'me') {
                        getMe();
                        vm.me = true;
                    }
                } else {
                    getAuthorities().then(function (data) {
                        vm.userAuthority = data.filter(function (authority) {
                            return authority.authority === 'user';
                        })[0];
                    });
                }
            });

        }

        function checkForm(form) {
            if(!form || form.$valid)
                return;
            if (form.$error.unique) {
                form.$error.unique.forEach(function (item) {
                    vm.errors.push({
                        name: item.$name,
                        caption: item.$name + ' is redundant'
                    })
                })
            }

            if(form.$error.pattern) {
                form.$error.pattern.forEach(function (item) {
                    vm.errors.push({
                        name: item.$name,
                        caption: item.$name + ' does not have valid value'
                    })
                })
            }

            if(form.$error.required) {
                form.$error.required.forEach(function (item) {
                    vm.errors.push({
                        name: item.$name,
                        caption: item.$name + ' is required'
                    })
                })
            }
        }

        function checkErrors(userForm) {
            vm.errors = [];
            // console.log('userForm',userForm);
            // console.log('userInfoForm', userInfoForm);
            if(vm.user.password && vm.user.password !== <PASSWORD>)
                vm.errors.push({
                    name: 'checkPassword',
                    caption: 'Password does not match entered amount'
                });
            checkForm(userForm);
            // checkForm(userInfoForm);
        }
        function save(userForm) {
            checkErrors(userForm);
            if(vm.errors.length > 0)
                return;
            vm.user.authorities = [];
            vm.user.authorities.push({
                authority: vm.userAuthority.authority,
                username: vm.user.username
            });

            vm.loading = true;
            switch (vm.method) {
                case 'create':
	                userService.createUser(vm.user).then(function () {
                        toastr.success('کاربر با موفقیت  ایجاد شد.');
		                $timeout(function () {
                            vm.loading = false;
			                $state.go('root.createUpdateUser', {'method':'update', 'username':vm.user.username});
		                }, 3000);
                    }, function (error) {
                        vm.loading = false;
                        toastr.error('خطا در ایجاد کاربر!');
	                });
                    break;
                case 'update':
	                userService.updateUser(vm.user).then(function () {
                        vm.loading = false;
                        toastr.success('کابر با موفقیت به روزرسانی شد.');
	                }, function () {
                        vm.loading = false;
		                toastr.error('خطا در به روزرسانی کاربر!');
	                });
                    break;
                default:
                    vm.loading = false;
            }
        }

        function getAuthorities() {
            return userService.getAuthorities().then(function (data) {
                return vm.authorities = data;
            });
        }

        function getCaption(authority) {
            for (var i = 0; i < vm.authorities.length; i++) {
                if (vm.authorities[i].authority === authority)
                    return vm.authorities[i].caption;
            }
        }

        function reset(form) {
            vm.errors = [];
            switch (vm.method) {
                case 'create':
                    if(form) {
                        angular.forEach(form, function (value, key) {
                            if(key.indexOf('$') < 0){
                                value.$$rawModelValue = null;
                                value.$$lastCommittedViewValue = null;
                                value.$$rawModelValue = null;
                                value.$viewValue = null;
                                value.$error = {};
                                value.$render();
                                console.log(key, value);
                            }
                        });
                        form.$error = {};
                    }
                    vm.user = {
                        authorities: []
                    };
                    break;
                case 'update':
                    getUser();
            }
        }

        function getUser() {
            vm.userAuthorities = [];
            if (vm.user.username) {
                vm.loading = true;
                userService.getUser(vm.user.username).then(function (data) {
                    vm.user = data;
                    // console.log(data);
                    vm.passwordCheck = <PASSWORD>;
                    vm.user.authorities.forEach(function (authority) {
                        vm.userAuthority = {
                            "authority": authority.authority,
                            "caption": getCaption(authority.authority)
                        };
                    });
                    vm.loading = false;
                }, function () {
                    vm.loading = false;
                });
            }
        }

        function getMe() {
            vm.loading = true;
            return userService.getMe().then(function (data) {
                vm.user = data;
                vm.loading = false;
            }, function () {
                vm.loading = false;
            });
        }
        function resetPassword() {
            vm.loading = true;
            if (vm.isAdmin) {
                userService.resetPassword(vm.user.username, vm.user.password).then(function () {
                    vm.loading = false;
                    toastr.success('کلمه عبور با موفقیت به روزرسانی شد.');
                }, function () {
                    vm.loading = false;
                    toastr.error('خطا در به روزرسانی کلمه عبور!');
                });
            } else {
                userService.updatePassword(vm.user.username, vm.user.password, vm.user.oldPassword).then(function () {
                    vm.loading = false;
                    toastr.success('کلمه عبور با موفقیت به روزرسانی شد.');
                }, function () {
                    vm.loading = false;
                    toastr.error('خطا در به روزرسانی کلمه عبور!');
                });
            }

        }

        function addCredit() {
            userService.addCredit(vm.user.username, vm.creditToAdd, vm.creditComment).then(function (data) {
                toastr.success('اعتبار با موفقیت افزوده شد.');
                vm.user.credit = data;
                vm.creditToAdd = null;
                vm.creditComment = null;
            }, function () {
                toastr.error('خطا در افزایش موجودی!');
            });
        }

        function deleteProfilePicture() {
            $ngConfirm({
                title: 'حذف تصویر کاربری',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function(scope, button){
                            vm.loading = true;
                            userService.deleteProfilePicture(vm.user.username).then(function () {
                                util.toast('success','تصویر با موفقیت حذف شد.');
                                vm.user.profilePicture = null;
                                vm.loading = false;
                            }, function () {
                                util.toast('error','خطا در حذف تصویر!');
                                vm.loading = false;
                            });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function(scope, button){
                            return true;
                        }
                    }
                }
            });

        }

        function reduceCredit() {
            userService.addCredit(vm.user.username, vm.creditToAdd * -1, vm.creditComment).then(function (data) {
                toastr.success('اعتبار با موفقیت کسر شد.');
                vm.user.credit = data;
                vm.creditToAdd = null;
                vm.creditComment = null;
            }, function () {
                toastr.error('خطا در کاهش موجودی!');
            });
        }

        function saveProfilePicture(dataUrl) {
            vm.loading = true;
            userService.saveProfilePicture(vm.user.username, dataUrl)
                .then(function (response) {
                    vm.user.profilePicture = response;
                    vm.tmpData = new Date();
                    util.toast('success', 'تصویر کاربری با موفقیت به روزرسانی شد.');
                    vm.cropper = {};
                    vm.cropper.sourceImage = null;
                    vm.cropper.croppedImage = null;
                    vm.loading = false;
                }, function (error) {
                    if (error.status > 0) {
                        vm.errorMsg = error.status + ': ' + error.data;
                    }
                    util.toast('error', 'خطا در بارگذاری تصویر!');
                    vm.loading = false;
                });
        }

        function getUserGroups() {
            userGroupService.getAllUserGroups().then(function (data) {
                vm.groups = data;
            })
        }

        function checkUsername(form) {
            vm.loading = true;
            userService.usernameIsValid(vm.user.username).then(function (isValid) {
                form.username.$setValidity('unique', isValid);
                vm.loading = false;
            }, function (error) {
                vm.loading = false;
            });
        }

        function checkEmail(form) {
            // console.log('checkEmail');
            vm.loading = true;
            return userService.emailIsValid(vm.user.email, vm.user.username).then(function (isValid) {
                form.email.$setValidity('unique', isValid);
                vm.loading = false;
                checkErrors(form);
            }, function (error) {
                vm.loading = false;
            });
        }

        function checkMobilePhone(form) {
            vm.loading = true;
            userService.mobilePhoneIsValid(vm.user.mobilePhone, vm.user.username).then(function (isValid) {
                form.mobilePhone.$setValidity('unique', isValid);
                vm.loading = false;
                checkErrors(form);
            }, function (error) {
                vm.loading = false;
            });
        }

        function getError(name) {
            // console.log('getError');
            var res = null;
            for(var i = 0; i < vm.errors.length; i++) {
                if(vm.errors[i].name === name)
                    res = vm.errors[i];
            }
            return res;
        }
        function checkField(field) {
            // console.log('checkField', field, getError(field.$name));
            if(field.$name === 'email')
                checkEmail(field).then(function () {
                    check();
                });
            else
                check();

            function check() {
                if(!field || field.$valid || getError(field.$name))
                    return;
                if (field.$error.unique) {
                    vm.errors.push({
                        name: field.$name,
                        caption: field.$name + ' is redundant'
                    })
                }

                if(field.$error.pattern) {
                    vm.errors.push({
                        name: field.$name,
                        caption: field.$name + ' does not have valid value'
                    })
                }

                if(field.$error.required) {
                    vm.errors.push({
                        name: field.$name,
                        caption: field.$name + ' is required'
                    })
                }
            }
        }

        function addGroup() {
            userService.addGroup(vm.user.username, vm.group.id).then(function (success) {
                vm.user.userGroups.push(angular.copy(vm.group));
                util.toast('success', 'گروه با موفقیت افزوده شد.');
            }, function (error) {
                util.toast('error', 'خطا در افزودن گروه به کاربر');
            })
        }

        function removeGroup(group) {
            userService.removeGroup(vm.user.username, group.id).then(function (success) {
                if (!vm.user.userGroups)
                    vm.user.userGroups = [];
                var i = 0;
                for (i; i < vm.user.userGroups.length; i++) {
                    if (vm.user.userGroups[i].id === group.id)
                        break;
                }
                vm.user.userGroups.splice(i, 1);
                util.toast('success', 'گروه با موفقیت حذف شد.');
            }, function (error) {
                util.toast('error', 'خطا در حذف گروه از کاربر');
            })
        }

        var stillClearPassword = vm.user.password !== undefined && vm.user.password !== null;
        $scope.$watch(angular.bind(this, function () {
            return this.user.password;
        }), function (newVal) {
            if (stillClearPassword && newVal !== undefined && newVal !== null) {
                vm.user.password = '';
                stillClearPassword = false;
            }
        });
    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('UserController', UserController);
	
	/** @ngInject */
	function UserController($log, NgTableParams, userService) {
		var vm = this;
		vm.title = 'UserController';
		vm.userTable = new NgTableParams({
			page: 0,
			count: 20
		}, {
			getData: getUsers
		});
		
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('User module activated');

		}
		
		function getUsers(tabelparams) {
			var params = {
				page: tabelparams.page(),
				size: tabelparams.count()
			};
			return userService.getUsers(params).then(function (data) {
				tabelparams.total(data.totalElemets);
				return data.content;
			});
		}
		
		
	}
	
})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .directive('appKitModule', appKitModule);

    /** @ngInject */
    function appKitModule() {
        'use strict';
        return {
            restrict: "AE",
            transclude: {
                'more': '?moreMenu',
                'body': 'paneBody',
                'footer': '?paneFooter'
            },
            replace: true,
            require: '?^^appKitMasonry',
            templateUrl: 'app/directives/appKitModule/appKitModule.html',
            scope: {
                wrapperClass: '@',
                moduleClass: '@',
                contentClass: '@',
                title: '@',
                meta: '@',
                controls: "=?",
                collapsed: '@'
            },
            link: function (scope, element, attrs, appKitMasonry, transclude) {
                if (typeof scope.controls === 'undefined') {
                    scope.controls = !!appKitMasonry;
                }

                if (typeof scope.collapsed === 'undefined') {
                    scope.collapsed = false;
                }

                scope.showFooter = transclude.isSlotFilled('footer');
                scope.showMore = transclude.isSlotFilled('more');

                if (typeof scope.wrapperClass === 'undefined') {
                    if (scope.title || scope.meta) {
                        scope.wrapperClass = 'module-headings';
                    } else {
                        scope.wrapperClass = 'module-headings';
                    }
                }

                if (appKitMasonry) {
                    appKitMasonry.layout();
                }

                scope.closeModule = function (ev) {
                    if (appKitMasonry) {
                        appKitMasonry.closeModule($(ev.target).closest(appKitMasonry.selector));
                    } else {
                        $(element).remove();
                    }
                };

                scope.collapseModule = function (ev) {
                    scope.collapsed = !scope.collapsed;
                };
            }
        };
    }

})();

<file_sep>package ir.saafta.repo;

import ir.saafta.dto.SessionStatus;
import ir.saafta.model.Session;
import ir.saafta.model.SpringSession;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.ArrayList;

/**
 * Created by rkesh on 6/30/2017.
 */
public interface SpringSessionRepository extends PagingAndSortingRepository<SpringSession, String> {
    ArrayList<SpringSession> findAllByPrincipalNameIsNotNull();
}
<file_sep>/**
 * Created by Reza on 11/19/2016.
 */

(function () {
    'use strict';

    angular
        .module('app')
        .controller('CreateUpdateFileController', CreateUpdateFileController);

    /** @ngInject */
    function CreateUpdateFileController(host, file, application, $timeout, Upload) {
        var vm = this;
        vm.application = application;
        vm.file = file | {};

        vm.uploadFile = uploadFile;

        function uploadFile(file) {
            file.upload = Upload.upload({
                url: host + '/application/4/file',
                data:{username: 'reza', file: file}
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                });
            },
                function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            },
                function (evt) {
                // Math.min is to fix IE which reports 200% sometimes
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }




    }
});
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('CreateUpdateAdController', CreateUpdateAdController);
	
	/** @ngInject */
    function CreateUpdateAdController($log, $timeout, adService, userService, $stateParams, toastr,
                                      $state, $filter, host, $window) {
		var vm = this;
		vm.title = 'CreateUpdateAdController';
		vm.method = $stateParams.method;
		vm.ad = {
			id: $stateParams.id
		};

        vm.bounds = {
            left: 0,
            right: 20,
            top: 0,
            bottom: 20
        };
        vm.cropperWidth = $window.innerWidth * 0.4;

        vm.host = host;
		vm.save = save;
		vm.reset = reset;
		vm.date = new Date();
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('Ad module activated');
			getAd();
            getUsers();
		}
		
		function save() {
            var ad = angular.copy(vm.ad);
            ad.fromDate = $filter('sDate')(vm.ad.fromDate);
            ad.toDate = $filter('sDate')(vm.ad.toDate);
            ad.username = vm.ad.user.username;
            console.log('save');
            vm.loading = true;
			switch (vm.method) {
				case 'create':
                    adService.createAd(ad, vm.cropper.croppedImage)
						.then(function (data) {
							$timeout(function () {
								$state.go('root.ad');
                                vm.loading = false;
                            }, 1000);
							toastr.success('تبلیغات با موفقیت افزوده شد.');
						}, function () {
                            vm.loading = false;
							toastr.error('خطا در ایجاد تبلیغات!');
						});
					break;
				case 'update':
					console.log('save ', vm.ad);
					var croppedImage = vm.cropper ? vm.cropper.croppedImage : null;
                    adService.updateAd(vm.ad.id, ad, croppedImage)
                        .then(function (response) {
                            getAd(response.data);
							toastr.success('تبلیغات با موفقیت ویرایش شد.');
							vm.date = new Date();
							vm.cropper = null;
                            vm.loading = false;
						}, function () {
                            vm.loading = false;
							toastr.error('خطا در ویرایش تبلیغات!');
						});
					break;
			}
		}
		
		
		function reset() {
			switch (vm.method) {
				case 'create':
					vm.ad = {};
					break;
				case 'update':
					getAd();
			}
		}

        function getAd(ad) {
            if (ad) {
                loadAd(ad);
            }
            else if (vm.ad.id) {
                vm.loading = true;
				adService.getAd(vm.ad.id).then(function (data) {
                    loadAd(data);
                    vm.loading = false;
                }, function () {
                    util.toast('error', 'APP.MESSAGES.FAILURE');
                    vm.loading = false;
                });
			}

            function loadAd(advertisement) {
                vm.ad = advertisement;
                vm.ad.label = advertisement.picture.label;
            }
		}

        function getUsers() {
            userService.getAllUsers().then(function (data) {
                vm.users = data;
            }, function () {
                toastr.error('خطا در بارگذاری لیست کاربران!')
            });
        }
		
	}
	
})();<file_sep>package ir.saafta.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by reza on 11/12/16.
 */
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        logger.info("RestAuthenticationEntryPoint");
    }
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .directive('appKitResponsive', appKitResponsive);

    /** @ngInject */
    function appKitResponsive($window) {
        'use strict';
        return {
            restrict: 'AE',
            link: function (scope, element) {
                $window = angular.element($window);

                function adaptToScreenSize() {
                    scope.compact = $window.width() <= 1200;
                    scope.mobile = $window.width() <= 768;
                }

                scope.navOpen = false;
                scope.showFooter = true;

                $window.bind('resize', function () {
                    scope.$apply(adaptToScreenSize);
                });

                $window.bind('load', function () {
                    $(element).removeClass('preload');
                });

                adaptToScreenSize();
            }
        };
    }

})();

<file_sep>CREATE TABLE `user_content` (
  `id`           BIGINT(20) NOT NULL AUTO_INCREMENT,
  `username`     VARCHAR(50),
  `content_id`   BIGINT(20),
  `phone_number` VARCHAR(14),
  `rating`       DOUBLE              DEFAULT 0,
  PRIMARY KEY (`id`)
);

INSERT INTO `user_content` (
  `id`,
  `username`,
  `content_id`,
  `phone_number`,
  `rating`
) SELECT

    id,
    username,
    app_id,
    phone_number,
    rating
  FROM user_app;

ALTER TABLE `user_app`
  DROP COLUMN `username`,
  DROP COLUMN `app_id`,
  DROP COLUMN `phone_number`,
  DROP INDEX `user_app_fk1_username`,
  DROP INDEX `user_app_fk2_app_id`,
  DROP FOREIGN KEY `user_app_fk1_username`,
  DROP FOREIGN KEY `user_app_fk2_app_id`;


ALTER TABLE `user_app`
  CHANGE `id` `id` BIGINT(20) UNSIGNED NOT NULL,
  DROP PRIMARY KEY;

ALTER TABLE `user_content`
  CHANGE `id` `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;

ALTER TABLE `user_app`
  ADD CONSTRAINT `user_app_user_content_id_fk` FOREIGN KEY (`id`) REFERENCES `user_content` (`id`)
  ON UPDATE CASCADE
  ON DELETE CASCADE;

ALTER TABLE `user_content`
  CHANGE `content_id` `content_id` BIGINT(20) UNSIGNED NULL,
  ADD CONSTRAINT `user_content_user_username_fk` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
  ON UPDATE CASCADE
  ON DELETE CASCADE,
  ADD CONSTRAINT `user_content_content_id_fk` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`)
  ON UPDATE CASCADE
  ON DELETE CASCADE;
;

ALTER TABLE `feedback`
  CHANGE `rate` `rate` DOUBLE DEFAULT 0  NULL;

ALTER TABLE `user_content`
  CHANGE `rating` `rating` DOUBLE DEFAULT -1  NULL;

ALTER TABLE `feedback`
  CHANGE `liked` `liked` TINYINT(1) DEFAULT 0  NULL,
  CHANGE `disliked` `disliked` TINYINT(1) DEFAULT 0  NULL;

ALTER TABLE `application`
  ADD COLUMN `recently_updated` BINARY(1) DEFAULT '0'  NULL
  AFTER `last_file_id`;

ALTER TABLE `advertisement`
  ADD COLUMN `seen_count` BINARY(1) DEFAULT '0'  NULL
  AFTER `toDate`;

ALTER TABLE `advertisement`
  CHANGE `fromDate` `from_date` DATETIME NULL,
  CHANGE `toDate` `to_date` DATETIME NULL;

ALTER TABLE `news`
  DROP COLUMN `content_id`,
  CHANGE `context` `body` TEXT CHARSET utf8
COLLATE utf8_general_ci NULL,
  ADD COLUMN `writer` VARCHAR(60) NULL
  AFTER `date`,
  ADD COLUMN `lead` VARCHAR(200) NULL
  AFTER `writer`;

ALTER TABLE `user_app`
  ADD COLUMN `bookmarked` BINARY(1) DEFAULT '0'  NULL AFTER `current_version`;

ALTER TABLE `application`
  ADD COLUMN `installation_count` INT(11) DEFAULT 0  NULL
  AFTER `recently_updated`;

ALTER TABLE `application`
  ADD COLUMN `in_app_payment` BINARY(1) DEFAULT '0'  NULL
  AFTER `installation_count`;

ALTER TABLE `file`
    ADD COLUMN `minimum_android_version` VARCHAR(255) NULL AFTER `version`;

ALTER TABLE `access_file`
  CHANGE `id` `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;

ALTER TABLE `access_file`
  ADD  UNIQUE INDEX `Unique_file_access` (`access_id`, `file_id`);

ALTER TABLE `application`
  ADD COLUMN `suggestion_priority` BIGINT(20) UNSIGNED NULL AFTER `in_app_payment`;

CREATE TABLE `suggestion_priority` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `app_id` BIGINT(20) UNSIGNED,
  `priority` INT(2) UNSIGNED DEFAULT 0,
  PRIMARY KEY (`id`),
  CONSTRAINT `suggestion_priority_application` FOREIGN KEY (`app_id`) REFERENCES `application` (`id`)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);

ALTER TABLE `application`
  ADD COLUMN `suggested_app` BIGINT(1) DEFAULT 0  NULL AFTER `suggestion_priority`;

CREATE TABLE `event` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `time` DATETIME NOT NULL,
  `action` VARCHAR(50) NOT NULL,
  `username` VARCHAR(50),
  `remote_addr` VARCHAR(30),
  `host` VARCHAR(50),
  `session_id` VARCHAR(100),
  `Cookie` VARCHAR(200),
  `method` VARCHAR(10),
  `params` TEXT,
  `body` TEXT,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_event_user_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
    ON UPDATE CASCADE
    ON DELETE NO ACTION
);

ALTER TABLE `event`
  ADD COLUMN `user-agent` TEXT NULL AFTER `body`;

ALTER TABLE `event`
  ADD COLUMN `path` VARCHAR(50) NULL AFTER `user-agent`;

ALTER TABLE `event`
  CHANGE `user-agent` `user_agent` TEXT CHARSET utf8 COLLATE utf8_general_ci NULL;

ALTER TABLE `application`
  ADD CONSTRAINT `foreign_key_application_file_last_file` FOREIGN KEY (`last_file_id`) REFERENCES `file` (`id`)
  ON UPDATE CASCADE
  ON DELETE NO ACTION;

SET FOREIGN_KEY_CHECKS = 0;
ALTER TABLE `user`
  CHANGE `username` `username` VARCHAR(50)
CHARSET utf8
COLLATE utf8_bin NOT NULL;
SET FOREIGN_KEY_CHECKS = 1;

CREATE TABLE `session` (
  `session_id`    VARCHAR(100) NOT NULL,
  `username`      VARCHAR(50)  NOT NULL,
  `creation_time` DATETIME,
  `finish_time`   DATETIME,
  `status`        INT(1),
  `last_request`  TIMESTAMP,
  `remote_addr`   VARCHAR(30),
  `device_info`   VARCHAR(255),
  PRIMARY KEY (`session_id`)
);

ALTER TABLE `user_content`
  ADD COLUMN `install_date` DATETIME NULL
  AFTER `rating`,
  ADD COLUMN `uninstall_date` DATETIME NULL
  AFTER `install_date`,
  ADD COLUMN `current_version` VARCHAR(255) NULL
  AFTER `uninstall_date`,
  ADD COLUMN `bookmarked` BINARY(1) NULL
  AFTER `current_version`;

ALTER TABLE `company`
  ADD COLUMN `email` VARCHAR(50) NULL
  AFTER `url`,
  ADD COLUMN `phone_number` VARCHAR(15) NULL
  AFTER `email`,
  ADD COLUMN `type` INT(1) NULL
  AFTER `phone_number`;

RENAME TABLE
    `company` TO `owner`;

ALTER TABLE `application`
  CHANGE `company_id` `owner_id` BIGINT(20) UNSIGNED NULL;

ALTER TABLE `application`
  DROP INDEX `foreign_key_application_company`;

ALTER TABLE `application`
  ADD CONSTRAINT `foreign_key_application_owner` FOREIGN KEY (`owner_id`) REFERENCES `owner` (`id`)
  ON UPDATE CASCADE
  ON DELETE NO ACTION;

ALTER TABLE `comment`
  ADD COLUMN `approved` BINARY DEFAULT '0'   NULL
  AFTER `user_id`;

ALTER TABLE `application`
  CHANGE `app_package` `app_package` VARCHAR(255)
CHARSET utf8
COLLATE utf8_general_ci NOT NULL,
  CHANGE `name` `name` VARCHAR(255)
CHARSET utf8
COLLATE utf8_general_ci NOT NULL;

CREATE TABLE `user_group` (
  `id`      BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `title`   VARCHAR(50)         NOT NULL,
  `logo_id` BIGINT(20) UNSIGNED,
  PRIMARY KEY (`id`)
);

ALTER TABLE `user`
  ADD COLUMN `user_group_id` BIGINT(20) UNSIGNED NULL
  AFTER `imei`;

ALTER TABLE `user`
  ADD CONSTRAINT `user_fk2_group` FOREIGN KEY (`user_group_id`) REFERENCES `user_group` (`id`)
  ON UPDATE CASCADE
  ON DELETE NO ACTION;

ALTER TABLE `application`
  DROP FOREIGN KEY `foreign_key_application_category`;

ALTER TABLE `application`
  ADD CONSTRAINT `foreign_key_application_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)
  ON UPDATE CASCADE
  ON DELETE RESTRICT;


ALTER TABLE `application`
  CHANGE `category_id` `category_id` BIGINT(20) UNSIGNED NOT NULL;

ALTER TABLE `user`
  ADD UNIQUE INDEX `user_email_unique` (`email`),
  ADD UNIQUE INDEX `user_phoneNumber_unique` (`mobile_phone`);

ALTER TABLE `user_group`
  ADD UNIQUE INDEX `user_group_name_unique` (`title`);

ALTER TABLE `category`
  ADD UNIQUE INDEX `category_name_unique` (`name`);

ALTER TABLE `file`
  ADD UNIQUE INDEX `file_version_application_unique` (`application_id`, `version`);

ALTER TABLE `application`
  ADD COLUMN `disabled` BINARY(1) DEFAULT '0'   NULL
  AFTER `suggested_app`;

ALTER TABLE `user_content`
  ADD COLUMN `bought` BINARY(1) DEFAULT '0'   NULL
  AFTER `bookmarked`;

ALTER TABLE `application`
  ADD COLUMN `incomplete` BINARY(1) DEFAULT '1'  NULL AFTER `disabled`;

ALTER TABLE `user`
  CHANGE `name` `name` VARCHAR(45) CHARSET utf8 COLLATE utf8_persian_ci NULL,
  CHANGE `family` `family` VARCHAR(45) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `application`
  CHANGE `name` `name` VARCHAR(255) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `access`
  CHANGE `label` `label` VARCHAR(50) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `category`
  CHANGE `name` `name` VARCHAR(255) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `content`
  CHANGE `title` `title` VARCHAR(255) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `owner`
  CHANGE `name` `name` VARCHAR(255) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `role`
  CHANGE `caption` `caption` VARCHAR(50) CHARSET utf8 COLLATE utf8_persian_ci NULL;

ALTER TABLE `user_group`
  CHANGE `title` `title` VARCHAR(50) CHARSET utf8 COLLATE utf8_persian_ci NOT NULL;

ALTER TABLE `user`
  CHANGE `address` `address` TEXT CHARSET utf8
COLLATE utf8_general_ci NULL;

ALTER TABLE `access_file`
  CHANGE `access_id` `access_id` BIGINT(20) UNSIGNED NOT NULL;

ALTER TABLE `access_file`
  ADD CONSTRAINT `access_file_access_to_access` FOREIGN KEY (`access_id`) REFERENCES `access` (`id`);

CREATE TABLE `deleted_user` (
  `username` VARCHAR(50) CHARSET utf8 COLLATE utf8_bin NOT NULL,
  `deletion_date` DATETIME NOT NULL,
  `deleted_by` VARCHAR(50) CHARSET utf8 COLLATE utf8_bin NOT NULL,
  `credit` INT(11),
  `score` INT(11),
  PRIMARY KEY (`username`)
);

INSERT INTO `user_group` (`id`, `title`, `logo_id`) VALUES ('1', 'عمومی', NULL);

ALTER TABLE `user_content`
  ADD COLUMN `session` VARCHAR(100) NULL AFTER `bought`,
  ADD  UNIQUE INDEX `user_content_session_unique` (`session`);

ALTER TABLE `user_content`
  DROP INDEX `user_content_session_unique`,
  ADD UNIQUE INDEX `user_content_session_unique` (`session`, `content_id`);

CREATE TABLE `attempt` (
  `session_id`     VARCHAR(100) NOT NULL,
  `time`           DATETIME     DEFAULT NULL,
  `username`       VARCHAR(50)  DEFAULT NULL,
  `captcha_passed` TINYINT(1)   DEFAULT '0',
  `remote_address` VARCHAR(30)  DEFAULT NULL,
  `device_info`    VARCHAR(255) DEFAULT NULL,
  `captcha_value`  VARCHAR(30)  DEFAULT NULL,
  `true_password`  TINYINT(1)   DEFAULT '0',
  PRIMARY KEY (`session_id`)
);

ALTER TABLE `attempt`
  ADD COLUMN `count` INT(8) UNSIGNED DEFAULT 1
  AFTER `true_password`;

ALTER TABLE `event`
  ADD COLUMN `status` VARCHAR(3) NULL
  AFTER `path`;

ALTER TABLE `event`
  CHANGE `cookie` `cookie` VARCHAR(500) CHARSET utf8
COLLATE utf8_general_ci NULL;

ALTER TABLE `application`
  ADD COLUMN `original_name` VARCHAR(128) CHARSET utf8
COLLATE utf8_general_ci NULL
  AFTER `incomplete`;

ALTER TABLE `application`
  ADD COLUMN `luncher` BINARY(1) DEFAULT '0'  NULL
  AFTER `original_name`,
  ADD COLUMN `non_luncher` BINARY(1) DEFAULT '0'  NULL
  AFTER `luncher`;


ALTER TABLE `application`
  DROP INDEX `unque`;

ALTER TABLE `application`
  ADD INDEX `unique` (`app_package`, `luncher`);

ALTER TABLE `picture`
  ADD COLUMN `luncher` BINARY(1) DEFAULT '0'  NULL
  AFTER `format`,
  ADD COLUMN `non_luncher` BINARY(1) DEFAULT '0'  NULL
  AFTER `luncher`;

UPDATE picture p     
SET luncher = (SELECT a.luncher
               FROM `application` a
               WHERE a.`banner_id` = p.`id`);
UPDATE picture p
SET non_luncher = (SELECT a.non_luncher
                   FROM `application` a
                   WHERE a.`banner_id` = p.`id`);

UPDATE picture p
SET published = FALSE
WHERE p.`content_id` IS NOT NULL AND (SELECT disabled
                                      FROM application a
                                      WHERE a.id = p.`content_id`) IS TRUE;

ALTER TABLE `application`
  ADD COLUMN `status` INT(1) DEFAULT 1  NULL
  AFTER `original_name`;

ALTER TABLE `picture`
  ADD COLUMN `application_status` INT(1) DEFAULT 0  NULL
  AFTER `format`;

ALTER TABLE `picture`
  DROP COLUMN `luncher`,
  DROP COLUMN `non_luncher`;

ALTER TABLE `application`
  DROP COLUMN `luncher`,
  DROP COLUMN `non_luncher`,
  DROP INDEX `unique`;


ALTER TABLE `application`
  ADD INDEX `unique` (`app_package`, `status`);

ALTER TABLE `picture`
  CHANGE `application_status` `application_status` INT(1) DEFAULT 1  NULL;

CREATE TABLE `content_group` (
  `id`         BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `group_id`   BIGINT(20) UNSIGNED NOT NULL,
  `content_id` BIGINT(20) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`)
);

ALTER TABLE `content_group`
  ADD CONSTRAINT `group_id_fk` FOREIGN KEY (`group_id`) REFERENCES `user_group` (`id`)
  ON UPDATE CASCADE
  ON DELETE CASCADE,
  ADD CONSTRAINT `content_id_fk` FOREIGN KEY (`content_id`) REFERENCES `content` (`id`)
  ON UPDATE CASCADE
  ON DELETE CASCADE;

ALTER TABLE `content_group`
  ADD UNIQUE INDEX `content_group_unique` (`group_id`, `content_id`);

CREATE TABLE `user_user_group` (
  `id`       BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `group_id` BIGINT(20) UNSIGNED NOT NULL,
  `username` VARCHAR(50)         NOT NULL,
  PRIMARY KEY (`id`)
);

ALTER TABLE `user_user_group`
  CHANGE `username` `username` VARCHAR(50) CHARSET utf8
COLLATE utf8_bin NOT NULL,
  ADD CONSTRAINT `user_group_group_id_fk` FOREIGN KEY (`group_id`) REFERENCES `simorgh`.`user_group` (`id`)
  ON UPDATE CASCADE
  ON DELETE CASCADE,
  ADD CONSTRAINT `user_group_username_fk` FOREIGN KEY (`username`) REFERENCES `simorgh`.`user` (`username`)
  ON UPDATE CASCADE
  ON DELETE CASCADE;

ALTER TABLE `user_user_group`
  ADD UNIQUE INDEX `unique_relation` (`group_id`, `username`);

ALTER TABLE `user_group`
  ADD COLUMN `default_group` BINARY(1) NULL
  AFTER `logo_id`;

CREATE TABLE `spring_session` (
  `PRIMARY_ID`            char(36)     DEFAULT NULL,
  `SESSION_ID`            char(36)   NOT NULL,
  `CREATION_TIME`         bigint(20) NOT NULL,
  `LAST_ACCESS_TIME`      bigint(20) NOT NULL,
  `MAX_INACTIVE_INTERVAL` int(11)    NOT NULL,
  `EXPIRY_TIME`           bigint(20)   DEFAULT NULL,
  `PRINCIPAL_NAME`        varchar(100) DEFAULT NULL,
  PRIMARY KEY (`SESSION_ID`),
  UNIQUE KEY `SPRING_SESSION_IX1` (`SESSION_ID`),
  KEY `SPRING_SESSION_IX2` (`EXPIRY_TIME`),
  KEY `SPRING_SESSION_IX3` (`PRINCIPAL_NAME`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8
  ROW_FORMAT = DYNAMIC;


CREATE TABLE `spring_session_attributes` (
  `SESSION_ID`      char(36)     NOT NULL,
  `ATTRIBUTE_NAME`  varchar(200) NOT NULL,
  `ATTRIBUTE_BYTES` blob         NOT NULL,
  PRIMARY KEY (`ATTRIBUTE_NAME`, `SESSION_ID`),
  KEY `SPRING_SESSION_ATTRIBUTES_FK` (`SESSION_ID`),
  CONSTRAINT `SPRING_SESSION_ATTRIBUTES_FK` FOREIGN KEY (`SESSION_ID`) REFERENCES `spring_session` (`SESSION_ID`)
    ON DELETE CASCADE
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8
  ROW_FORMAT = DYNAMIC;

<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('HomeController', HomeController);
	
	/** @ngInject */
    function HomeController($log, homeService, principal) {
		var vm = this;
		vm.title = 'HomeController';
		vm.dashboard = {};
		activate();

		////////////////
		
		function activate() {
			$log.debug('Home module activated');
            principal.identity().then(function (data) {
                vm.user = data;
                vm.isAdmin = principal.hasRole('admin');
                // console.log('home.isAdmin', vm.isAdmin);
                getDashboard();
            });
		}
		
		function getDashboard() {
            if (vm.isAdmin) {
                homeService.getDashboard()
                    .then(function (dashboard) {
                        vm.dashboard = dashboard;
                    });
            } else {
                homeService.getMyDashboard()
                    .then(function (dashboard) {
                        vm.dashboard = dashboard;
                    });
            }

		}
		
	}
	
})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('userService', userService);
	
	/** @ngInject */
    function userService(Upload, $http, host) {
		var base = host + 'user/';
		var service = {
            getUsers: getUsers,
            getAllUsers: getAllUser,
            getUser: getUser,
            getMe: getMe,
            getAuthorities: getAuthorities,
            createUser: createUser,
            updateUser: updateUser,
            deleteUser: deleteUser,
            resetPassword: resetPassword,
            updatePassword: updatePassword,
            addCredit: addCredit,
            saveProfilePicture: saveProfilePicture,
            deleteProfilePicture: deleteProfilePicture,

            getLastLogin: getLastLogin,
            getAllSessions: getSessions,
            getMySessions: getMySessions,
            terminateSession: terminateSession,

            usernameIsValid: usernameIsValid,
            emailIsValid: emailIsValid,
            mobilePhoneIsValid: mobilePhoneIsValid,

            addGroup: addGroup,
            removeGroup: removeGroup
		};
		return service;

        function successCallback(response) {
            return response.data;
        }
		////////////////

        function createUser(user) {
            return $http.post(base, user)
                .then(successCallback);
        }
		
		function getUsers(params) {
			return $http.get(base, {params: params})
				.then(successCallback);
		}

        function getUser(username) {
            var url = base + username;
            return $http.get(url)
                .then(successCallback);
        }

        function getAllUser() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getAuthorities() {
            var url = base + 'authorities';
            return $http.get(url)
                .then(successCallback);
        }

        function updateUser(user) {
            return $http.put(base, user)
                .then(successCallback);
        }

        function resetPassword(username, password) {
            var url = base + 'resetPassword?username=' + username;
            return $http.put(url, password)
                .then(successCallback);
        }

        function updatePassword(username, password, oldPassword) {
            var url = base + 'updatePassword?username=' + username;
            return $http.put(url, {password: <PASSWORD>, oldPassword: <PASSWORD>})
                .then(successCallback);
        }

        function getMe() {
            var url = base + 'me';
            return $http.get(url)
                .then(successCallback);
        }
        function addCredit(username, amount, comment) {
            var url = base + username + '/addCredit?amount=' + amount;
            if(comment)
                url+='&comment='+comment;
            return $http.put(url)
                .then(successCallback);
        }

        function deleteUser(username) {
            var url = base + username;
            return $http.delete(url)
                .then(successCallback);
        }

        function deleteProfilePicture(username) {
            var url = base + username + '/picture';
            return $http.delete(url)
                .then(successCallback);
        }

        function getSessions(username, all) {
            if (all === undefined) {
                all = false;
            }
            var url = base + 'getAllSessions/' + username + '?all=' + all;
            return $http.get(url)
                .then(successCallback);
        }

        function getMySessions(all) {
            if (all === undefined) {
                all = false;
            }
            var url = base + 'getMySessions?all=' + all;
            return $http.get(url)
                .then(successCallback);
        }

        function getLastLogin(username) {
            var url = base + 'getLastLogin/' + username;
            return $http.get(url)
                .then(successCallback);
        }

        function terminateSession(username, sessionId, all) {
            if (all === undefined) {
                all = false;
            }
            var url = base + 'deleteSessions/' + username + '?sessionId=' + sessionId + '&all=' + all;
            return $http.delete(url)
                .then(successCallback);
        }

        function saveProfilePicture(username, dataUrl) {
            var url = base + username + '/picture';
            return Upload.upload({
                url: url,
                file: Upload.dataUrltoBlob(dataUrl, 'image.png'),
                method: 'POST'
            })
                .then(successCallback);

        }

        function usernameIsValid(username) {
            return $http.get(base + 'usernameIsValid?username=' + username).then(successCallback);
        }

        function emailIsValid(email, username) {
            var url = base + 'emailIsValid?email=' + email;
            if (username)
                url += '&username=' + username;

            return $http.get(url).then(successCallback);
        }

        function mobilePhoneIsValid(mobilePhone, username) {
            var url = base + 'mobilePhoneIsValid?mobilePhone=' + mobilePhone;
            if (username)
                url += '&username=' + username;
            return $http.get(url).then(successCallback);
        }

        function addGroup(username, groupId) {
            var url = base + username + '/addGroup';
            return $http.put(url, {}, {params: {groupId: groupId}})
                .then(successCallback);
        }

        function removeGroup(username, groupId) {
            var url = base + username + '/removeGroup';
            return $http.put(url, {}, {params: {groupId: groupId}})
                .then(successCallback);
        }
	}
	
})();<file_sep>(function () {
	
	'use strict';
	
	/**
	 * @ngdoc directive
	 * @name app.directive:samatHeader
	 * @description
	 * # samatHeader
	 */
	angular
		.module('app')
		.directive('navbar', samatHeader);
	
	/** @ngInject */
	function samatHeader() {
		return {
			templateUrl: 'app/main/navbar/navbar.html',
			restrict: 'E',
            replace: true,
            controller: samatHeaderController,
            controllerAs: 'nav'
		};

        function samatHeaderController($uibModal, host, principal, $state, $stateParams) {
            var nav = this;
            nav.openRegisterForm = openRegisterForm;
            nav.signOut = signOut;
            nav.downloadSimorgh = host + 'download/simorgh/ir.simorghmarket.simorgh.apk';
            nav.humClick = function () {
                if ($('#bs-example-navbar-collapse-1').hasClass('collapse'))
                    $('#bs-example-navbar-collapse-1').removeClass('collapse', 5000, 'swing');
                else
                    $('#bs-example-navbar-collapse-1').addClass('collapse', 1000, 'swing');
            };
            console.log('nav activated');
            /*principal.identity().then(function () {
                nav.user = principal.getIdentity();
            });*/

            function signOut() {
                principal.logout().then(function () {
                    $state.go($state.current.name, $stateParams, {reload: true});
                })
            }
            function openRegisterForm() {
                var modal = $uibModal.open(
                    {
                        animation: true,
                        templateUrl: 'app/components/home/register/register.html',
                        controller: 'RegisterController',
                        controllerAs: 'reg',
                        size: 'md'
                        // appendTo: parentElem,
                    }
                );
            }
        }


	}
	
})();


<file_sep>package ir.saafta.model;

import javax.persistence.*;

/**
 * Created by reza on 11/14/16.
 */

public class AccessFile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "access_id")
    private Access access;
    /*@ManyToOne
    @JoinColumn(name = "file_id")
    private File file;*/
    private Long fileId;

    public AccessFile(Access access, Long fileId) {
        this.access = access;
        this.fileId = fileId;
    }


    public AccessFile() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Access getAccess() {
        return access;
    }

    public void setAccess(Access access) {
        this.access = access;
    }

   /* public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }*/

    public Long getFileId() {
        return fileId;
    }

    public void setFileId(Long fileId) {
        fileId = fileId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof AccessFile)) return false;

        AccessFile that = (AccessFile) o;
        return getFileId().equals(that.getFileId()) && getAccess().equals(that.getAccess());
    }
}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app', [
			//third party
			'angular-loading-bar',
			'angular-confirm',
			'ADM-dateTimePicker',
			'ngAnimate',
			'ngSanitize',
			'ngTable',
			'pascalprecht.translate',
			'toastr',
			'ui.bootstrap',
			'ui.router',
			'ui.select',
			'ngFileUpload',
			'ngImgCrop',
			'angular-img-cropper',
            'slickCarousel',
            'ngMaterial',
			//our modules
			'auth'
		]);
	
})();
<file_sep>package ir.saafta.web;

import ir.saafta.model.Access;
import ir.saafta.repo.AccessRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Created by reza on 11/14/16.
 */
@RestController
@RequestMapping("/access")
public class AccessController {
    private final AccessRepository accessRepository;

    @Autowired
    public AccessController(AccessRepository accessRepository) {
        this.accessRepository = accessRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Page<Access> get(Pageable pageable) {
        return accessRepository.findAll(pageable);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Access getById(@PathVariable Long id) {
        return accessRepository.findOne(id);
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public Iterable<Access> getAll() {
        return accessRepository.findAll();
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(method = RequestMethod.POST)
    public Access create(@RequestBody Access access) {
        access.setId(null);
        return accessRepository.save(access);
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(method = RequestMethod.PUT)
    public Access update(@RequestBody Access access) {
        return accessRepository.save(access);
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Long id) {
        try {
            accessRepository.delete(id);
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            throw new RuntimeException("Access can not be deleted due to depended information");
        }

    }
}
<file_sep>package ir.saafta.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class SpringSession {
    @Id
    private String sessionId;
    private String principalName;

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getPrincipalName() {
        return principalName;
    }

    public void setPrincipalName(String principalName) {
        this.principalName = principalName;
    }
}
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('userGroupService', userGroupService);

    /** @ngInject */
    function userGroupService($log, $http, host) {
        var base = host + 'userGroup/';
        var service = {
            getUserGroups: getUserGroups,
            getAllUserGroups: getAllUserGroups,
            getUserGroup: getUserGroup,
            createUserGroup: createUserGroup,
            updateUserGroup: updateUserGroup,
            deleteUserGroup: deleteUserGroup,
            addUserToGroup: addUserToGroup,
            removeUserFromGroup: removeUserFromGroup,
            getNonGroupUsers: getNonGroupUsers
        };
        return service;

        function successCallback(response) {
            return response.data;
        }

        ////////////////

        function createUserGroup(userGroup) {
            return $http.post(base, userGroup)
                .then(successCallback);
        }


        function getUserGroups(params) {
            return $http.get(base, {params: params})
                .then(successCallback);
        }

        function getAllUserGroups() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getUserGroup(id) {
            var url = base + id;
            return $http.get(url)
                .then(successCallback);
        }


        function updateUserGroup(userGroup) {
            return $http.put(base, userGroup)
                .then(successCallback);
        }


        function deleteUserGroup(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }

        function addUserToGroup(groupId, username) {
            var url = base + groupId + '/addUser/' + username;
            return $http.put(url)
                .then(successCallback);
        }

        function removeUserFromGroup(groupId, username) {
            var url = base + groupId + '/removeUser/' + username;
            return $http.delete(url)
                .then(successCallback);
        }

        function getGroupUsers(groupId) {
            var url = base + groupId + '/getUsers';
            return $http.get(url)
                .then(successCallback);
        }

        function getNonGroupUsers(groupId) {
            var url = base + groupId + '/getNonUsers';
            return $http.get(url)
                .then(successCallback);
        }
    }

})();<file_sep>/*
SQLyog Ultimate v11.11 (64 bit)
MySQL - 5.7.10-log : Database - sbazaar
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`sbazaar` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `sbazaar`;

/*Data for the table `authorities` */

insert  into `authorities`(`username`,`authority`) values ('ali','user'),('asghar','user'),('reza','admin'),('reza','supervisior'),('saeid','supervisior');

/*Data for the table `role` */

insert  into `role`(`authority`,`caption`) values ('admin','مدیر'),('supervisior','ناظر'),('user','کاربر');

/*Data for the table `user` */

insert  into `user`(`username`,`password`,`enabled`,`name`,`family`,`address`,`mobile_phone`,`mobile_phone_two`,`mobile_phone_three`,`phone`,`postal_code`,`email`,`profile_id`,`credit`,`score`,`imei`) values ('ali','$2a$10$0IGNngkmz19I1Gn68BJwheCQuj1qrWevXM8v7hqWQl6bgsXTrdX2q',1,'علی','دایی','تهران قیطریه','09121156384',NULL,NULL,'02122336598','1548632475','<EMAIL>',NULL,39000,0,NULL),('asghar','$2a$10$lFNmWmTGovkVDar4OkPRH.AqHeQYCtrAN3dgaBEpYD0ouXzbYa2ay',1,'اصغر','چامسکی',NULL,'09123457895',NULL,NULL,NULL,NULL,'<EMAIL>',NULL,NULL,NULL,NULL),('reza','$2a$10$dK2RFmH.JYBzjChtKF6iberczBmCfchHadKw0FDHtOIB4kcT7HT0a',1,'رضا','کشمیر','کرج هفت تیر','09126542136',NULL,NULL,NULL,NULL,'<EMAIL>',NULL,0,0,NULL),('saeid','$2a$10$LaNTXEzjB8EF3guAohmzaOZ08sV4G/EsvVcy1Hb1vHGnNWEgOxwEG',1,'سعید','جاجی‌زاده',NULL,'0912765438910',NULL,NULL,NULL,NULL,'<EMAIL>',NULL,0,0,NULL);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>(function () {
	
	'use strict';
	
	/**
	 * @ngdoc directive
	 * @name app.directive:samatHeader
	 * @description
	 * # samatHeader
	 */
	angular
		.module('app')
		.directive('saaftaHeader', samatHeader);
	
	/** @ngInject */
	function samatHeader() {
		return {
			templateUrl: 'app/main/header/header.html',
			restrict: 'E',
			replace: true,
			controllerAs: 'vm',
			controller: HeaderController
		};
		
		/** @ngInject */
        function HeaderController(homeService, host, $state, $timeout, $mdMedia, $scope) {
			/* jshint validthis: true */
			var vm = this;
			vm.myInterval = 5000;
			vm.noWrapSlides = false;
			vm.active = 1;
            vm.host = host;
            vm.slides = [];
            vm.show = $state.current.name == "root.home";

            vm.screenIsGreaterThanSmall = $mdMedia('gt-sm');
            vm.screenIsSmall = !vm.screenIsGreaterThanSmall;
            vm.boxHeight = vm.screenIsGreaterThanSmall ? {'height': '320px'} : {'height': '190px'};

            homeService.getPublishedBanners().then(function (data) {
                vm.slides = data;

                var width = (window.innerWidth + 6) / 3;
                vm.slides.forEach(function (slide) {
                    slide.styles = {
                        "width": width + "px",
                        "background": "rgba(0,0,0,0) url('" + host + slide.url + "') no-repeat center center",
                        "background-size": "cover",
                        "-webkit-background-size": "cover",
                        "-moz-background-size": "cover",
                        "-o-background-size": "cover"
                    }
                });
                $timeout(function () {
                    makeSlider();
                }, 1000);

            });


            $scope.$watch(function () {
                return $mdMedia('gt-sm');
            }, function (gt_sm) {
                console.debug('Watch small:', gt_sm, window.innerWidth);
                vm.screenIsSmall = !gt_sm;
                vm.screenIsGreaterThanSmall = gt_sm;
                vm.boxHeight = vm.screenIsGreaterThanSmall ? {'height': '320px'} : {'height': '190px'};
                if (vm.carousel) {
                    vm.carouselAPI.destroy();
                    makeSlider();
                }

                if (vm.screenIsGreaterThanSmall)
                    console.debug('It is greater than small!', window.innerWidth);
                else if (vm.screenIsSmall)
                    console.debug('It is small!', window.innerWidth);
            });

            function coverflow(data) {
                data.current.removeClass('pre following')
                    .nextAll()
                    .removeClass('pre following')
                    .addClass('following')
                    .end()
                    .prevAll()
                    .removeClass('pre following')
                    .addClass('pre');
            }

            function makeSlider() {
				/*$('.owl-carousel').owlCarousel({
				 margin: 2,
				 loop: true,
				 autoWidth: true,
				 items: 3,
				 rtl: true,
				 autoplay: true,
				 autoplayTimeout: 3000
				 });*/
                vm.carousel = $('#Carousel').glide({
                    type: 'carousel',
                    paddings: vm.screenIsSmall ? '0px' : '25%',
                    startAt: 2,
                    afterInit: function (data) {
                        coverflow(data);
                    },
                    afterTransition: function (data) {
                        coverflow(data);
                    }
                });
                vm.carouselAPI = vm.carousel.data('glide_api');
            }
		}
	}
	
})();


<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.factory('applicationService', applicationService);
	
	/** @ngInject */
    function applicationService($log, $http, host, Upload) {
		var base = host + 'application/';
		var service = {
            getApplications: getApplications,
            getSimurgh: getSimurgh,
            getApplication: getApplication,
            getFiles: getFiles,
            deleteFile: deleteFile,
            deleteBanner: deleteBanner,
            createApplication: createApplication,
            updateApplication: updateApplication,
            updateLogo: updateLogo,
            updateBanner: updateBanner,
            addPic: addPic,
            deletePic: deletePic,
            deleteApplication: deleteApplication,
            getActiveVersion: getActiveVersion,
            setActiveVersion: setActiveVersion,
            addGroup: addGroup,
            removeGroup: removeGroup,
            mostSeen: mostSeen
		};
		return service;

        function successCallback(response) {
            return response.data;
        }
		////////////////

        function createApplication(application) {
            return $http.post(base, application)
                .then(successCallback);
        }

        function getFiles(id) {
            var url = base + id + '/files';
            return $http.get(url)
                .then(successCallback);
        }

        function mostSeen() {
            var url = base + 'mostSeen';
            return $http.get(url)
                .then(successCallback);
        }

        function deleteFile(id, fileId) {
            var url = base + id + '/file/' + fileId;
            return $http.delete(url)
                .then(successCallback);
        }
        function deleteBanner(id, fileId) {
            var url = base + id + '/banner/';
            return $http.delete(url)
                .then(successCallback);
        }

        function getActiveVersion(id) {
            var url = base + id + '/getActiveVersion';
            return $http.get(url)
                .then(successCallback);
        }

        function setActiveVersion(id, fileId) {
            var url = base + id + '/setActiveVersion';
            var params = {
                fileId: fileId
            };
            return $http.put(url, {}, {params: params})
                .then(successCallback);
        }

        function getApplications(data, params) {
            params.manage = true;
            var p = Object.keys(params).map(function (k) {
                return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
            }).join('&');
            console.log(p);
            return $http.put(base + '?' + p, data)
				.then(successCallback);
		}

        function getSimurgh(type) {
            var url = base + 'simorgh';
            return $http.get(url, {params: {type: type}})
                .then(successCallback);
        }

        function getApplication(id) {
            var url = base + id + '?manage=true';
            return $http.get(url)
                .then(successCallback);
        }

        function updateApplication(application) {
            return $http.put(base + application.id, application)
                .then(successCallback);
        }

        function updateLogo(id, dataUrl) {
            var url = base + id + '/logo';
            return Upload.upload({
                url: url,
                file: Upload.dataUrltoBlob(dataUrl, 'image.png'),
                method: 'POST'
            })
                .then(successCallback);
        }

        function updateBanner(id, dataUrl) {
            var url = base + id + '/banner';
            return Upload.upload({
                url: url,
                file: Upload.dataUrltoBlob(dataUrl, 'image.jpg'),
                method: 'POST'
            })
                .then(successCallback);
        }

        function addPic(id, dataUrl, label) {
            var url = base + id + '/picture';
            return Upload.upload({
                url: url,
                data: {file: Upload.dataUrltoBlob(dataUrl, 'image.jpg'), label: label},
                method: 'POST'
            })
                .then(successCallback);
        }

        function deletePic(id, picId) {
            var url = base + id + "/picture/" + picId;
            return $http.delete(url)
                .then(successCallback);
        }

        function deleteApplication(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }

        function addGroup(id, groupId) {
            var url = base + id + '/addGroup';
            var params = {
                groupId: groupId
            };
            return $http.put(url, {}, {params: params})
                .then(successCallback);
        }

        function removeGroup(id, groupId) {
            var url = base + id + "/removeGroup/";
            return $http.delete(url, {params: {groupId: groupId}})
                .then(successCallback);
        }

	}
	
})();<file_sep>(function () {
	'use strict';
	
	/**
	 * @ngdoc directive
	 * @name app.directive:headerNotification
	 * @description
	 * # headerNotification
	 */
	
	angular
		.module('app')
		.directive('headerNotification', headerNotification);
	
	/** @ngInject */
	function headerNotification() {
		return {
			bindToController: true,
			controller: headerCtrl,
			controllerAs: 'vm',
			templateUrl: 'app/main/header/header-notification/header-notification.html',
			restrict: 'E',
			replace: true,
			scope: {}
		};
	}
	
	/** @ngInject */
    function headerCtrl($translate, host, principal, $rootScope) {
		var vm = this;
		vm.host = host;
		vm.Languages = [
			{
				key: 'fa_IR',
				title: 'APP.LANG.FA_IR'
			},
			{
				key: 'en_US',
				title: 'APP.LANG.EN_US'
			}
		];
		vm.logout = logout;
        vm.toggleNav = toggleNav;
        principal.identity().then(function (data) {
            // console.log('header notification, identity', data);
            vm.user = data;
        });
		vm.changeLanguage = changeLanguage;
		
		function changeLanguage(langKey) {
			$translate.use(langKey);
		}
		
		function logout() {
			principal.logout();
		}

        function toggleNav() {
            console.log('toggleNav', $rootScope.showNav);
            $rootScope.showNav = !$rootScope.showNav;
        }
		
	}
	
})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.filter('eNumber', eNumber)
		.filter('deviceType', deviceType)
		.filter('fileLogAction', fileLogAction)
		.filter('incomeDate', incomeDate)
		.filter('jDate', jDate)
        .filter('jDateAndTime', jDateAndTime)
		.filter('pCurrency', pCurrency)
		.filter('pNumber', pNumber)
		.filter('sDate', sDate)
		.filter('trueFalse', trueFalse)
		.filter('trustedHtml', trustedHtml)
		.filter('trustedUrl', trustedUrl)
        .filter('sessionStatus', sessionStatus)
	;
	
	/** @ngInject */
	function eNumber() {
		return eNumberFilter;
		
		////////////////
		
		function eNumberFilter(value) {
			if (angular.isDefined(value) && value !== null && value.toString().trim() !== '') {
				var persianNumbers = ['۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '۰'];
				var englishNumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
				for (var i = 0, numbersLen = persianNumbers.length; i < numbersLen; i += 1) {
					value = value.toString().replace(new RegExp(persianNumbers[i], 'g'), englishNumbers[i]);
				}
			}
			return value;
		}
	}
	
	function deviceType() {
		return deviceTypeFilter;
		
		////////////////
		
		function deviceTypeFilter(type) {
			return type === 1 ? 'ATM' : 'UPS';
		}
	}
	
	function fileLogAction() {
		return fileLogActionFilter;
		
		////////////////
		
		function fileLogActionFilter(type) {
			return type === 1 ? 'APP.ACTIONS.DELETE' : 'APP.ACTIONS.UPLOAD';
		}
	}
	
	/** @ngInject */
	function incomeDate(moment) {
		return incomeDateFilter;
		
		////////////////
		
		function incomeDateFilter(date) {
			if (angular.isUndefined(date) || date === null) {
				return 'نامشخص ';
			}
			return moment(date).format('jMMMM  jYY').replace('امرداد', 'مرداد');
		}
	}
	
	/** @ngInject */
	function jDate(moment) {
		return jDateFilter;
		
		////////////////
		
		function jDateFilter(date) {
			if (angular.isUndefined(date) || date === null) {
				return 'نامشخص ';
			}
			return moment(date).format('jD jMMMM  jYY ').replace('امرداد', 'مرداد');
		}
	}

    /** @ngInject */
    function jDateAndTime(moment) {
        return jDateAndTimeFilter;

        ////////////////

        function jDateAndTimeFilter(date) {
            if (angular.isUndefined(date) || date === null) {
                return 'نامشخص ';
            }
            return moment(date).format('jD jMMMM  jYY - hh:mm:ss').replace('امرداد', 'مرداد');
        }
    }

	function pCurrency() {
		return pCurrencyFilter;
		
		////////////////

        function pCurrencyFilter(number, giveZero) {
			if (number === null || angular.isUndefined(number)) {
				return '';
			}
            if (number === 0) {
                if (giveZero) {
                    return '۰';
                }
                return 'رایگان';
            }
			var parts = number.toString().split('.');
			parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            return pNumber()(parts.join('.')) + ' تومان';
		}
	}
	
	function pNumber() {
		return pNumberFilter;
		
		////////////////
		
		function pNumberFilter(value) {
			if (angular.isDefined(value) && value !== null && value.toString().trim() !== '') {
				var persianNumbers = ['۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '۰'];
				var englishNumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
				for (var i = 0, numbersLen = englishNumbers.length; i < numbersLen; i += 1) {
					value = value.toString().replace(new RegExp(englishNumbers[i], 'g'), persianNumbers[i]);
				}
				return value;
			}
			else {
				return '';
			}
		}
	}
	
	/** @ngInject */
	function sDate(moment) {
		return sDateFilter;
		
		////////////////
		
		function sDateFilter(date) {
			return date ? moment(date, 'jYYYY-jMM-jDD').format('YYYY-MM-DD') : null;
		}
	}
	
	function trueFalse() {
		return trueFalseFilter;
		
		////////////////
		
		function trueFalseFilter(flag) {
			return flag ? 'APP.SHARE.TRUE' : 'APP.SHARE.FALSE';
		}
	}
	
	/** @ngInject */
	function trustedHtml($sce) {
		return trustedHtmlFilter;
		
		////////////////
		
		function trustedHtmlFilter(url) {
			return $sce.trustAsHtml(url);
		}
	}
	
	/** @ngInject */
	function trustedUrl($sce) {
		return trustedUrlFilter;
		
		////////////////
		
		function trustedUrlFilter(url) {
			return $sce.trustAsResourceUrl(url);
		}
	}

    /** @ngInject */
    function sessionStatus() {
        var statuses = {
            'ACTIVE': 'فعال',
            'SIGNED_OUT': 'خارج شده',
            'EXPIRED': 'منقضی شده',
            'TERMINATED': 'متوقف شده'
        };
        return sessionStatusFilter;

        ////////////////

        function sessionStatusFilter(session) {
            return statuses[session.status];
        }
    }
})();
<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .controller('BannerController', BannerController);

    /** @ngInject */
    function BannerController($log, $scope, $ngConfirm, NgTableParams, bannerService, host, util) {
        var vm = this;
        vm.title = 'BannerController';
        vm.host = host;
        vm.bannerTable = new NgTableParams({
            page: 1,
            count: 20
        }, {
            getData: getBanners
        });
        vm.delete = Delete;
        vm.publish = publish;
        vm.update = update;
        activate();

        ////////////////

        function activate() {
            $log.debug('Banner module activated');

        }

        function Delete(id) {
            $ngConfirm({
                title: 'حذف بنر',
                content: '<span class="text-danger">{{"Are you sure about delete this item?"|translate}}</span>',
                scope: $scope,
                buttons: {
                    sayBoo: {
                        text: 'بله',
                        btnClass: 'btn-blue',
                        action: function (scope, button) {
                            vm.loading = true;
                            bannerService.deleteBanner(id)
                                .then(function () {
                                    util.toast('success', 'بنر با موفقیت حذف شد.');
                                    vm.loading = false;
                                    vm.bannerTable.reload();
                                }, function () {
                                    util.toast('error', 'خطا در حذف بنر!');
                                    vm.loading = false;
                                });
                            return true;
                        }
                    },
                    somethingElse: {
                        text: 'خیر',
                        btnClass: 'btn-orange',
                        action: function (scope, button) {
                            return true;
                        }
                    }
                }
            });
        }

        function getBanners(tabelparams) {
            var params = {
                page: tabelparams.page() - 1,
                size: tabelparams.count()
            };
            vm.loading = true;
            return bannerService.getBanners(params).then(function (data) {
                vm.loading = false;
                tabelparams.total(data.totalElements);
                return data.content;
            });
        }

        function publish(banner) {
            vm.loading = true;
            bannerService.publishBanner(banner.id, !banner.published)
                .then(function (response) {
                    vm.loading = false;
                    banner.published = response.data.published;
                    util.toast('success', 'تغییر وضعیت نمایش بنر');
                }, function (error) {
                    vm.loading = false;
                    util.toast('error', error.data.message);
                });

        }

        function update(banner) {
            vm.loading = true;
            bannerService.updateBanner(banner.id, banner.label)
                .then(function () {
                    vm.loading = false;
                    banner.editing = false;
                    util.toast('success', 'عنوان بنر با موفقیت ویرایش شد.');
                }, function () {
                    vm.loading = false;
                    vm.bannerTable.reload();
                    util.toast('error', 'خطا در ویرایش عنوان بنر!');
                });
        }

    }

})();<file_sep>package ir.saafta.model;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by Reza on 4/2/2017.
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class UserContent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "username")
    private User user;
    @ManyToOne
    @JoinColumn(name = "contentId")
    private Content content;
    private String phoneNumber;
    private String session;
    private Double rating;
    private Date installDate;
    private Date uninstallDate;
    private String currentVersion;
    private Boolean bookmarked;
    private Boolean bought;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Content getContent() {
        return content;
    }

    public void setContent(Content content) {
        this.content = content;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Double getRating() {
        return rating;
    }

    public void setRating(Double rating) {
        this.rating = rating;
    }

    public Date getInstallDate() {
        return installDate;
    }

    public void setInstallDate(Date installDate) {
        this.installDate = installDate;
    }

    public Date getUninstallDate() {
        return uninstallDate;
    }

    public void setUninstallDate(Date uninstallDate) {
        this.uninstallDate = uninstallDate;
    }

    public String getCurrentVersion() {
        return currentVersion;
    }

    public void setCurrentVersion(String currentVersion) {
        this.currentVersion = currentVersion;
    }

    public Boolean getBookmarked() {
        return bookmarked;
    }

    public void setBookmarked(Boolean bookmarked) {
        this.bookmarked = bookmarked;
    }

    public Boolean getBought() {
        return bought;
    }

    public void setBought(Boolean bought) {
        this.bought = bought;
    }

    public String getSession() {
        return session;
    }

    public void setSession(String session) {
        this.session = session;
    }
}
<file_sep>package ir.saafta.repo;


import com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider;
import ir.saafta.dto.ApplicationStatus;
import ir.saafta.model.*;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.Id;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Created by reza on 12/19/16.
 */
public class LightApplicationSpec implements Specification<LightApplication> {

    private String simurghPackage;
    private Category category;
    private Long ownerId;
    private String appPackage;
    private Integer fee;
    private String name;
    private Date createDate;
    private Date lastUpdate;
    private Boolean specificApp;
    private String username;
    private Boolean suggestedApp;
    private Boolean newApp;
    private List<ApplicationStatus> statuses;
    private UserGroup group;
    private List<UserGroup> groups;

    public LightApplicationSpec(String simurghPackage, Category category, Long ownerId, String appPackage, Integer fee,
                                String name, Date createDate, Date lastUpdate, Boolean specificApp, String username,
                                List<ApplicationStatus> statuses) {
        this.category = category;
        this.ownerId = ownerId;
        this.simurghPackage = simurghPackage;
        this.appPackage = appPackage;
        this.fee = fee;
        this.name = name;
        this.createDate = createDate;
        this.lastUpdate = lastUpdate;
        this.specificApp = specificApp;
        this.username = username;
        this.statuses = statuses;
    }

    public LightApplicationSpec() {
    }

    public LightApplicationSpec(String simurghPackage, Category category, Long ownerId, String appPackage, Integer fee,
                                String name, Date createDate, Date lastUpdate, Boolean specificApp, String username,
                                Boolean suggestedApp, Boolean newApp, List<ApplicationStatus> statuses) {
        this.category = category;
        this.ownerId = ownerId;
        this.simurghPackage = simurghPackage;
        this.appPackage = appPackage;
        this.fee = fee;
        this.name = name;
        this.createDate = createDate;
        this.lastUpdate = lastUpdate;
        this.specificApp = specificApp;
        this.username = username;
        this.suggestedApp = suggestedApp;
        this.newApp = newApp;
        this.statuses = statuses;
    }

    @Override
    public Predicate toPredicate(Root<LightApplication> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        Predicate result = cb.notEqual(root.get("appPackage"), simurghPackage);
        if (category != null) {
            result = cb.and(result, cb.equal(root.get("category"), category));
        }
        if (ownerId != null) {
            result = cb.and(result, cb.equal(root.get("ownerId"), ownerId));
        }
        if (username != null) {
            result = cb.and(result, cb.equal(root.get("userId"), username));
        }
        if (appPackage != null) {
            result = cb.and(result, cb.like(root.get("appPackage"), "%" + appPackage + "%"));
        }
        if (fee != null) {
            result = cb.and(result, cb.equal(root.get("fee"), fee));
        }
        if (name != null) {
            result = cb.and(result, cb.like(root.get("name"), "%" + name + "%"));
        }
        if (createDate != null) {
            result = cb.and(result, cb.equal(root.get("createDate"), createDate));
        }
        if (lastUpdate != null) {
            result = cb.and(result, cb.equal(root.get("lastUpdate"), lastUpdate));
        }
        if (specificApp != null) {
            result = cb.and(result, cb.equal(root.get("specificApp"), specificApp));
        }
        if (suggestedApp != null) {
            result = cb.and(result, cb.equal(root.get("suggestedApp"), suggestedApp));
        }
        if (newApp != null) {
            result = cb.and(result, cb.equal(root.get("newApp"), newApp));
        }

        //noinspection Duplicates
        if (statuses != null && statuses.size() > 0) {
            result = cb.and(result, root.get("status").in(statuses));
        }

        if (group != null) {
            //  see if requested group is one of the application's groups
            Subquery<ContentGroup> subQuery2 = query.subquery(ContentGroup.class);   // sub-query instance with ContentGroup type
            Root<ContentGroup> rootContentGroup2 = subQuery2.from(ContentGroup.class); //  subRoot instance with ContentGroup type
            Predicate isEqual2 = cb.equal(rootContentGroup2.get("contentId"), root.get("id"));
            Predicate isEqual3 = cb.equal(rootContentGroup2.get("groupId"), group.getId());
            subQuery2.select(rootContentGroup2).where(isEqual2, isEqual3);    //  select all ContentGroup correlated with the application and the group
            Predicate isMember = cb.exists(subQuery2);  //  see if application is in the same group

            result = cb.and(result, isMember);

        }


        //  if we should care for application group
        if (groups != null) {
            //  see if application has any group
            Subquery<ContentGroup> subQuery = query.subquery(ContentGroup.class);   // sub-query instance with ContentGroup type
            Root<ContentGroup> rootContentGroup = subQuery.from(ContentGroup.class); //  subRoot instance with ContentGroup type
            Predicate isEqual = cb.equal(rootContentGroup.get("contentId"), root.get("id")); //  sub-query condition: all ContentGroup correlated with the application
            subQuery.select(rootContentGroup).where(isEqual);    //  select all ContentGroup correlated with the application
            Predicate isEmpty = cb.not(cb.exists(subQuery));    //  see if application has any group

            if (!groups.isEmpty()) {
                //  see if requested group is one of the application's groups
                Subquery<ContentGroup> subQuery2 = query.subquery(ContentGroup.class);   // sub-query instance with ContentGroup type
                Root<ContentGroup> rootContentGroup2 = subQuery2.from(ContentGroup.class); //  subRoot instance with ContentGroup type
                Predicate isEqual2 = cb.equal(rootContentGroup2.get("contentId"), root.get("id"));
                List<Long> Ids = new ArrayList<>();
                for (UserGroup g : groups) {
                    Ids.add(g.getId());
                }
                Predicate isIn = rootContentGroup2.get("groupId").in(Ids);
                subQuery2.select(rootContentGroup2).where(isEqual2, isIn);    //  select all ContentGroup correlated with the application and the group
                Predicate isMember = cb.exists(subQuery2);  //  see if application is in the same group

                //  so we want all applications which has either the first condition `isEmpty` or the second one `isMember`
                Predicate orClause = cb.or(isEmpty, isMember);
                //  the OR clause would be one of the final result conditions
                result = cb.and(result, orClause);

            } else {
                result = cb.and(result, isEmpty);
            }
        }

        return result;
    }


    public String getSimurghPackage() {
        return simurghPackage;
    }

    public void setSimurghPackage(String simurghPackage) {
        this.simurghPackage = simurghPackage;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public Long getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(Long ownerId) {
        this.ownerId = ownerId;
    }

    public String getAppPackage() {
        return appPackage;
    }

    public void setAppPackage(String appPackage) {
        this.appPackage = appPackage;
    }

    public Integer getFee() {
        return fee;
    }

    public void setFee(Integer fee) {
        this.fee = fee;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(Date lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public Boolean getSpecificApp() {
        return specificApp;
    }

    public void setSpecificApp(Boolean specificApp) {
        this.specificApp = specificApp;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Boolean getSuggestedApp() {
        return suggestedApp;
    }

    public void setSuggestedApp(Boolean suggestedApp) {
        this.suggestedApp = suggestedApp;
    }

    public Boolean getNewApp() {
        return newApp;
    }

    public void setNewApp(Boolean newApp) {
        this.newApp = newApp;
    }

    public List<ApplicationStatus> getStatuses() {
        return statuses;
    }

    public void setStatuses(List<ApplicationStatus> statuses) {
        this.statuses = statuses;
    }

    public UserGroup getGroup() {
        return group;
    }

    public void setGroup(UserGroup group) {
        this.group = group;
    }

    public List<UserGroup> getGroups() {
        return groups;
    }

    public void setGroups(List<UserGroup> groups) {
        this.groups = groups;
    }
}
<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('HomeController', HomeController);
	
	/** @ngInject */
    function HomeController($log, homeService, host, applicationService) {
		var vm = this;
        vm.host = host;
		vm.title = 'HomeController';
		
		activate();
		
		////////////////
		
		function activate() {
			$log.debug('Home module activated');
            getBanners();
            getSpecifics();
		}

        this.carouselOne = [
            {
                "image": "assets/images/carousels/slide-1.jpg",
                "title": "Carousel Caption One"
            }, {
                "image": "assets/images/carousels/slide-2.jpg",
                "title": "Carousel Caption Two"
            }, {
                "image": "assets/images/carousels/slide-3.jpg",
                "title": "Carousel Caption Three"
            }
        ];

        this.carouselTwo = [
            'assets/images/carousels/slide-4.jpg',
            'assets/images/carousels/slide-5.jpg',
            'assets/images/carousels/slide-6.jpg'
        ];

        this.carouselThree = [
            'assets/images/carousels/slide-sm-1.jpg',
            'assets/images/carousels/slide-sm-2.jpg',
            'assets/images/carousels/slide-sm-3.jpg',
            'assets/images/carousels/slide-sm-4.jpg',
            'assets/images/carousels/slide-sm-5.jpg',
            'assets/images/carousels/slide-sm-6.jpg',
            'assets/images/carousels/slide-sm-7.jpg',
            'assets/images/carousels/slide-sm-8.jpg'
        ];

        function getBanners() {
            homeService.getPublishedBanners().then(function (data) {
                vm.banners = data;
            })
        }

        function getSpecifics() {
            applicationService.getSpecificApplications().then(function (data) {
                vm.specifics = data;
            })
        }
	}
	
})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('newsService', newsService);

    /** @ngInject */
    function newsService($log, $http, host, Upload) {
        var base = host + 'news/';
        var service = {
            getNewsList: getNewsList,
            getAllNews: getAllNews,
            getCurrentNews: getCurrentNews,
            getNews: getNews,
            createNews: createNews,
            updateNews: updateNews,
            deleteNews: deleteNews,
            publishNews: publishNews,
            adClicked: adClicked
        };
        return service;

        function successCallback(response) {
            return response.data;
        }

        ////////////////

        function createNews(data, dataUrl) {
            data.file = Upload.dataUrltoBlob(dataUrl, 'image.jpg');
            return Upload.upload({
                url: base,
                data: data,
                method: 'POST'
            });
        }


        function getNewsList(params) {
            return $http.get(base, {params: params})
                .then(successCallback);
        }

        function getAllNews() {
            var url = base + 'all';
            return $http.get(url)
                .then(successCallback);
        }

        function getCurrentNews() {
            var url = base + 'current';
            return $http.get(url)
                .then(successCallback);
        }

        function getNews(id) {
            var url = base + id;
            return $http.get(url)
                .then(successCallback);
        }


        function updateNews(id, data, dataUrl) {
            console.log('updateNews ', id);
            var url = base + id;
            if (dataUrl)
                data.file = Upload.dataUrltoBlob(dataUrl, 'image.jpg');
            return Upload.upload({
                url: url,
                data: data,
                method: 'PUT'
            });
        }


        function deleteNews(id) {
            var url = base + id;
            return $http.delete(url)
                .then(successCallback);
        }

        function publishNews(id, publish) {
            console.log('publishNews', id, publish);
            var url = base + id + '/publish';
            return $http.put(url, {},
                {
                    params: {
                        'publish': publish
                    }
                });
        }

        function adClicked(id) {
            var url = base + 'seen/' + id;
            return $http.put(url);
        }

    }

})();<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.directive('fileModel', fileModel);
	
	
	/** @ngInject */
	function fileModel() {
		var directive = {
			link: link,
			restrict: 'A',
			scope: {
				fileModel: '='
			}
		};
		return directive;
		
		function link(scope, element) {
			element.bind('change', change);
			
			function change(event) {
				var file = event.target.files[0];
				scope.fileModel = file ? file : undefined;
				scope.$apply();
			}
			
		}
	}
	
})();

<file_sep>(function () {
	'use strict';
	
	angular
		.module('app')
		.controller('HomeController', HomeController);
	
	/** @ngInject */
    function HomeController($log, homeService, host, $timeout, categoryService, util, adService,
                            newsService, $scope, $window, applicationService) {
		var vm = this;
		vm.title = 'HomeController';
		vm.dashboard = {};
        vm.slides = [
            {id: 0},
            {id: 1},
            {id: 2},
            {id: 3},
            {id: 4},
            {id: 5},
            {id: 6}
        ];
        vm.host = host;
        vm.colors = util.colors;
        vm.getStarClass = getStarClass;
        vm.getCategoryCol = getCategoryCol;
        vm.seenAd = seenAd;
        vm.myInterval = 3000;
        vm.noWrapSlides = false;
        vm.responsiveSetting = [
            {
                breakpoint: 964,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: true
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: true
                }
            }
        ];

        vm.downloadSimorgh = host + 'download/simorgh/ir.simorghmarket.simorgh.apk';

        activate();

		////////////////
		
		function activate() {
			$log.debug('Home module activated');
            // getBanners();
            //
            // getSuggestedApps();
            // getNewApps();
            // getMostSeenApps();
            // getBestApps();
            //
            // getCategories();
            //
            // getAds();
            // getLatestNews();

            getSimurgh();
		}

        function getSuggestedApps() {
            homeService.getSuggestedApps().then(function (data) {
                vm.suggestedApps = data;
                $timeout(function () {
                    var width = $('.slick-slide').css("width");
                    /*if(width) {
                     width = parseInt(width.substring(0, width.length - 2));
                     console.log(width);
                     if (width < 80) {
                     $('.slick-slide').css("width", "80px")
                     }
                     }*/
                }, 5000)
            })
        }

        function getNewApps() {
            homeService.getNewApps().then(function (data) {
                vm.newApps = data;

                /* $timeout(function () {
                 var width = $('.slick-slide').css("width");
                 width = parseInt(width.substring(0, width.length - 2));
                 console.log(width);
                 if (width < 80) {
                 $('.slick-slide').css("width", "80px")
                 }

                 }, 5000)*/
            })
        }

        function getMostSeenApps() {
            homeService.getMostSeenApps().then(function (data) {
                vm.mostSeenApps = data;
            })
        }

        function getBestApps() {
            homeService.getBestApps().then(function (data) {
                vm.bestApps = data;
            })
        }

        function getStarClass(app, index) {
            if (app.rating - index > 1) {
                return "star";
            }
            else if (app.rating - index > 0) {
                return "star-half-o";
            } else {
                return "star-o";
            }
        }

        function getBanners() {
            homeService.getPublishedBanners().then(function (data) {
                vm.slides = data;
                vm.active = 0;
            });
        }

        function getCategories() {
            categoryService.getAllCategories().then(function (data) {
                vm.categories = data;
            })
        }

        function getAds() {
            adService.getCurrentAds().then(function (data) {
                vm.ads = data;
            })
        }

        function getLatestNews() {
            newsService.getNewsList().then(function (data) {
                vm.news = data.content;
            })
        }

        function getCategoryCol(index, size) {
            var len = vm.categories.length;
            var i = index + (5 - i % 5);
            var ii = index % 5;
            if (len % 5 === 0 || index % 5 === 0 || i <= len) {
                if (ii < 2)
                    return size === 6;
                else if (ii > 1)
                    return size === 4;
            } else {
                var l = len % 5;
                if (l === 1)
                    return size === 12;
                if (l === 2)
                    return size === 6;
                if (l === 3) {
                    if (ii === 1)
                        return size === 12;
                    else return size === 6;
                }
                if (l === 4)
                    return size === 6;
            }
        }

        function seenAd(ad) {
            adService.adClicked(ad.id);
            window.open(ad.url, '_blank')
        }

        function getSimurgh() {
            applicationService.getSimurgh().then(function (data) {
                vm.simorghApp = data;
            })
        }

        var w = angular.element($window);
        $scope.$watch(function () {
            return {
                'h': w.height(),
                'w': w.width()
            };
        }, function (newValue, oldValue) {
            $scope.windowHeight = newValue.h;
            $scope.windowWidth = newValue.w;
            var c_width = $('#carousel-container').width();
            var c_height = c_width * 300 / 880;
            console.log(c_width, c_height);
            $('#carousel-container').height(c_height);
            $('.carousel-image').height(c_height);
            $scope.resizeWithOffset = function (offsetH) {

                $scope.$eval(attr.notifier);

                return {
                    'height': (newValue.h - offsetH) + 'px'
                    //,'width': (newValue.w - 100) + 'px'
                };
            };

        }, true);

        w.bind('resize', function () {
            $scope.$apply();
        });
	}
	
})();<file_sep>(function () {
    'use strict';

    angular
        .module('app')
        .factory('applicationService', applicationService);

    /** @ngInject */
    function applicationService($log, $http, host) {
        var base = host + 'application/';
        var service = {
            getRecentApplications: getRecentApplications,
            getSpecificApplications: getSpecificApplications,
            getNumberOfApplications: getNumberOfApplications
        };
        return service;

        ////////////////
        function getNumberOfApplications() {
            var url = base + 'count';
            return $http.get(url).then(successCallback);
        }

        function getSpecificApplications() {
            var url = base + 'specific';
            return $http.get(url).then(successCallback);
        }
        function getRecentApplications(size) {
            var params = {
                size: size || 20,
                page: 0,
                sort: 'createDate',
                'createDate.dir': 'desc'
            };
            return $http.get(base, {params: params}).then(successCallback);
        }

        function successCallback(response) {
            return response.data;
        }

    }

})();<file_sep>package ir.saafta.model;



import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import ir.saafta.dto.ApplicationStatus;
import org.springframework.context.annotation.Scope;

import javax.imageio.ImageIO;
import javax.persistence.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;

/**
 * Created by reza on 11/13/16.
 */
@Entity
public class Picture implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long contentId;
    @JsonIgnore
    private byte[] data;
    private String label;
    private String type;
    private String format;
    private Boolean published;
    private ApplicationStatus applicationStatus;
    @Transient
    private String url;

    public Picture(byte[] data, String label, String type, String fileName) throws ParseException {
        this.data = data;
        this.label = label;
        this.type = type;
        this.published = false;
        this.format = extractFormat(fileName);
        this.applicationStatus = ApplicationStatus.PUBLIC;
    }

    public Picture(Long contentId, byte[] data, String label, String type, String fileNameOrFormat) throws ParseException {
        this.contentId = contentId;
        this.data = data;
        this.label = label;
        this.type = type;
        this.published = false;
        this.format = extractFormat(fileNameOrFormat);
        this.applicationStatus = ApplicationStatus.PUBLIC;
    }

    public Picture(Long contentId, byte[] data, String label, String type, String fileNameOrFormat,
                   ApplicationStatus applicationStatus) throws ParseException {
        this.contentId = contentId;
        this.data = data;
        this.label = label;
        this.type = type;
        this.published = false;
        this.format = extractFormat(fileNameOrFormat);
        this.applicationStatus = applicationStatus != null ? applicationStatus : ApplicationStatus.PUBLIC;
    }

    public Picture(){

    }

    private String extractFormat(String fileNameOrFormat) throws ParseException {
        if (fileNameOrFormat == null)
            throw new ParseException("Unknown file format", 0);
        fileNameOrFormat = fileNameOrFormat.toLowerCase();
        if (fileNameOrFormat.equals("jpg") || fileNameOrFormat.equals("jpeg"))
            return "jpg";
        else if (fileNameOrFormat.equals("png") || fileNameOrFormat.equals("tiff") ||
                fileNameOrFormat.equals("gif") || fileNameOrFormat.equals("bmp"))
            return fileNameOrFormat;

        if (fileNameOrFormat.endsWith(".jpg") || fileNameOrFormat.endsWith(".jpeg"))
            return "jpg";
        else if (fileNameOrFormat.endsWith(".png"))
            return "png";
        else if (fileNameOrFormat.endsWith(".tiff"))
            return "tiff";
        else if (fileNameOrFormat.endsWith(".gif"))
            return "gif";
        else if (fileNameOrFormat.endsWith(".bmp"))
            return "bmp";
        else
            throw new ParseException("Unknown file format", 0);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getContentId() {
        return contentId;
    }

    public void setContentId(Long contentId) {
        this.contentId = contentId;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
//        String format = this.format != null ? this.format : "jpg";
        String format = "jpg";
        if (this.id != null) {
            String url = "picture/" + this.id + "/pic";
            if (this.contentId != null)
                url += this.contentId + "_";
            if (this.type != null)
                url += this.type + "_";
            url += this.id + "." + format;
            return url;
        }
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Boolean getPublished() {
        return published;
    }

    public void setPublished(Boolean published) {
        this.published = published;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) throws ParseException {
        this.format = extractFormat(format);
    }

    @Transient
    public int getWidth() {
        if (this.getData() == null)
            return -1;
        try {
            InputStream in = new ByteArrayInputStream(this.getData());
            BufferedImage image = ImageIO.read(in);
            return image.getWidth();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Transient
    public int getHeight() {
        if (this.getData() == null)
            return -1;
        try {
            InputStream in = new ByteArrayInputStream(this.getData());
            BufferedImage image = ImageIO.read(in);
            return image.getHeight();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public ApplicationStatus getApplicationStatus() {
        return applicationStatus;
    }

    public void setApplicationStatus(ApplicationStatus applicationStatus) {
        this.applicationStatus = applicationStatus;
    }
}
<file_sep>package ir.saafta.model;

import ir.saafta.dto.SessionStatus;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import java.util.Date;

/**
 * Created by rkesh on 6/30/2017.
 */
@Entity
public class Session {
    @Id
    private String sessionId;
    private String username;
    private Date creationTime;
    private Date finishTime;
    @Enumerated(EnumType.ORDINAL)
    private SessionStatus status;
    private Date lastRequest;
    private String remoteAddr;
    private String deviceInfo;


    public Session() {
    }

    public Session(String sessionId, String username, Date creationTime, Date finishTime, SessionStatus status, Date lastRequest, String remoteAddr, String deviceInfo) {
        this.sessionId = sessionId;
        this.username = username;
        this.creationTime = creationTime;
        this.finishTime = finishTime;
        this.status = status;
        this.lastRequest = lastRequest;
        this.remoteAddr = remoteAddr;
        this.deviceInfo = deviceInfo;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(Date creationTime) {
        this.creationTime = creationTime;
    }

    public Date getFinishTime() {
        return finishTime;
    }

    public void setFinishTime(Date finishTime) {
        this.finishTime = finishTime;
    }

    public SessionStatus getStatus() {
        return status;
    }

    public void setStatus(SessionStatus status) {
        this.status = status;
    }

    public Date getLastRequest() {
        return lastRequest;
    }

    public void setLastRequest(Date lastRequest) {
        this.lastRequest = lastRequest;
    }

    public String getRemoteAddr() {
        return remoteAddr;
    }

    public void setRemoteAddr(String remoteAddr) {
        this.remoteAddr = remoteAddr;
    }

    public String getDeviceInfo() {
        return deviceInfo;
    }

    public void setDeviceInfo(String deviceInfo) {
        this.deviceInfo = deviceInfo;
    }
}
<file_sep>spring.datasource.url=jdbc:mysql://simorgh_db/simorgh?characterEncoding=utf-8
spring.datasource.username=suser
spring.datasource.password=<PASSWORD><file_sep>package ir.saafta.model;


import org.hibernate.annotations.FilterJoinTable;
import org.hibernate.annotations.WhereJoinTable;

import javax.persistence.*;
import java.util.List;

/**
 * Created by rkesh on 7/4/2017.
 */
@Entity
@Table(name = "user")
public class UserProperties {
    @Id
    private String username;
    @ManyToMany
    @JoinTable(
            name = "user_content",
            joinColumns = @JoinColumn(name = "username", referencedColumnName = "username"),
            inverseJoinColumns = @JoinColumn(name = "contentId", referencedColumnName = "id"))
    @WhereJoinTable(clause = "bookmarked = true")
    private List<Application> bookmarked;

    @ManyToMany
    @JoinTable(
            name = "user_content",
            joinColumns = @JoinColumn(name = "username", referencedColumnName = "username"),
            inverseJoinColumns = @JoinColumn(name = "contentId", referencedColumnName = "id"))
    @WhereJoinTable(clause = "install_date is not null")
    private List<Application> downloaded;

    @ManyToMany
    @JoinTable(
            name = "userContent",
            joinColumns = @JoinColumn(name = "username", referencedColumnName = "username"),
            inverseJoinColumns = @JoinColumn(name = "contentId", referencedColumnName = "id"))
    @WhereJoinTable(clause = "bought = 1")
    private List<Application> bought;


    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }

    public List<Application> getBookmarked() {
        return bookmarked;
    }

    public void setBookmarked(List<Application> bookmarked) {
        this.bookmarked = bookmarked;
    }

    public List<Application> getDownloaded() {
        return downloaded;
    }

    public void setDownloaded(List<Application> downloaded) {
        this.downloaded = downloaded;
    }

    public List<Application> getBought() {
        return bought;
    }

    public void setBought(List<Application> bought) {
        this.bought = bought;
    }
}
