Commit 3d30819d authored by Srikanth Gajula's avatar Srikanth Gajula

MT-01:[Srikanth] committing intial project setup and related rest

services
parent 87e1b7d5
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.nisum.mytime'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.data:spring-data-mongodb')
compile('org.springframework:spring-context-support')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-data-rest')
compile('org.springframework.boot:spring-boot-starter-web')
compile('javax.servlet:jstl')
compile('javax.mail:mail:1.4.1')
compile('org.mongodb:mongo-java-driver')
compile('org.projectlombok:lombok:1.16.+')
compile('org.quartz-scheduler:quartz:2.2.1')
compile('org.quartz-scheduler:quartz:2.3.0')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile ('junit:junit:4.12')
compile('net.sf.ucanaccess:ucanaccess:4.0.1')
testCompile('org.hsqldb:hsqldb')
compile('com.healthmarketscience.jackcess:jackcess')
compile('commons-logging:commons-logging')
compile('commons-lang:commons-lang')
compile('com.jcraft:jsch:0.1.46')
compile('com.itextpdf:itextpdf:5.0.6')
compile('jcifs:jcifs:1.3.17')
compile('javax.servlet:servlet-api')
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-bin.zip
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
package com.nisum.mytime;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@SpringBootApplication
@EnableAutoConfiguration
@EnableMongoRepositories(basePackages = { "com.nisum.mytime.repository" })
public class MyTimeApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyTimeApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyTimeApplication.class, args);
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
package com.nisum.mytime.configuration;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
private static Connection connection = null;
public static Connection getDBConnection(String dbURL) throws SQLException {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
connection = DriverManager.getConnection(dbURL);
} catch (ClassNotFoundException cnfex) {
System.out.println("Problem in loading or " + "registering MS Access JDBC driver");
cnfex.printStackTrace();
}
return connection;
}
}
package com.nisum.mytime.configuration;
import java.io.IOException;
import java.util.Properties;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import com.nisum.mytime.schedular.AutowiringSpringBeanJobFactory;
import com.nisum.mytime.schedular.MyTimeCronSchedularJob;
@Configuration
@ConditionalOnProperty(name = "quartz.enabled")
public class SchedulerConfig {
@Value("${cron.expression}")
private String crosExp;
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public Scheduler schedulerFactoryBean(JobFactory jobFactory,
@Qualifier("myTimeJobTrigger") Trigger myTimeJobTrigger) throws Exception {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setOverwriteExistingJobs(true);
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
factory.afterPropertiesSet();
Scheduler scheduler = factory.getScheduler();
scheduler.setJobFactory(jobFactory);
scheduler.scheduleJob((JobDetail) myTimeJobTrigger.getJobDataMap().get("jobDetail"), myTimeJobTrigger);
scheduler.start();
return scheduler;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
@Bean
public JobDetailFactoryBean myTimeJobDetail() {
return createJobDetail(MyTimeCronSchedularJob.class);
}
@Bean(name = "myTimeJobTrigger")
public CronTriggerFactoryBean myTimeJobTrigger(@Qualifier("myTimeJobDetail") JobDetail jobDetail,
@Value("${myTimejob.frequency}") long frequency) {
return createCronTrigger(jobDetail, frequency);
}
private JobDetailFactoryBean createJobDetail(Class<MyTimeCronSchedularJob> jobClass) {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(jobClass);
factoryBean.setDurability(true);
return factoryBean;
}
private CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, long cronExpression) {
CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
factoryBean.setJobDetail(jobDetail);
factoryBean.setCronExpression(crosExp);
factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
return factoryBean;
}
}
\ No newline at end of file
package com.nisum.mytime.configuration;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.nisum.mytime.utils.MyTimeLogger;
@Configuration
public class SpringMongoConfig {
@Bean
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,
BeanFactory beanFactory) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
try {
mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
} catch (NoSuchBeanDefinitionException ignore) {
MyTimeLogger.getInstance().log(ignore.getMessage());
}
mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
return mappingConverter;
}
}
package com.nisum.mytime.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController("/")
public class ApplicationController {
public String login() {
return "index";
}
}
package com.nisum.mytime.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.service.UserService;
@RestController
@RequestMapping("/attendance")
public class AttendanceController {
@Autowired
private UserService userService;
@RequestMapping(value = "employee/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<EmpLoginData>> fetchEmployeeDataBasedOnEmpId(@PathVariable("id") long id)
throws MyTimeException {
List<EmpLoginData> empLoginData = userService.fetchEmployeeDataBasedOnEmpId(id);
return new ResponseEntity<>(empLoginData, HttpStatus.OK);
}
@RequestMapping(value = "employeeLoginsBasedOnDate/{id}/{fromDate}/{toDate}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<EmpLoginData>> employeeLoginsBasedOnDate(@PathVariable("id") long id,
@PathVariable("fromDate") String fromDate, @PathVariable("toDate") String toDate) throws MyTimeException {
List<EmpLoginData> message = userService.employeeLoginsBasedOnDate(id, fromDate, toDate);
return new ResponseEntity<>(message, HttpStatus.OK);
}
@RequestMapping(value = "generatePdfReport/{id}/{fromDate}/{toDate}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> generatePdfReport(@PathVariable("id") long id,
@PathVariable("fromDate") String fromDate, @PathVariable("toDate") String toDate)
throws MyTimeException {
String result= userService.generatePdfReport(id, fromDate, toDate);
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
\ No newline at end of file
package com.nisum.mytime.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.mytime.model.EmailDomain;
import com.nisum.mytime.service.MailService;
@RestController
public class EmailController {
@Autowired
private MailService mailService;
@RequestMapping(value = "/sendEmail", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> sendAttachmentMail(@RequestBody EmailDomain emailObj) {
String response = mailService.sendEmailWithAttachment(emailObj);
if ("Success".equals(response))
return new ResponseEntity<>(response, HttpStatus.OK);
else
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping(value = "/deleteReport/{fileName}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> deletePdfReport(@PathVariable("fileName") String fileName) {
String response = mailService.deletePdfReport(fileName);
if ("Success".equals(response))
return new ResponseEntity<>(response, HttpStatus.OK);
else
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
package com.nisum.mytime.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.nisum.mytime.model.Employee;
@Controller
public class GoogleController {
@PostMapping("/empData")
@ResponseBody
public String getEmpData(@RequestBody Employee employee,
HttpSession session) {
System.out.println(employee.getEmail());
return "{'message':'success'}";
}
}
package com.nisum.mytime.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmployeeRoles;
import com.nisum.mytime.service.UserService;
@RestController
@RequestMapping("/employee")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "employee/{emailId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EmployeeRoles> getEmployeeRole(@PathVariable("emailId") String emailId)
throws MyTimeException {
EmployeeRoles employeesRole = userService.getEmployeesRole(emailId);
return new ResponseEntity<>(employeesRole, HttpStatus.OK);
}
@RequestMapping(value = "/employeesDataSave", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> employeesDataSave() throws MyTimeException {
Boolean result = userService.fetchEmployeesData();
return new ResponseEntity<>(result, HttpStatus.OK);
}
@RequestMapping(value = "/assigingEmployeeRole", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> assigingEmployeeRole(@RequestBody EmployeeRoles employeeRoles) throws MyTimeException {
EmployeeRoles employeeRole = userService.assigingEmployeeRole(employeeRoles);
return new ResponseEntity<>(employeeRole.getId(), HttpStatus.OK);
}
@RequestMapping(value = "/deleteEmployee", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> deleteEmployee(@RequestBody EmployeeRoles employeeRoles) throws MyTimeException {
userService.deleteEmployee(employeeRoles);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@RequestMapping(value = "/getEmployeeRoles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<EmployeeRoles>> getEmployeeRoles() throws MyTimeException {
List<EmployeeRoles> employeesRoles = userService.getEmployeeRoles();
return new ResponseEntity<>(employeesRoles, HttpStatus.OK);
}
}
\ No newline at end of file
package com.nisum.mytime.exception.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(DataAccessException.class)
public String handleDataAccessExceptions(DataAccessException ex){
log.error("DataAccessException occured due to: ",ex);
return "DataAccessException occured due to: "+ex.toString();
}
@ExceptionHandler(Exception.class)
public String handleOtherExceptions(Exception ex){
log.error("Exception occured due to: ",ex);
return "Exception occured due to: "+ex.toString();
}
}
\ No newline at end of file
package com.nisum.mytime.exception.handler;
public class MyTimeException extends Exception {
/**
*
*/
private static final long serialVersionUID = 3489301441198508177L;
public MyTimeException() {
}
public MyTimeException(String arg0) {
super(arg0);
}
public MyTimeException(Throwable arg0) {
super(arg0);
}
public MyTimeException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public MyTimeException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
}
}
package com.nisum.mytime.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
public class DateCompare implements Comparator<EmpLoginData> {
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public int compare(EmpLoginData o1, EmpLoginData o2) {
Date first = null;
Date second = null;
try {
first = formatter.parse(o1.getFirstLogin());
second = formatter.parse(o2.getFirstLogin());
} catch (ParseException e) {
e.printStackTrace();
}
return first.before(second) ? -1 : first.after(second) ? 1 : 0;
}
}
\ No newline at end of file
package com.nisum.mytime.model;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class EmailDomain {
private String[] toEmail;
private String[] ccEmail;
private String[] bccEmail;
private String empId;
private String fromDate;
private String toDate;
}
package com.nisum.mytime.model;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document(collection = "EmployeesLoginData")
public class EmpLoginData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8448056441155775579L;
@Id
private String id;
private String employeeId;
private String employeeName;
private String dateOfLogin;
private String firstLogin;
private String lastLogout;
private String totalLoginTime;
private String direction;
}
package com.nisum.mytime.model;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Employee {
private String email;
private String name;
private String givenName;
private String familyName;
}
package com.nisum.mytime.model;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document(collection = "EmployeeRoles")
public class EmployeeRoles implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2685951572250975416L;
@Id
private String id;
private String employeeId;
private String employeeName;
private String emailId;
private String role;
}
package com.nisum.mytime.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.nisum.mytime.model.EmpLoginData;
public interface EmployeeAttendanceRepo extends MongoRepository<EmpLoginData, Long> {
}
package com.nisum.mytime.repository;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.nisum.mytime.model.EmployeeRoles;
public interface EmployeeRolesRepo extends MongoRepository<EmployeeRoles, Serializable> {
EmployeeRoles findByEmailId(String emailId);
}
package com.nisum.mytime.schedular;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
public void setApplicationContext(final ApplicationContext context) {
beanFactory = context.getAutowireCapableBeanFactory();
}
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}
package com.nisum.mytime.schedular;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.service.AttendanceDataService;
import com.nisum.mytime.utils.MyTimeLogger;
@DisallowConcurrentExecution
public class MyTimeCronSchedularJob implements Job {
@Autowired
private AttendanceDataService attendanceDataService;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
try {
attendanceDataService.populateEmployeeAttendanceData();
} catch (MyTimeException e) {
MyTimeLogger.getInstance().info(e.getMessage());
}
}
}
/**
*
*/
package com.nisum.mytime.service;
import com.nisum.mytime.model.EmailDomain;
/**
* @author nisum
*
*/
public interface MailService {
public String sendEmailWithAttachment(EmailDomain emailObj);
public String deletePdfReport(String fileName);
}
/**
*
*/
package com.nisum.mytime.service;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.nisum.mytime.model.EmailDomain;
/**
* @author nisum
*
*/
@Service
public class MailServiceImpl implements MailService {
private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Autowired
JavaMailSender emailSender;
@Autowired
ResourceLoader resourceLoader;
@Value("${spring.mail.username}")
private String fromEmail;
@Override
public String sendEmailWithAttachment(EmailDomain emailObj) {
String response = "Success";
MimeMessage msg = emailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setTo(emailObj.getToEmail());
helper.setCc(emailObj.getCcEmail());
helper.setFrom(fromEmail);
helper.setSubject(emailObj.getEmpId() + " - Login hours Report");
helper.setText("Hi,\n PFA for your login hours report for the period: " + emailObj.getFromDate() + " / "
+ emailObj.getToDate());
String fileName = emailObj.getEmpId() + "_" + emailObj.getFromDate() + "_" + emailObj.getToDate()+".pdf";
File file = resourceLoader.getResource("/reports/" + fileName).getFile();
FileSystemResource fileSystem = new FileSystemResource(file);
helper.addAttachment(fileSystem.getFilename(), fileSystem);
helper.setSentDate(new Date());
emailSender.send(msg);
} catch (MessagingException e) {
response = "Mail sending failed due to " + e.getMessage();
logger.error("Mail sending failed due to: ", e);
} catch (IOException e) {
response = "Mail sending failed due to " + e.getMessage();
logger.error("Mail sending failed due to: ", e);
}
return response;
}
@Override
public String deletePdfReport(String fileName) {
String response = "";
try {
File file = resourceLoader.getResource("/reports/" + fileName+".pdf").getFile();
if(file.exists()){
boolean status = file.delete();
if(status){
response = "Success";
}
}
} catch (IOException e) {
response = "Report deletion failed due to: " + e.getMessage();
logger.error("Report deletion failed due to: ", e);
}
return response;
}
}
package com.nisum.mytime.service;
import java.util.List;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.model.EmployeeRoles;
public interface UserService {
List<EmpLoginData> fetchEmployeeDataBasedOnEmpId(long id) throws MyTimeException;
Boolean fetchEmployeesData() throws MyTimeException;
List<EmpLoginData> employeeLoginsBasedOnDate(long id, String fromDate, String toDate) throws MyTimeException;
List<EmployeeRoles> getEmployeeRoles() throws MyTimeException;
EmployeeRoles assigingEmployeeRole(EmployeeRoles employeeRoles) throws MyTimeException;
String generatePdfReport(long id, String fromDate, String toDate) throws MyTimeException;
EmployeeRoles getEmployeesRole(String emailId);
void deleteEmployee(EmployeeRoles employeeRoles);
}
package com.nisum.mytime.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.model.EmployeeRoles;
import com.nisum.mytime.repository.EmployeeAttendanceRepo;
import com.nisum.mytime.repository.EmployeeRolesRepo;
import com.nisum.mytime.utils.PdfReportGenerator;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private EmployeeAttendanceRepo employeeLoginsRepo;
@Autowired
private EmployeeRolesRepo employeeRolesRepo;
@Autowired
private EmployeeDataService employeeDataBaseService;
@Autowired
private PdfReportGenerator pdfReportGenerator;
@Override
public List<EmpLoginData> fetchEmployeeDataBasedOnEmpId(long id) throws MyTimeException {
return employeeDataBaseService.fetchEmployeeDataBasedOnEmpId(id);
}
@Override
public Boolean fetchEmployeesData() throws MyTimeException {
Boolean result = false;
List<EmpLoginData> listOfEmpLoginData = employeeDataBaseService.fetchEmployeesData();
employeeLoginsRepo.save(listOfEmpLoginData);
result = true;
return result;
}
@Override
public List<EmpLoginData> employeeLoginsBasedOnDate(long id, String fromDate, String toDate)
throws MyTimeException {
return employeeDataBaseService.fetchEmployeeLoginsBasedOnDates(id, fromDate, toDate);
}
@Override
public String generatePdfReport(long id, String fromDate, String toDate) throws MyTimeException {
return pdfReportGenerator.generateEmployeeReport(id, fromDate, toDate);
}
@Override
public List<EmployeeRoles> getEmployeeRoles() throws MyTimeException {
return employeeRolesRepo.findAll();
}
@Override
public EmployeeRoles assigingEmployeeRole(EmployeeRoles employeeRoles) throws MyTimeException {
return employeeRolesRepo.save(employeeRoles);
}
@Override
public EmployeeRoles getEmployeesRole(String emailId) {
return employeeRolesRepo.findByEmailId(emailId);
}
@Override
public void deleteEmployee(EmployeeRoles employeeRoles) {
employeeRolesRepo.delete(employeeRoles);
}
}
package com.nisum.mytime.utils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class MyTimeLogger {
/** The logging instance. */
private static MyTimeLogger loggingInstance = null;
/** The logger. */
private static Logger logger = null;
private MyTimeLogger() {
logger = LogManager.getLogger("com.nisum.mytime.utils.MyTimeLogger");
}
public static MyTimeLogger getInstance() {
if (loggingInstance == null) {
synchronized (MyTimeLogger.class) {
if (loggingInstance == null) {
loggingInstance = new MyTimeLogger();
return loggingInstance;
} else {
return loggingInstance;
}
}
} else {
return loggingInstance;
}
}
private String getClassName() {
String className = "";
try {
className = Thread.currentThread().getStackTrace()[3].getClassName();
} catch (Exception e) {
e.printStackTrace();
}
return className;
}
private String getMethodName() {
String methodName = "";
try {
methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
} catch (Exception e) {
e.printStackTrace();
}
return methodName;
}
public void entry() {
String message = "Entry";
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.INFO, logMsg);
}
public void info(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.INFO, logMsg);
}
public void warn(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.WARN, logMsg);
}
public void warn(String message, Throwable t) {
String logMsg = getClassName() + " : " + getMethodName() + " - " + message;
logger.log(Level.WARN, logMsg, t);
}
public void debug(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.DEBUG, logMsg);
}
public void debug(String message, Throwable t) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.DEBUG, logMsg, t);
}
public void error(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.ERROR, logMsg);
}
public void error(String message, Throwable t) {
String logMsg = getClassName() + " : " + getMethodName() + " - " + message;
logger.log(Level.ERROR, logMsg, t);
}
public void fatal(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.FATAL, logMsg);
}
public void trace(String message) {
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.TRACE, logMsg);
}
public void log(String msg) {
logger.log(Level.INFO, msg);
}
public void exit() {
String message = "Exit";
String logMsg = "TID : " + Thread.currentThread().getId() + " : " + getClassName() + " : " + getMethodName()
+ " - " + message;
logger.log(Level.INFO, logMsg);
}
}
package com.nisum.mytime.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class MyTimeUtils {
private MyTimeUtils() {
}
public final static String driverUrl = "jdbc:ucanaccess://";
public final static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public final static DateFormat tdf = new SimpleDateFormat("HH:mm");
public final static DateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd");
}
package com.nisum.mytime.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.service.EmployeeDataService;
@Component
public class PdfReportGenerator {
@Autowired
ResourceLoader resourceLoader;
@Autowired
private EmployeeDataService employeeDataBaseService;
public String generateEmployeeReport(long employeeId, String startDate, String endDate) throws MyTimeException {
String fileName = employeeId + "_" + startDate + "_" + endDate + ".pdf";
List<EmpLoginData> empLoginDetails = getEmployeeData(employeeId, startDate, endDate);
return createPDF(fileName, empLoginDetails);
}
private List<EmpLoginData> getEmployeeData(long employeeId, String fromDate, String toDate) throws MyTimeException {
return employeeDataBaseService.fetchEmployeeLoginsBasedOnDates(employeeId, fromDate, toDate);
}
private String createPDF(String pdfFilename, List<EmpLoginData> empLoginDatas) throws MyTimeException {
Document doc = new Document();
PdfWriter docWriter = null;
try {
File file = resourceLoader.getResource("/reports/" + pdfFilename).getFile();
docWriter = PdfWriter.getInstance(doc, new FileOutputStream(file.getPath()));
setPdfDocumentProperties(doc);
doc.open();
preparePdfDocument(doc, empLoginDatas);
} catch (Exception dex) {
MyTimeLogger.getInstance()
.error("DocumentException while generating {} " + pdfFilename + "\n" + dex.getMessage());
throw new MyTimeException(dex.getMessage());
} finally {
if (doc != null) {
doc.close();
}
if (docWriter != null) {
docWriter.close();
}
}
return pdfFilename;
}
private void setPdfDocumentProperties(Document doc) {
doc.addAuthor("Nisum Consulting Pvt. Ltd.");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("MyTime");
doc.addTitle("Nisum MyTime Employee Report");
doc.setPageSize(PageSize.A4);
}
private void preparePdfDocument(Document doc, List<EmpLoginData> empLoginDatas) throws DocumentException {
boolean isFirst = true;
Paragraph paragraph = new Paragraph();
Paragraph paragraph1 = new Paragraph();
float[] columnWidths = { 1f, 1f, 1f, 1f };
PdfPTable table = new PdfPTable(columnWidths);
table.setWidthPercentage(100f);
prepareTableHeader(table);
for (EmpLoginData data : empLoginDatas) {
if (isFirst) {
Anchor anchorTarget = new Anchor(
"Employee Id : " + data.getEmployeeId() + "\nEmployee Name : " + data.getEmployeeName());
isFirst = false;
paragraph1.add(anchorTarget);
}
prepareTableRow(table, data);
}
paragraph.add(table);
doc.add(paragraph1);
paragraph.setSpacingBefore(1);
doc.add(paragraph);
}
private void prepareTableHeader(PdfPTable table) {
Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
insertCell(table, "Date ", Element.ALIGN_CENTER, 1, bfBold12);
insertCell(table, "Login Time", Element.ALIGN_CENTER, 1, bfBold12);
insertCell(table, "Logout Time", Element.ALIGN_CENTER, 1, bfBold12);
insertCell(table, "Total Hours", Element.ALIGN_CENTER, 1, bfBold12);
table.setHeaderRows(1);
}
private void prepareTableRow(PdfPTable table, EmpLoginData data) {
Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);
insertCell(table, data.getDateOfLogin(), Element.ALIGN_CENTER, 1, bf12);
insertCell(table, data.getFirstLogin(), Element.ALIGN_CENTER, 1, bf12);
insertCell(table, data.getLastLogout(), Element.ALIGN_CENTER, 1, bf12);
insertCell(table, data.getTotalLoginTime(), Element.ALIGN_CENTER, 1, bf12);
}
private void insertCell(PdfPTable table, String text, int align, int colspan, Font font) {
PdfPCell cell = new PdfPCell(new Phrase(text.trim(), font));
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
if (text.trim().equalsIgnoreCase("")) {
cell.setMinimumHeight(10f);
}
table.addCell(cell);
}
}
server.port=8080
#Mongo DB configuration
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mytime
quartz.enabled=false
cron.expression=0 0/1 * 1/1 * ? *
myTimejob.frequency=10000
mytime.remoteFileTransfer.required=false
mytime.remote.connection=smb://MyTime:nisum@192.168.15.67/eTimeTrackLite/
mytime.localFile.directory=/Users/nisum/Documents/
mytime.remote.directory=/C:\\Program Files (x86)\\eSSL\\eTimeTrackLite
mytime.attendance.fileName=eTimeTrackLite1.mdb
#Mail configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<no-reply@nisum.com>
spring.mail.password=<password>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
org.quartz.scheduler.instanceName=NisumTime
org.quartz.scheduler.instanceId=AUTO
org.quartz.threadPool.threadCount=5
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
\ No newline at end of file
package com.nisum.mytime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTimeApplicationTests {
@Test
public void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment