Commit 7d1ea13e authored by hcordova's avatar hcordova

feat: added flight agency endpoints

parents
Pipeline #393 failed with stages
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
FROM java:openjdk-8-jdk-alpine
MAINTAINER schicoma@bytesw.com
USER root
#RUN yum -y install java-1.8.0-openjdk
RUN apk add --update curl && \
rm -rf /var/cache/apk/*
RUN export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:/bin/java::")
RUN export PATH=$JAVA_HOME/bin:$PATH
# VOLUME /tmp
RUN echo 'target/bytebot-service-1.0.1-SNAPSHOT.jar'
COPY 'target/bytebot-service-1.0.1-SNAPSHOT.jar' app.jar
# ENV JAVA_OPTS="-Xms512m -Xmx1024m"
EXPOSE 8080
EXPOSE 8443
EXPOSE 22
ENTRYPOINT [ "sh", "-c", "java -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
FROM python:3.8-slim
USER root
COPY . .
RUN apt update && \
apt install -y nano curl awscli
RUN chmod +x entrypoint.sh
RUN mkdir /data
VOLUME [ "/data" ]
CMD ["sh","entrypoint.sh"]
\ No newline at end of file
pipeline {
agent any
parameters {
string(defaultValue: 'no', description: 'Ejecuta los procesos docker', name: 'include_docker')
}
environment {
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
url = "http://192.168.27.148:5000"
tag_name = "192.168.27.148:5000"
imagename = "${tag_name}/bytesw/${IMAGE}"
credentials = "admin-docker-hub"
}
tools {
maven 'Maven'
jdk "jdk-11.0.1"
jdk "jdk8"
}
stages {
stage ('Initialize') {
steps {
sh '''
echo "PATH = ${PATH}"
echo "M2_HOME = ${M2_HOME}"
'''
}
}
stage('Build') {
steps {
withMaven(maven: 'Maven', mavenSettingsConfig: '2ea57b6f-d6f0-42bc-9770-f24d4170a439') {
sh 'mvn -B -DskipTests clean package'
}
}
}
stage('Test') {
steps {
withMaven(maven: 'Maven', mavenSettingsConfig: '2ea57b6f-d6f0-42bc-9770-f24d4170a439') {
sh 'mvn test'
}
}
post {
always {
junit 'target/surefire-reports/*.xml'
}
}
}
/* stage('Code Quality Check via SonarQube') {
steps {
withEnv(["JAVA_HOME=${tool 'jdk8'}", "PATH=${tool 'jdk8'}/bin:${env.PATH}"]) {
withMaven(maven: 'Maven', mavenSettingsConfig: '2ea57b6f-d6f0-42bc-9770-f24d4170a439') {
sh 'mvn -DskipTests sonar:sonar \
-Dsonar.projectKey=bytebot-service_$BRANCH_NAME \
-Dsonar.projectName=bytebot-service_$BRANCH_NAME \
-Dsonar.sources=src/main/java/ \
-Dsonar.language=java \
-Dsonar.java.binaries=target/classes \
-Dsonar.junit.reportsPath=target/surefire-reports \
-Dsonar.jacoco.reportPaths=target/jacoco.exec \
-Dsonar.cobertura.reportPath=target/site/cobertura/coverage.xml \
-Dsonar.clover.reportPath=target/clover.xml \
-Dsonar.dynamicAnalysis=reuseReports \
-Dsonar.java.coveragePlugin=plugin \
-Dsonar.jacoco.reportMissing.force.zero=true \
-Dsonar.host.url=http://byteswpe-sonar.tbs.com:9000 \
-Dsonar.login=d09303420d51f36385b4613d29ee98978ca2ebe4'
}}
}
} */
stage('Deploy') {
steps {
withMaven(maven: 'Maven', mavenSettingsConfig: '2ea57b6f-d6f0-42bc-9770-f24d4170a439') {
sh 'mvn -DskipTests deploy'
}
}
}
stage('Build Docker Image') {
when {
expression { params.include_docker == 'yes' }
}
steps {
withMaven(maven: 'Maven', mavenSettingsConfig: '2ea57b6f-d6f0-42bc-9770-f24d4170a439') {
sh 'mvn clean install -DskipTests -P docker'
}
}
}
stage('Deploy Image') {
when {
expression { params.include_docker == 'yes' }
}
steps{
script {
docker.withRegistry(url, credentials ) {
sh "docker push ${imagename}:${VERSION}"
sh "docker tag ${imagename}:${VERSION} ${imagename}:latest"
sh "docker push ${imagename}:latest"
}
}
}
}
stage('Remove Unused docker image') {
when {
expression { params.include_docker == 'yes' }
}
steps {
sh "docker rmi ${imagename}:latest"
sh "docker rmi ${imagename}:${VERSION}"
}
}
}
post {
always {
echo 'Confirmación de ejecución!'
emailext body: "${currentBuild.currentResult}: Job ${env.JOB_NAME} build ${env.BUILD_NUMBER}\n More info at: ${env.BUILD_URL}",
recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
subject: "Jenkins Build ${currentBuild.currentResult}: Job ${env.JOB_NAME}",
to: '$DEFAULT_RECIPIENTS'
}
}
}
DROP TABLE IF EXISTS `PILO_ENTITY` CASCADE;
DROP TABLE IF EXISTS `TiposDeMotivo` CASCADE;
DROP TABLE IF EXISTS `XDF_ENTIDADES` CASCADE;
DROP TABLE IF EXISTS `Estados` CASCADE;
DROP TABLE IF EXISTS `Motivos` CASCADE;
CREATE TABLE PILO_ENTITY
(
`ENT_ID` BIGINT NOT NULL COMMENT 'Identificador único del tipo de la entidad, secuencial auto generado.',
`ENT_NAME` VARCHAR(50) NOT NULL COMMENT 'Nombre de la entidad.',
`ENT_DESC` VARCHAR(50) NOT NULL COMMENT 'Descripción de la entidad',
CONSTRAINT `PK_Entidades` PRIMARY KEY (`ENT_ID` ASC)
)
COMMENT='Catálogo de entidades del sistema'
;
CREATE TABLE `Estados`
(
`idEstado` BIGINT NOT NULL,
`idEntidad` BIGINT NULL,
`codEstado` BIGINT NULL,
`aliasEstado` VARCHAR(20) NULL,
`descEstado` VARCHAR(50) NULL,
CONSTRAINT `PK_Estados` PRIMARY KEY (`idEstado` ASC)
)
;
CREATE TABLE `Motivos`
(
`idMotivo` BIGINT NOT NULL COMMENT 'Identificador de motivo, secuencial auto generado.',
`codMotivo` BIGINT NULL COMMENT 'Código de motivo para el negocio.',
`descMotivo` VARCHAR(50) NULL COMMENT 'Descripción motivo.',
`idTipoDeMotivo` BIGINT NULL,
CONSTRAINT `PK_Motivos` PRIMARY KEY (`idMotivo` ASC)
)
COMMENT='Motivos para usos varios.'
;
CREATE TABLE `TiposDeMotivo`
(
`idTipoDeMotivo` BIGINT NOT NULL COMMENT 'Identificador único del tipo de motivo, secuencial auto generado.',
`codTipoDeMotivo` BIGINT NOT NULL COMMENT 'Código del tipo de motivo para el negocio.',
`descTipoDeMotivo` VARCHAR(50) NOT NULL COMMENT 'Descripción del tipo de motivo.',
`aliasTipoDeMotivo` VARCHAR(20) NOT NULL COMMENT 'Alias del tipo de motivo para uso desde el sistema.',
CONSTRAINT `PK_TiposDeMotivo` PRIMARY KEY (`idTipoDeMotivo` ASC)
)
COMMENT='Agrupan los motivos.'
;
\ No newline at end of file
#!/bin/bash
aws s3 sync s3://$bucket$path /data/$directory/
while :
do
echo "Container is still running"
sleep 5
done
\ No newline at end of file
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
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
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<netbeans.hint.jdkPlatform>JDK_1.8</netbeans.hint.jdkPlatform>
</properties>
</project-shared-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action>
<actionName>run</actionName>
<packagings>
<packaging>jar</packaging>
</packagings>
<goals>
<goal>process-classes</goal>
<goal>org.codehaus.mojo:exec-maven-plugin:1.5.0:exec</goal>
</goals>
<properties>
<exec.args>-classpath %classpath com.bytesw.bytebot.BytebotApplication -Djasypt.encryptor.password=179CD78D24F9BC63D6E677272D1A7 -Xms256M -Xmx512M</exec.args>
<exec.executable>java</exec.executable>
</properties>
</action>
<action>
<actionName>debug</actionName>
<packagings>
<packaging>jar</packaging>
</packagings>
<goals>
<goal>process-classes</goal>
<goal>org.codehaus.mojo:exec-maven-plugin:1.5.0:exec</goal>
</goals>
<properties>
<exec.args>-agentlib:jdwp=transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath com.bytesw.bytebot.BytebotApplication -Djasypt.encryptor.password=179CD78D24F9BC63D6E677272D1A7 -Xms256M -Xmx512M</exec.args>
<exec.executable>java</exec.executable>
<jpda.listen>true</jpda.listen>
</properties>
</action>
<action>
<actionName>profile</actionName>
<packagings>
<packaging>jar</packaging>
</packagings>
<goals>
<goal>process-classes</goal>
<goal>org.codehaus.mojo:exec-maven-plugin:1.5.0:exec</goal>
</goals>
<properties>
<exec.args>-classpath %classpath com.bytesw.bytebot.BytebotApplication -Djasypt.encryptor.password=179CD78D24F9BC63D6E677272D1A7 -Xms256M -Xmx512M</exec.args>
<exec.executable>java</exec.executable>
</properties>
</action>
</actions>
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action>
<actionName>CUSTOM-clean install no test</actionName>
<displayName>clean install no test</displayName>
<goals>
<goal>clean</goal>
<goal>install</goal>
</goals>
<properties>
<skipTests>true</skipTests>
<dockerfile.skip>true</dockerfile.skip>
</properties>
</action>
<action>
<actionName>CUSTOM-basic cobertura</actionName>
<displayName>basic cobertura</displayName>
<goals>
<goal>cobertura:cobertura</goal>
</goals>
</action>
</actions>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.bytesw.bytebot</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>bytebot-service</artifactId>
<version>1.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<xdf.version>3.4.0</xdf.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<camel.version>2.22.0</camel.version>
<mainclass>com.bytesw.bytebot.BytebotApplication</mainclass>
<docker.image.prefix>192.168.27.148:5000/bytesw</docker.image.prefix>
<docker.image.name>bytebot-service</docker.image.name>
<packaging.type>war</packaging.type>
<json-path.version>2.4.0</json-path.version>
<org.everit.json.schema.version>1.5.1</org.everit.json.schema.version>
<jacoco.version>0.8.5</jacoco.version>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
<sonar.exclusions></sonar.exclusions>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>com.bytesw.xdf</groupId>
<artifactId>byteXDF4Java-coreweb</artifactId>
<version>${xdf.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>7.37.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${json-path.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>${org.everit.json.schema.version}</version>
</dependency>
<!-- Inicio de Lock para scheduling -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>4.30.0</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
<version>4.30.0</version>
</dependency>
<!-- Fin de Lock para scheduling -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- camel -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-ftp</artifactId>
<version>${camel.version}</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.cobertura</groupId>
<artifactId>cobertura</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jparams</groupId>
<artifactId>to-string-verifier</artifactId>
<version>1.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.18</version>
</dependency>
<dependency>
<groupId>org.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<version>1.3.3</version>
</dependency>
<!-- websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
<version>0.37</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<!-- fin de web sockets -->
<!-- ibatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.twilio.sdk/twilio -->
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>8.22.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.12.129</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.2.5.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.codehaus.mojo</groupId>-->
<!-- <artifactId>cobertura-maven-plugin</artifactId>-->
<!-- <version>2.7</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>cobertura</id>-->
<!-- <phase>test</phase>-->
<!-- <goals>-->
<!-- <goal>cobertura</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <formats>-->
<!-- <format>xml</format>-->
<!-- <format>html</format>-->
<!-- </formats>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<runOrder>random</runOrder>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<phase>test-compile</phase>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>docker</id>
<activation>
<property>
<name>docker</name>
</property>
</activation>
<properties>
<packaging.type>jar</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-spi</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-core</artifactId>
<version>1.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>dockerfile-maven-plugin</artifactId>
<version>1.3.6</version>
<executions>
<execution>
<id>default</id>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
<configuration>
<repository>${docker.image.prefix}/${docker.image.name}</repository>
<tag>${project.version}</tag>
<buildArgs>
<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>default</id>
<activation>
<property>
<name>default</name>
</property>
</activation>
<properties>
<packaging.type>jar</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceExcludes>**/jboss-web.xml</warSourceExcludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>weblogic</id>
<activation>
<property>
<name>weblogic</name>
</property>
</activation>
<properties>
<packaging.type>war</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.16</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceExcludes>**/jboss-web.xml</warSourceExcludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>nexus</id>
<activation>
<property>
<name>nexus</name>
</property>
</activation>
<properties>
<packaging.type>jar</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.16</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
<!-- SOPORTE AL XDF -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.bytesw.xdf</groupId>
<artifactId>byteXDF4Java-arq</artifactId>
<version>${xdf.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<distributionManagement>
<repository>
<id>maven-releases</id>
<name>Repository Release</name>
<url>http://byteswpe-nexus.tbs.com:8081/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>maven-snapshots</id>
<name>RepositoryProxy</name>
<url>http://byteswpe-nexus.tbs.com:8081/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
package com.bytesw.bytebot;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication(scanBasePackages = "com.bytesw")
@ImportResource("classpath:application-config.xml")
@EnableCaching
@EnableAspectJAutoProxy
@EnableFeignClients(basePackages = "com.bytesw")
@EnableBatchProcessing
public class BytebotApplication {
public static void main(String[] args) {
SpringApplication.run(BytebotApplication.class, args);
}
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class ActionSummaryByGoalBean implements Serializable {
@Expose
private String goal;
@Expose
private BigInteger count;
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Agent;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter @Setter
@ToString
public class AgentBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String description;
@Expose
private String version;
@Expose
private String status;
@Expose
private Long countryId;
@Expose
private String countryName;
@Expose
private String timezone;
@Expose
private String avatar;
@Expose
private String language;
@Expose
private String type;
@Expose
private int period;
@Expose
private List<DeploymentChannelBean> deploymentChannels;
@Expose
private List<FrequentQuestionBean> frequentQuestions;
public static AgentBean miniClone(Agent agent) {
AgentBean bean = new AgentBean();
bean.setId(agent.getId());
bean.setName(agent.getName());
bean.setVersion(agent.getVersion());
bean.setStatus(agent.getStatus().getName());
bean.setTimezone(agent.getTimezone());
bean.setAvatar(agent.getAvatar());
if (agent.getCountry() != null) {
bean.setCountryName(agent.getCountry().getName());
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigDecimal;
@Getter @Setter
public class AverageBean implements Serializable {
@Expose
private BigDecimal firstResponseAverage;
@Expose
private BigDecimal sessionAverage;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter @Setter
public class BdcControlBean implements Serializable {
@Expose private Long id;
@Expose private String uuid;
@Expose private String fileName;
@Expose private String status;
@Expose private String user;
@Expose private String date;
@Expose private Long fileId;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterBean implements Serializable {
@Expose private BigInteger id;
@Expose private long version;
@Expose private String key;
@Expose private String description;
@Expose private String required;
@Expose private String defaultValue;
@Expose private String currentValue;
@Expose private OffsetDateTime dateFrom;
@Expose private OffsetDateTime dateApplyFrom;
@Expose private String programmedValue;
@Expose private BigInteger currentConfigurationId;
@Expose private BigInteger programmedConfigurationId;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterConfigurationBean implements Serializable {
@Expose private BigInteger id;
@Expose private long version;
@Expose private OffsetDateTime from;
@Expose private OffsetDateTime to;
@Expose private String value;
@Expose private String programmedValue;
@Expose private BusinessParameterBean businessParameters;
@Expose private BigInteger currentConfigurationId;
@Expose private BigInteger programmedConfigurationId;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterValueBean implements Serializable {
@Expose private String key;
@Expose private String description;
@Expose private boolean required;
@Expose private String defaultValue;
@Expose private String value;
@Expose private OffsetDateTime from;
@Expose private BigInteger id;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
@Getter
@Setter
public class CalendarBean implements Serializable {
@Expose
private String id;
@Expose
private long version;
@Expose
private String name;
//@TODO: Revisar List<WeekScheduler> weekSchedulerList de la clase Calendar
@Expose
private List<WeekSchedulerBean> weekSchedulerBeanList;
@Expose
private List<CalendarExceptionBean> calendarExceptionBeanList;
}
\ No newline at end of file
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@Getter
@Setter
public class CalendarExceptionBean {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private String description;
@Expose
private CalendarBean calendar;
@Expose
private String calendarExceptionType;
//Frecuencia
@Expose
private String frequencyType;
//annualCalendar y UniqueWeekly
@Expose
private int month;
@Expose
private int dayOfMonth;
@Expose
private int weekOfMonth;
@Expose
private int dayOfWeek;
//UniqueCalendar
@Expose
private LocalDate date;
//rangeCalendar
@Expose
private OffsetDateTime from;
@Expose
private OffsetDateTime to;
@Expose
private boolean delete;
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class ChannelBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String image;
@Expose
private List<ChannelParamBean> parameters;
@Expose
private String suggestTitle;
@Expose
private String suggestDetail;
public static ChannelBean clone(Channel channel) {
ChannelBean bean = new ChannelBean();
bean.setId(channel.getId());
bean.setName(channel.getName());
bean.setImage(channel.getImage());
bean.setParameters(new ArrayList<>());
bean.setSuggestTitle(channel.getSuggestTitle());
bean.setSuggestDetail(channel.getSuggestDetail());
if (channel.getParameters() != null) {
Collections.sort(channel.getParameters(), (o1, o2) -> o1.getOrder() - o2.getOrder());
for (ChannelParam param : channel.getParameters()) {
bean.getParameters().add(ChannelParamBean.clone(param));
}
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.ChannelParam;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class ChannelParamBean {
@Expose
private String name;
@Expose
private String label;
@Expose
private Integer maxlength;
@Expose
private String type;
@Expose
private Boolean required;
@Expose
private Integer order;
@Expose
private String traductions;
@Expose
private String regex;
public static ChannelParamBean clone(ChannelParam channelParam) {
ChannelParamBean bean = new ChannelParamBean();
bean.setName(channelParam.getName());
bean.setLabel(channelParam.getLabel());
bean.setMaxlength(channelParam.getMaxlength());
bean.setRequired(channelParam.isRequired());
bean.setType(channelParam.getType());
bean.setOrder(channelParam.getOrder());
bean.setTraductions(channelParam.getTraductions());
bean.setRegex(channelParam.getRegex());
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Country;
import com.bytesw.bytebot.model.Timezone;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class CountryBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private List<String> timezones;
public static CountryBean clone(Country country) {
CountryBean bean = new CountryBean();
bean.setId(country.getId());
bean.setName(country.getName());
bean.setTimezones(new ArrayList<>());
if (country.getTimezones() != null) {
for (Timezone timezone : country.getTimezones()) {
bean.getTimezones().add(timezone.getTimezone());
}
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class DeploymentChannelBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String status;
@Expose
private Long channelId;
@Expose
private String channelName;
@Expose
private List<DeploymentChannelParamValueBean> parameters;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class DeploymentChannelParamValueBean {
@Expose
private Long id;
@Expose
private String channelParamName;
@Expose
private String value;
@Expose
private Long agen_id;
@Expose
private String channel;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
@Setter
@ToString
public class FrequentQuestionBean {
@Expose
private Long id;
@Expose
private String uuid;
@Expose
private String filename;
@Expose
private String description;
@Expose
private String status;
@Expose
private String user;
@Expose
private String uploadDate;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class MessageByIntentBean implements Serializable {
@Expose
private String identifier;
@Expose
private BigInteger count;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class ProcessETLBean implements Serializable {
@Expose
private int id;
@Expose
private String name;
@Expose
private long version;
}
package com.bytesw.bytebot.bean;
import lombok.Getter;
import lombok.Setter;
import java.time.OffsetDateTime;
@Getter @Setter
public class RangeBean {
private OffsetDateTime startDate;
private OffsetDateTime endDate;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter
@Setter
public class SchedulerTaskBean implements Serializable {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private String description;
@Expose
private String internals;
@Expose
private String cronExpression;
@Expose
private String stringParameters;
@Expose
private Integer etlId;
@Expose
private String calendarID;
@Expose
private String calendarName;
// @Expose
// private int idEtl;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class SessionByClientBean implements Serializable {
@Expose
private BigInteger user_id;
@Expose
private String sender_id;
@Expose
private BigInteger count;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@Getter @Setter
public class SummaryBean implements Serializable {
@Expose
private BigInteger value;
@Expose
private BigDecimal percent;
@Expose
private List<ArrayList<Object>> history;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class SummaryMessageByIntentBean implements Serializable {
@Expose
private Long id;
@Expose
private String identifier;
@Expose
private BigInteger count;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class SummaryMessageBySentenceBean implements Serializable {
@Expose
private Long id;
@Expose
private String identifier;
@Expose
private String sentence;
@Expose
private BigInteger count;
@Expose
private BigInteger customerCount;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
@Getter
@Setter
public class WeekSchedulerBean {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private int dayOfWeek;
@Expose
private OffsetTime from;
@Expose
private OffsetTime to;
@Expose
private String calendarID;
@Expose
private String calendarName;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.AgencyAgent;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AgentBean implements Serializable {
@Expose
private Integer id;
@Expose
private String name;
@Expose
private String lastname;
@Expose
private String email;
@Expose
private String details;
public static AgentBean miniClone(AgencyAgent agent) {
return new AgentBean(agent.getId(),
agent.getName(),
agent.getLastname(),
agent.getUser().getEmail(),
agent.getDetails());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Aircraft;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AircraftBean implements Serializable {
@Expose
private Integer value;
@Expose
private String label;
public static AircraftBean miniClone(Aircraft aircraft) {
return new AircraftBean(aircraft.getId(), aircraft.getName());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Airline;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AirlineBean implements Serializable {
@Expose
private Integer value;
@Expose
private String label;
public static AirlineBean miniClone(Airline airline) {
return new AirlineBean(airline.getId(), airline.getName());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Airport;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AirportBean implements Serializable {
@Expose
private Integer value;
@Expose
private String label;
public static AirportBean miniClone(Airport airport) {
return new AirportBean(airport.getId(), airport.getName());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Cost;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Getter
@Setter
public class CostBean implements Serializable {
@Expose
private Integer id;
@Expose
private String departureDate;
@Expose
private String arrivalDate;
@Expose
private Double amount;
public static CostBean miniClone(Cost cost) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
CostBean costBean = new CostBean();
costBean.setId(cost.getId());
costBean.setArrivalDate(cost.getArrivalDate().format(formatter));
costBean.setDepartureDate(cost.getDepartureDate().format(formatter));
costBean.setAmount(cost.getAmount());
return costBean;
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.*;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
public class FlightBean implements Serializable {
@Expose
private Integer id;
@Expose
private Integer airlineId;
@Expose
private String airlineName;
@Expose
private Integer aircraftId;
@Expose
private String aircraftName;
@Expose
private Integer airportOriginId;
@Expose
private String airportOriginName;
@Expose
private Integer airportDestinationId;
@Expose
private String airportDestinationName;
@Expose
private String departureDate;
@Expose
private String arrivalDate;
@Expose
private List<ScaleBean> scales;
@Expose
private List<CostBean> costs;
public static FlightBean miniClone(Flight flight) {
FlightBean flightBean = new FlightBean();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
flightBean.setId(flight.getId());
flightBean.setAirlineId(flight.getAirline().getId());
flightBean.setAirlineName(flight.getAirline().getName());
flightBean.setAircraftId(flight.getAircraft().getId());
flightBean.setAircraftName(flight.getAircraft().getName());
flightBean.setAirportOriginId(flight.getAirportOrigin().getId());
flightBean.setAirportOriginName(flight.getAirportOrigin().getName());
flightBean.setAirportDestinationId(flight.getAirportDestination().getId());
flightBean.setAirportDestinationName(flight.getAirportDestination().getName());
flightBean.setDepartureDate(flight.getDepartureDate().format(formatter));
flightBean.setArrivalDate(flight.getArrivalDate().format(formatter));
List<Scale> scales = flight.getScales();
List<ScaleBean> scalesBean = new ArrayList<>();
for (Scale scale : scales) {
scalesBean.add(ScaleBean.miniClone(scale));
}
List<Cost> costs = flight.getCosts();
List<CostBean> costsBean = new ArrayList<>();
for (Cost cost : costs) {
costsBean.add(CostBean.miniClone(cost));
}
flightBean.setScales(scalesBean);
flightBean.setCosts(costsBean);
return flightBean;
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Cost;
import com.bytesw.bytebot.model.agency.Flight;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
public class FlightSearchBean {
@Expose
private Integer id;
@Expose
private String airline;
@Expose
private String aircraft;
@Expose
private String flightType;
@Expose
private String airportOrigin;
@Expose
private String airportDestination;
@Expose
private String departureDate;
@Expose
private String arrivalDate;
@Expose
private Double amount;
@Expose
private List<ScaleBean> scales;
public static FlightSearchBean miniClone(Flight flight, LocalDateTime date) {
FlightSearchBean searchBean = new FlightSearchBean();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime departureDate = LocalDateTime.of
(date.getYear(), date.getMonth(), date.getDayOfMonth(), flight.getScales().get(0).getDepartureDate().getHour(),
flight.getScales().get(0).getDepartureDate().getMinute(), flight.getScales().get(0).getDepartureDate().getSecond());
LocalDateTime arrivalDate = departureDate;
Duration duration = Duration.between(flight.getScales().get(0).getDepartureDate(), flight.getScales().get(flight.getScales().size() - 1).getArrivalDate());
arrivalDate = arrivalDate.plus(duration);
searchBean.setId(flight.getId());
searchBean.setAirline(flight.getAirline().getName());
searchBean.setAircraft(flight.getAircraft().getName());
searchBean.setFlightType(flight.getScales().size() > 1 ? "With scales" : "Direct");
searchBean.setDepartureDate(departureDate.format(formatter));
searchBean.setAirportOrigin(flight.getAirportOrigin().getName());
searchBean.setAirportDestination(flight.getAirportDestination().getName());
searchBean.setArrivalDate(arrivalDate.format(formatter));
searchBean.setAmount(getAmount(flight.getCosts(), date));
searchBean.setScales(flight.getScales().stream().map(ScaleBean::miniClone).collect(Collectors.toList()));
return searchBean;
}
public static Double getAmount(List<Cost> costs, LocalDateTime date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
for (Cost cost : costs) {
LocalDateTime departureDate = cost.getDepartureDate();
LocalDateTime arrivalDate = cost.getArrivalDate();
if ((date.isAfter(departureDate) && date.isBefore(arrivalDate))
|| date.isEqual(departureDate))
return cost.getAmount();
}
throw new RuntimeException(String.format("Cost not found for %s", date.format(formatter)));
}
}
package com.bytesw.bytebot.bean.agency;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class FlightSearchRequestBean {
@Expose
private Integer airportOrigin;
@Expose
private Integer airportDestination;
@Expose
private String travelDate;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Passenger;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Column;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class PassengerBean implements Serializable {
@Expose
private Integer id;
@Expose
private String name;
@Expose
private String lastname;
@Expose
private String email;
@Expose
private String role;
@Expose
private String phone;
@Expose
private String country;
@Expose
private String city;
@Expose
private String address;
public static PassengerBean miniClone(Passenger passenger) {
return new PassengerBean(passenger.getId(),
passenger.getName(),
passenger.getLastname(),
passenger.getUser().getEmail(),
passenger.getUser().getRole().getName(),
passenger.getPhone(),
passenger.getCountry(),
passenger.getCity(),
passenger.getAddress());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Passenger;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PassengerMapBean {
@Expose
private Integer value;
@Expose
private String label;
public static PassengerMapBean miniClone(Passenger passenger) {
PassengerMapBean passengerMapBean = new PassengerMapBean();
passengerMapBean.setValue(passenger.getId());
passengerMapBean.setLabel(String.format("%s %s", passenger.getName(), passenger.getLastname()));
return passengerMapBean;
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.enums.PaymentStatusEnum;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDate;
@Getter
@Setter
public class PaymentBean implements Serializable {
@Expose
private Integer id;
@Expose
private PaymentStatusEnum status;
@Expose
private Double amount;
@Expose
private LocalDate date;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Cost;
import com.bytesw.bytebot.model.agency.Reservation;
import com.bytesw.bytebot.model.agency.Scale;
import com.bytesw.bytebot.model.agency.enums.ReservationStatusEnum;
import com.bytesw.bytebot.model.agency.enums.TicketTypeEnum;
import com.bytesw.bytebot.model.agency.enums.TravelClassEnum;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
public class ReservationBean implements Serializable {
@Expose
private Integer id;
@Expose
private String passenger;
@Expose
private String airportOrigin;
@Expose
private Integer airportOriginId;
@Expose
private String airportDestination;
@Expose
private Integer airportDestinationId;
@Expose
private String departureDate;
@Expose
private Integer passengerId;
@Expose
private Integer agentId;
@Expose
private String ticketType;
@Expose
private String travelClass;
@Expose
private String status;
@Expose
private Double amount;
@Expose
private List<ScaleBean> scales;
@Expose
private Integer flightId;
@Expose
private FlightSearchBean flightSearchBean;
public static ReservationBean miniClone(Reservation reservation) {
ReservationBean reservationBean = new ReservationBean();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
reservationBean.setId(reservation.getId());
reservationBean.setPassenger(String.format("%s %s", reservation.getPassenger().getName(), reservation.getPassenger().getLastname()));
reservationBean.setPassengerId(reservation.getPassenger().getId());
reservationBean.setAirportOrigin(reservation.getFlight().getAirportOrigin().getName());
reservationBean.setAirportOriginId(reservation.getFlight().getAirportOrigin().getId());
reservationBean.setAirportDestination(reservation.getFlight().getAirportDestination().getName());
reservationBean.setAirportDestinationId(reservation.getFlight().getAirportDestination().getId());
reservationBean.setScales(getScalesBean(reservation.getFlight().getScales()));
reservationBean.setFlightId(reservation.getFlight().getId());
reservationBean.setDepartureDate(reservation.getDepartureDate().format(formatter));
reservationBean.setTicketType(reservation.getTicketType().getName());
reservationBean.setTravelClass(reservation.getTravelClass().getName());
reservationBean.setFlightSearchBean(FlightSearchBean.miniClone(reservation.getFlight(), reservation.getDepartureDate()));
if(reservation.getPayment() != null)
reservationBean.setAmount(reservation.getPayment().getAmount());
reservationBean.setStatus(reservation.getStatus().getName());
reservationBean.setAgentId(reservation.getAgencyAgent().getId());
return reservationBean;
}
private static List<ScaleBean> getScalesBean(List<Scale> scales) {
return scales.stream().map(ScaleBean::miniClone)
.collect(Collectors.toList());
}
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Airport;
import com.bytesw.bytebot.model.agency.Flight;
import com.bytesw.bytebot.model.agency.Scale;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Getter
@Setter
public class ScaleBean implements Serializable {
@Expose
private Integer id;
@Expose
private Integer flightId;
@Expose
private Integer airportOriginId;
@Expose
private String airportOriginName;
@Expose
private Integer airportDestinationId;
@Expose
private String airportDestinationName;
@Expose
private String departureDate;
@Expose
private String arrivalDate;
public static ScaleBean miniClone(Scale scale) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
ScaleBean scaleBean = new ScaleBean();
scaleBean.setId(scale.getId());
scaleBean.setFlightId(scale.getFlight().getId());
scaleBean.setAirportOriginId(scale.getAirportOrigin().getId());
scaleBean.setAirportOriginName(scale.getAirportOrigin().getName());
scaleBean.setAirportDestinationId(scale.getAirportDestination().getId());
scaleBean.setAirportDestinationName(scale.getAirportDestination().getName());
scaleBean.setDepartureDate(scale.getDepartureDate().format(formatter));
scaleBean.setArrivalDate(scale.getArrivalDate().format(formatter));
return scaleBean;
}
}
package com.bytesw.bytebot.bean.agency;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SignInBean {
@Expose
private String email;
@Expose
private String password;
}
package com.bytesw.bytebot.bean.agency;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SignUpBean {
@Expose
private String name;
@Expose
private String lastname;
@Expose
private String role;
@Expose
private String email;
@Expose
private String password;
@Expose
private String details;
@Expose
private String country;
@Expose
private String city;
@Expose
private String phone;
@Expose
private String address;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Supervisor;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class SupervisorBean {
@Expose
private Integer id;
@Expose
private String name;
@Expose
private String lastname;
@Expose
private String email;
@Expose
private String details;
public static SupervisorBean miniClone(Supervisor supervisor) {
return new SupervisorBean(supervisor.getId(),
supervisor.getName(),
supervisor.getLastname(),
supervisor.getUser().getEmail(),
supervisor.getDetails());
}
}
package com.bytesw.bytebot.bean.agency;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UpdatePasswordBean {
@Expose
private String password;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.Reservation;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UpdateReservationStatus {
@Expose
private String status;
}
package com.bytesw.bytebot.bean.agency;
import com.bytesw.bytebot.model.agency.User;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserBean {
@Expose
private Integer id;
@Expose
private String email;
@Expose
private String role;
public static UserBean miniClone(User user) {
return new UserBean(
user.getId(),
user.getEmail(),
user.getRole().getName());
}
}
package com.bytesw.bytebot.config;
import com.bytesw.bytebot.routes.SFTPRoute;
import lombok.extern.log4j.Log4j2;
import org.apache.camel.CamelContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
@Log4j2
public class CamelConfig {
@Autowired
private CamelContext camelContext;
@Autowired
private SFTPRoute sftpRoute;
@PostConstruct
public void addBuilder() throws Exception {
camelContext.addRoutes(sftpRoute);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.etl.beans.ActionBean;
import com.bytesw.bytebot.service.ActionService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/actions")
@ProgramSecurity("ACTIONS")
@Log4j2
public class ActionController extends XDFController<ActionBean, Long> {
public ActionController(ActionService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.controller.bean.ResponseController;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.service.*;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Log4j2
@RestController
@RequestMapping("/service/agent")
@ProgramSecurity("conversational_agent")
public class AgentController {
@Autowired
private AgentService agentService;
@Autowired
private FileManagementService fileManagementService;
@Autowired
private GsonBuilder gsonBuilder;
@Autowired
private OrquestadorService orquestadorService;
@PostMapping(value = "/page")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> paginationConversationalAgent(@RequestBody Pagination<AgentBean> pagination) {
HttpStatus hs = HttpStatus.OK;
try {
agentService.searchByPagination(pagination);
return new ResponseEntity<>(gsonBuilder.create().toJson(pagination), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getConversartionalAgentById(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getAgent(id)), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PutMapping(value = "/")
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> createConversationalAgent(@RequestBody AgentBean agentBean) {
HttpStatus hs = HttpStatus.OK;
try {
agentService.save(agentBean);
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.insert.success", hs.value())), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PutMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> updateConversationalAgent(@PathVariable("id") Long id,
@RequestBody AgentBean agentBean) {
HttpStatus hs = HttpStatus.OK;
try {
if (id != null) {
agentService.save(agentBean);
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.update.success", hs.value())), hs);
} else {
hs = HttpStatus.UNAUTHORIZED;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.update.error", hs.value())), hs);
}
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'delete')")
public ResponseEntity<String> deleteConversationalAgent(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
HttpStatus hs = HttpStatus.OK;
try {
if (id != null) {
boolean deleteValid = agentService.delete(id);
if (deleteValid) {
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.success", hs.value())), hs);
} else {
// hs = HttpStatus.FAILED_DEPENDENCY;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.error.integrity", hs.FAILED_DEPENDENCY.value())), hs);
}
} else {
hs = HttpStatus.UNAUTHORIZED;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.error.unauthtorized", hs.value())), hs);
}
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/countries")
public ResponseEntity<String> getCountries() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getCountries()), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/channels")
public ResponseEntity<String> getChannels() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getChannels()), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PostMapping("/file-upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, Principal principal) {
Gson gson = gsonBuilder.create();
try {
String uuid = UUID.randomUUID().toString();
FileValidationResponse response = orquestadorService.executeGenerateBCD(uuid, file);
response.setUser(principal != null ? principal.getName() : null);
return new ResponseEntity<>(gson.toJson(response), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping("/file-upload/{uuid}")
public ResponseEntity<String> uploadFile(@PathVariable("uuid") String uuid, Principal principal) {
Gson gson = gsonBuilder.create();
try {
FileValidationResponse response = orquestadorService.retry(uuid);
response.setUser(principal != null ? principal.getName() : null);
return new ResponseEntity<>(gson.toJson(response), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/file-upload/{uuid}")
public ResponseEntity<String> deleteBdc(@ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) {
Gson gson = gsonBuilder.create();
Map<String, String> resp = new HashMap<>();
try {
orquestadorService.deleteBcd(uuid);
resp.put("message", "OK");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.OK);
} catch (Exception e) {
resp.put("message", "ERROR");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.OK);
}
}
@GetMapping("/synchronize/{id}")
public ResponseEntity<String> synchronizeFiles(@PathVariable("id") Long id,
@RequestParam("user") String user) {
Gson gson = new GsonBuilder().create();
try {
agentService.synchronizeFiles(id, user);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = "/")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getAgentAll() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getAgentAll()), hs);
} catch (Exception e) {
String info = "Error detectado al obtener informacion";
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(info), hs);
}
}
}
package com.bytesw.bytebot.controller;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AppSettingsController {
@Value("${application.logo.type:png}")
private String type;
@Value("classpath:logo.txt")
Resource resourceFile;
@Value("${application.show-side-bar:true}")
private boolean showSideBar;
@Autowired
private GsonBuilder gsonBuilder;
@GetMapping("/settings/information")
public ResponseEntity<String> getAppSettings() {
HttpStatus hs = HttpStatus.OK;
Map<String, Object> appSettings = new HashMap<>();
appSettings.put("tipo", type);
appSettings.put("logoBase64", getDefaultLogo());
//you
// appSettings.put("showSideBar", true);
return new ResponseEntity<>(gsonBuilder.disableHtmlEscaping().create().toJson(appSettings), hs);
}
public String getDefaultLogo() {
String str = "";
StringBuffer buf = new StringBuffer();
InputStream is = null;
try {
is = resourceFile.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
if (is != null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "" );
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try { is.close(); } catch (Throwable ignore) {}
}
return buf.toString();
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.BdcControlBean;
import com.bytesw.bytebot.service.BcdControlService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/bcdControl")
@ProgramSecurity("BCDCONTROL")
@Log4j2
public class BdcControlController extends XDFController<BdcControlBean, Long> {
public BdcControlController(BcdControlService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.BusinessParameterConfigurationService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigInteger;
@RestController()
@RequestMapping("/service/settings/business-parameter-configuration")
@ProgramSecurity("BUSINESS_PARAMETERS_CONFIGURATION")
@Log4j2
public class BusinessParameterConfigurationController extends XDFController<BusinessParameterConfigurationBean, BigInteger> {
public BusinessParameterConfigurationController(BusinessParameterConfigurationService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.BusinessParameterBean;
import com.bytesw.bytebot.bean.BusinessParameterValueBean;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.exception.ReferentialIntegrityException;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.List;
@RestController()
@RequestMapping("/service/settings/business-parameter")
@ProgramSecurity("BUSINESS-PARAMETERS")
@Log4j2
public class BusinessParameterController extends XDFController<BusinessParameterBean, BigInteger> {
@Autowired BusinessParameterService service;
@Autowired
protected GsonBuilder gsonBuilder;
public BusinessParameterController(BusinessParameterService service) {
super(service);
}
@RequestMapping(value = {"/value/{key}"}, method = {RequestMethod.PUT})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 404,message = "Not Found"),
@ApiResponse(code = 409,message = "Already exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<Void> addNewAddValue(
@ApiParam(value = "key", required = true) @PathVariable("key") String key,
@ApiParam(value = "value", required = true) @RequestParam("value") String value,
@ApiParam(value = "from", required = false) @RequestParam("from") String fromString) {
OffsetDateTime from = OffsetDateTime.parse(fromString);
this.service.addValue(key, value, from);
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(value = {"/create"}, method = {RequestMethod.POST})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 409, message = "Already Exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> createWithValue(@RequestBody BusinessParameterValueBean bean, HttpServletRequest req) {
Gson gson = gsonBuilder.create();
bean = this.service.createWithValue(bean);
return new ResponseEntity(gson.toJson(bean), HttpStatus.OK);
}
@RequestMapping(value = {"/current/{key}"}, method = {RequestMethod.GET})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 404,message = "Not Found"),
@ApiResponse(code = 409, message = "Already Exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> getCurrentValue(@ApiParam(value = "key", required = true) @PathVariable("key") String key) {
Gson gson = gsonBuilder.create();
// String value = this.service.getCurrentValue(key);
String value = this.service.getCurrentValueParameterByKey(key);
return new ResponseEntity(gson.toJson(value), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.GET},
value = {"/parameter-value/{key}"}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getFeaturesTemplate(@PathVariable("key") String key) {
String featuresTemplate = ((BusinessParameterService)this.service).getCurrentValueParameterByKey(key);
return new ResponseEntity(this.gson.toJson(featuresTemplate), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.POST},
value = {"/page"}
)
@ResponseBody
@Override
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<BusinessParameterBean> pagination) {
if (pagination.getFilterExpression()!=null) {
if (pagination.getFilterExpression().contains("(required==Y)")) {
pagination.setFilterExpression(pagination.getFilterExpression().replace("(required==Y)", "(required==true)"));
}
}
this.service.searchByPagination(pagination);
return new ResponseEntity(this.gson.toJson(pagination), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/{id}"},
method = {RequestMethod.DELETE}
)
@PreAuthorize("hasPermission(this, 'delete')")
public ResponseEntity<String> delete(@PathVariable("id") BigInteger id, HttpServletRequest req) {
this.service.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(
value = {"/{id}"},
method = {RequestMethod.PUT}
)
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> update(@PathVariable("id") BigInteger id, @RequestBody BusinessParameterBean bean, HttpServletRequest req) {
try {
if (this.service.validateKey(bean)) {
throw new ReferentialIntegrityException("Ya existe un identificador con el mismo nombre");
} else {
this.service.update(bean, id);
}
} catch (ObjectOptimisticLockingFailureException var6) {
BusinessParameterBean actualBean = this.service.getById(id);
return new ResponseEntity(this.gson.toJson(actualBean), HttpStatus.CONFLICT);
}
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(
value = {"/"},
method = {RequestMethod.POST}
)
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 409,
message = "Already Exists"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> create(@RequestBody BusinessParameterBean bean, HttpServletRequest req) {
if (this.service.validateKey(bean)) {
throw new ReferentialIntegrityException("Ya existe un identificador con el mismo nombre");
} else {
bean = this.service.createBP(bean);
return new ResponseEntity(this.gson.toJson(bean), HttpStatus.OK);
}
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/searchKey/{busnessKey}"},
method = {RequestMethod.GET}
)
@PreAuthorize("hasPermission(this, 'showHistory')")
public ResponseEntity<String> findByKey(@PathVariable("busnessKey") BigInteger busnessKey, HttpServletRequest req) {
List<BusinessParameterConfigurationBean> bean = this.service.getConfigurationParametersList(busnessKey);
return new ResponseEntity(this.gson.toJson(bean), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.bytebot.service.CalendarService;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/calendar")
@ProgramSecurity("CALENDAR")
@Log4j2
public class CalendarController extends XDFController<CalendarBean, String> {
public CalendarController(CalendarService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.service.CalendarExceptionService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
@RestController()
@RequestMapping("/service/settings/calendar-exception")
@ProgramSecurity("CALENDAR-EXCEPTION")
@Log4j2
public class CalendarExceptionController extends XDFController<CalendarExceptionBean, BigInteger> {
@Autowired
CalendarExceptionService service;
public CalendarExceptionController(CalendarExceptionService service) {
super(service);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/find-by-calendar-id"},
method = {RequestMethod.POST}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getCalendarExceptionbyID(@RequestBody Map<String, String> parametersCalendar, HttpServletRequest req) {
List<CalendarExceptionBean> calendarExceptionBeanList = this.service.getCalendarExceptionbyID(parametersCalendar);
return new ResponseEntity(this.gson.toJson(calendarExceptionBeanList), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean;
import com.bytesw.bytebot.service.dashboard.CustomerInteractionDashboardService;
import com.bytesw.bytebot.service.dashboard.OperativeDashboardService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/dashboard")
public class DashboardController {
@Autowired
private OperativeDashboardService operativeDashboardService;
@Autowired
private CustomerInteractionDashboardService customerInteractionDashboardService;
@Autowired
private Gson gson;
@PostMapping("/operative")
public ResponseEntity<String> getOperativeInfo(@RequestBody Map<String, Object> body) {
Map<String, Object> info = operativeDashboardService.generateInfo(body);
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
@PostMapping("/operative/sentence-by-intent/page")
public ResponseEntity<String> getSentenceByIntentPage(@RequestBody Pagination<SummaryMessageBySentenceBean> pagination) {
customerInteractionDashboardService.getSummaryBySentencePagination(pagination);
return new ResponseEntity<>(gson.toJson(pagination), HttpStatus.OK);
}
@PostMapping("/customer-interaction")
public ResponseEntity<String> getCustomerInteractionInfo(@RequestBody Map<String, Object> body) {
Map<String, Object> info = customerInteractionDashboardService.generateInfo(body);
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
@PostMapping("/customer-interaction/message-by-intent/page")
public ResponseEntity<String> getMessageByIntentPage(@RequestBody Pagination<SummaryMessageBySentenceBean> pagination) {
customerInteractionDashboardService.getSummaryByIntentAndSentencePagination(pagination);
return new ResponseEntity<>(gson.toJson(pagination), HttpStatus.OK);
}
@GetMapping("/test")
public ResponseEntity<String> getTest() {
Map<String, Object> data = customerInteractionDashboardService.generateInfo(new HashMap<>());
return new ResponseEntity<>(gson.toJson(data), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.GoalService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.google.gson.GsonBuilder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController()
@RequestMapping("/service/settings/goal")
@ProgramSecurity("GOAL")
@Log4j2
public class GoalController extends XDFController<Map, Long> {
@Autowired
private GoalService goalService;
@Autowired
private GsonBuilder gsonBuilder;
public GoalController(GoalService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.etl.beans.GoalForActionsBean;
import com.bytesw.bytebot.service.GoalForActionService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/goal-for-actions")
@ProgramSecurity("GOALFORACTIONS")
@Log4j2
public class GoalForActionController extends XDFController<GoalForActionsBean, Long> {
public GoalForActionController(GoalForActionService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.ProcessETLBean;
import com.bytesw.bytebot.service.CalendarService;
import com.bytesw.bytebot.service.ProcessETLService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/ProcessETL")
@ProgramSecurity("PROCESSETL")
@Log4j2
public class ProcessETLController extends XDFController<ProcessETLBean, Integer> {
public ProcessETLController(ProcessETLService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.NotFoundException;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import com.twilio.exception.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.gson.Gson;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@Log4j2
@RestController
@RequestMapping("/providers")
public class ProviderController {
@Autowired
private TwilioService twilioService;
@Autowired
private Gson gson;
@ApiResponses(value={
@ApiResponse(code=200, message = "OK"),
@ApiResponse(code=400, message = "Bad Request. Datos de entrada inválido"),
@ApiResponse(code=401, message = "Unauthorized. Credenciales erróneas"),
@ApiResponse(code=404, message = "Not Found. Recursos no encontrados")
})
@RequestMapping(value="/twilio/messages/{sid_message}",method = {RequestMethod.DELETE})
public ResponseEntity<String> deleteSensibleInfo(@ApiParam(value="sid_message",required = true) @PathVariable("sid_message") String sid_message,
@ApiParam(value = "agent_id: Agente a cual eliminar su data sensible\n{\"agent_id\":1}",
example = "{agent_id:1}",required = true) @NotNull @RequestBody(required = false) Map<String,Object> body){
Map<String,Object> info = new HashMap<>();
try {
if (body == null) {
log.info("Body Input Inválido");
throw new ClassCastException("Input inválido");
}
info = twilioService.generateInfo(sid_message, body);
}catch (ClassCastException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}catch(NotFoundException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
}catch (AuthenticationException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.UNAUTHORIZED);
}catch (InternalError e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.SchedulerTaskBean;
import com.bytesw.bytebot.service.SchedulerTaskService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@RestController()
@RequestMapping("/service/settings/scheduler-task")
@ProgramSecurity("SCHEDULER-TASK")
@Log4j2
public class SchedulerTaskController extends XDFController<SchedulerTaskBean, BigInteger> {
public SchedulerTaskController(SchedulerTaskService service) {
super(service);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.POST},
value = {"/page"}
)
@ResponseBody
@Override
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<SchedulerTaskBean> pagination) {
if (!Objects.isNull(pagination.getFilterExpression()) && !pagination.getFilterExpression().isEmpty()) {
String filterExpression = pagination.getFilterExpression();
if (filterExpression.contains("(internals==Y)")) {
filterExpression = filterExpression.replace("(internals==Y)", "(internals==true)");
}
if (filterExpression.contains("calendarName")) {
filterExpression = filterExpression.replace("calendarName", "calendar.name");
}
pagination.setFilterExpression(filterExpression);
}
this.service.searchByPagination(pagination);
return new ResponseEntity(this.gson.toJson(pagination), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.GET},
value = {"/initial-data"}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getInitialData() {
Map<String, List> initialData = ((SchedulerTaskService) this.service).getInitialData();
return new ResponseEntity(this.gson.toJson(initialData), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.AgentBean;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.UpdatePasswordBean;
import com.bytesw.bytebot.service.agency.AgencyAgentService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/service/agents")
public class AgencyAgentController {
private final AgencyAgentService agentService;
public AgencyAgentController(AgencyAgentService agentService) {
this.agentService = agentService;
}
@GetMapping
public ResponseEntity<List<AgentBean>> getAll() {
return ResponseEntity.ok(agentService.getAll());
}
@PostMapping("/page")
public ResponseEntity<CustomPaginationBean<AgentBean>> getByPagination(@RequestBody CustomPaginationBean<AgentBean> pagination) {
return ResponseEntity.ok(agentService.getByPagination(pagination));
}
@GetMapping("{id}")
public ResponseEntity<AgentBean> getById(@PathVariable Integer id) {
return ResponseEntity.ok(agentService.getById(id));
}
@PostMapping("/create")
public ResponseEntity<AgentBean> create(@RequestBody SignUpBean up) {
return ResponseEntity.ok(agentService.create(up));
}
@PutMapping("/edit/{id}")
public ResponseEntity<AgentBean> update(@RequestBody UpdatePasswordBean passwordBean, @PathVariable Integer id) {
return ResponseEntity.ok(agentService.update(passwordBean, id));
}
@DeleteMapping("{id}")
public ResponseEntity<AgentBean> delete(@PathVariable Integer id) {
return ResponseEntity.ok(agentService.delete(id));
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.AircraftBean;
import com.bytesw.bytebot.service.agency.AircraftService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("service/aircrafts")
public class AircraftController {
private final AircraftService aircraftService;
public AircraftController(AircraftService aircraftService) {
this.aircraftService = aircraftService;
}
@GetMapping
public List<AircraftBean> getAll() {
return this.aircraftService.getAll();
}
@PostMapping
public AircraftBean save(@RequestBody AircraftBean bean) {
return this.aircraftService.save(bean);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.AirlineBean;
import com.bytesw.bytebot.service.agency.AirlinesService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController()
@RequestMapping("/service/airlines")
public class AirlineController {
private final AirlinesService airlinesService;
public AirlineController(AirlinesService airlinesService) {
this.airlinesService = airlinesService;
}
@GetMapping
public List<AirlineBean> getAll() {
return this.airlinesService.findAll();
}
@PostMapping
public AirlineBean save(@RequestBody AirlineBean bean) {
return this.airlinesService.save(bean);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.AirportBean;
import com.bytesw.bytebot.service.agency.AirportService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/service/airports")
public class AirportController {
private final AirportService airportService;
public AirportController(AirportService airportService) {
this.airportService = airportService;
}
@GetMapping
public List<AirportBean> getAll() {
return this.airportService.getAll();
}
@PostMapping
public AirportBean save(@RequestBody AirportBean airportBean) {
return this.airportService.save(airportBean);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.FlightBean;
import com.bytesw.bytebot.bean.agency.FlightSearchBean;
import com.bytesw.bytebot.bean.agency.FlightSearchRequestBean;
import com.bytesw.bytebot.service.agency.FlightService;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/service/flights")
public class FlightController extends XDFController<FlightBean, Integer> {
@Autowired
private GsonBuilder gsonBuilder;
@Autowired
private FlightService flightService;
public FlightController(FlightService service) {
super(service);
}
@Override
@PostMapping("/page")
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<FlightBean> pagination) {
return super.findAllByPagination(pagination);
}
@Override
@PostMapping("/create")
public ResponseEntity<String> create(@RequestBody FlightBean flightBean, HttpServletRequest req) {
Gson gson = gsonBuilder.create();
flightBean = (FlightBean) this.service.create(flightBean);
return new ResponseEntity(gson.toJson(flightBean), HttpStatus.CREATED);
}
@Override
@PutMapping("/edit/{id}")
public ResponseEntity<String> update(@PathVariable Integer id, @RequestBody FlightBean flightBean, HttpServletRequest req) {
FlightBean flightResponse = (FlightBean) service.update(flightBean, id);
return new ResponseEntity<>(gson.toJson(flightResponse), HttpStatus.OK);
}
@Override
@DeleteMapping("{id}")
public ResponseEntity<String> delete(@PathVariable Integer id, HttpServletRequest req) {
Gson gson = gsonBuilder.create();
Map<String, String> resp = new HashMap<>();
try {
service.delete(id);
resp.put("message", "OK");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.OK);
} catch (Exception e) {
resp.put("message", "ERROR");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
@GetMapping("{id}")
public ResponseEntity<String> findOne(@PathVariable Integer id, HttpServletRequest req) {
FlightBean flightBean = (FlightBean) service.getById(id);
return new ResponseEntity(gson.toJson(flightBean), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.xdf.annotation.ProgramSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/api/hello")
public class HelloWorldController {
@GetMapping
public String sayHello() {
return "Hello world!";
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.PassengerBean;
import com.bytesw.bytebot.bean.agency.PassengerMapBean;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.UpdatePasswordBean;
import com.bytesw.bytebot.model.agency.User;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import com.bytesw.bytebot.service.agency.PassengerService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin
@RequestMapping("/service/passengers")
public class PassengerController {
private final PassengerService passengerService;
public PassengerController(PassengerService passengerService) {
this.passengerService = passengerService;
}
@PostMapping("/page")
public CustomPaginationBean<PassengerBean> getByPagination(@RequestBody CustomPaginationBean<PassengerBean> pagination) {
return passengerService.getByPagination(pagination);
}
@GetMapping("{id}")
public ResponseEntity<PassengerBean> getById(@PathVariable Integer id) {
return ResponseEntity.ok(passengerService.getById(id));
}
@PostMapping("/create")
public ResponseEntity<PassengerBean> create(@RequestBody SignUpBean up) {
return ResponseEntity.ok(passengerService.create(up));
}
@PutMapping("/edit/{id}")
public ResponseEntity<PassengerBean> update(@RequestBody UpdatePasswordBean passwordBean, @PathVariable Integer id) {
return ResponseEntity.ok(passengerService.update(passwordBean, id));
}
@DeleteMapping("{id}")
public ResponseEntity<PassengerBean> delete(@PathVariable Integer id) {
return ResponseEntity.ok(passengerService.delete(id));
}
@GetMapping
public ResponseEntity<List<PassengerMapBean>> getAll() {
return ResponseEntity.ok(passengerService.getAll());
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.FlightSearchBean;
import com.bytesw.bytebot.bean.agency.FlightSearchRequestBean;
import com.bytesw.bytebot.bean.agency.ReservationBean;
import com.bytesw.bytebot.bean.agency.UpdateReservationStatus;
import com.bytesw.bytebot.service.agency.FlightService;
import com.bytesw.bytebot.service.agency.ReservationService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import jdk.jfr.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.util.List;
@RestController
@RequestMapping("/service/reservations")
public class ReservationController {
@Autowired
private ReservationService reservationService;
@Autowired
private FlightService flightService;
@PostMapping("/page")
public ResponseEntity<CustomPaginationBean<ReservationBean>> getByPaginationAgent(@RequestBody CustomPaginationBean<ReservationBean> pagination) {
return ResponseEntity.ok(reservationService.getByPaginationAgent(pagination));
}
@PostMapping("/create")
public ResponseEntity<ReservationBean> create(@RequestBody ReservationBean reservationBean) {
return ResponseEntity.status(HttpStatus.CREATED).body(reservationService.create(reservationBean));
}
@PutMapping("/edit/{id}")
public ResponseEntity<ReservationBean> update(@RequestBody UpdateReservationStatus updateReservationStatus, @PathVariable Integer id) {
return ResponseEntity.ok(reservationService.updateStatusReservation(updateReservationStatus, id));
}
@DeleteMapping("{id}")
public ResponseEntity<ReservationBean> delete(@PathVariable Integer id) {
return ResponseEntity.ok(reservationService.delete(id));
}
@GetMapping("{id}")
public ResponseEntity<ReservationBean> getById(@PathVariable Integer id) {
return ResponseEntity.ok(reservationService.getById(id));
}
@GetMapping("/flights/search")
public ResponseEntity<List<FlightSearchBean>> searchFlights(@PathParam("airportOriginId") Integer airportOriginId,
@PathParam("airportDestinationId") Integer airportDestinationId,
@PathParam("departureDate") String departureDate) {
return ResponseEntity.ok(flightService.searchFlights(airportOriginId, airportDestinationId, departureDate));
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.SignInBean;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.UserBean;
import com.bytesw.bytebot.service.agency.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/service/auth")
public class SecurityController {
private final UserService userService;
public SecurityController(UserService userService) {
this.userService = userService;
}
@PostMapping("sign-in")
public ResponseEntity<?> signIn(@RequestBody SignInBean in) {
return userService.signIn(in);
}
@PostMapping("sign-up")
public ResponseEntity<?> signUp(@RequestBody SignUpBean up) {
return userService.signUp(up);
}
}
package com.bytesw.bytebot.controller.agency;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.SupervisorBean;
import com.bytesw.bytebot.bean.agency.UpdatePasswordBean;
import com.bytesw.bytebot.service.agency.SupervisorService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/service/supervisors")
public class SupervisorController {
private final SupervisorService supervisorService;
public SupervisorController(SupervisorService supervisorService) {
this.supervisorService = supervisorService;
}
@GetMapping
public ResponseEntity<List<SupervisorBean>> getAll() {
return ResponseEntity.ok(supervisorService.getAll());
}
@GetMapping("{id}")
public ResponseEntity<SupervisorBean> getById(@PathVariable Integer id) {
return ResponseEntity.ok(supervisorService.getById(id));
}
@PostMapping("/page")
public ResponseEntity<CustomPaginationBean<SupervisorBean>> getByPagination(@RequestBody CustomPaginationBean<SupervisorBean> pagination) {
return ResponseEntity.ok(supervisorService.getByPagination(pagination));
}
@PostMapping("/create")
public ResponseEntity<SupervisorBean> create(@RequestBody SignUpBean bean) {
return ResponseEntity.ok(supervisorService.create(bean));
}
@PutMapping("/edit/{id}")
public ResponseEntity<SupervisorBean> update(@RequestBody UpdatePasswordBean passwordBean, @PathVariable Integer id) {
return ResponseEntity.ok(supervisorService.update(passwordBean, id));
}
@DeleteMapping("{id}")
public ResponseEntity<SupervisorBean> delete(@PathVariable Integer id) {
return ResponseEntity.ok(supervisorService.delete(id));
}
}
package com.bytesw.bytebot.controller.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* @author Sebastian Chicoma Sandmann.
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*
*/
@Getter
@Setter
@ToString
public class ResponseController implements Serializable {
@Expose
private String message;
@Expose
private int statusCode;
@Expose
private Object additionalData;
public ResponseController() {
}
public ResponseController(String message, int statusCode) {
this.message = message;
this.statusCode = statusCode;
}
public ResponseController(String message, int statusCode, Object additionalData) {
this.message = message;
this.statusCode = statusCode;
this.additionalData = additionalData;
}
}
package com.bytesw.bytebot.controller.sso;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
@Controller
@Log4j2
@ConditionalOnProperty(
name="application.services.security",
havingValue = "oauth2sso",
matchIfMissing = false)
public class LoginController {
@RequestMapping(value = {"/home"}, method = RequestMethod.GET)
public final String home(HttpServletRequest request, HttpServletResponse response, Principal principal) {
System.out.println("* home *****> " + request.getSession(false).getId());
System.out.println(request.getSession().getAttribute("username"));
return "home";
}
@RequestMapping(value = {"/mylogin"})
public final String mylogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("* mylogin *****> " + request.getSession(false).getId());
System.out.println(request.getSession().getAttribute("username"));
return "home";
}
}
package com.bytesw.bytebot.controller.sso;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
/**
* @author Marco A. Ortíz García
* @version 2019-03-16.
* <p>
* <p>
* Copyright (c) 2018 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Controller
@ConditionalOnProperty(
name="application.services.security",
havingValue = "oauth2sso",
matchIfMissing = false)
@Log4j2
public class LogoutController {
@Value("${application.services.security.token-key:#{null}}")
private String tokenKey;
@RequestMapping(value = {"/goodbye"}, method = RequestMethod.GET)
public final String goodbye(HttpServletRequest request, HttpServletResponse response, Principal principal, Model model) {
model.addAttribute("token", tokenKey != null);
return "goodbye";
}
}
package com.bytesw.bytebot.controller.sso;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
@Controller
@ConditionalOnProperty(
name="application.services.security",
havingValue = "oauth2sso",
matchIfMissing = false)
@Log4j2
public class TokenFailController {
@RequestMapping(value = {"/token-fail"}, method = RequestMethod.GET)
public final String goodbye(HttpServletRequest request, HttpServletResponse response, Principal principal) {
return "/token-fail";
}
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.*;
import java.io.Serializable;
@Getter @Setter
@EqualsAndHashCode
@AllArgsConstructor
@ToString
public class AttributeValueBean implements Serializable {
private final String identifier;
private String value;
private final Long dataTypeId;
}
package com.bytesw.bytebot.etl.batch.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class DBConfig{
@Value("${spring.datasource.driverClassName}")
private String classDriver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(classDriver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class DeleteDataSensBean {
private Long id;
private String channelValue;
private String value;
private Long agenId;
private Long deletePeriod;
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
@Getter
@Setter
public class DeleteDataSensControlBean {
private Long id;
private Long agenId;
private Timestamp dateDelete;
private Long eventId;
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.time.OffsetDateTime;
@Getter @Setter
public class DeleteDataSensRegistryBean {
private Long id;
private Long inten_id;
private String sender_id;
private String message_sid;
private String multimedia_sid;
private OffsetDateTime update_time;
}
package com.bytesw.bytebot.etl.batch.beans;
import java.util.HashMap;
public class DynaBean extends HashMap<String, Object> {
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
@Getter @Setter
public class TenantBatchBean {
private String id;
private Map<String, String> datasource;
}
package com.bytesw.bytebot.etl.batch.factory.mapper;
import java.util.Map;
public interface MapperFactory<T> {
T createMapper(Map<String, Object> params);
}
package com.bytesw.bytebot.etl.batch.factory.mapper;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.batch.mapper.DynaBeanRowMapper;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class RowMapperFactory implements MapperFactory<DynaBeanRowMapper<DynaBean>>{
@Override
public DynaBeanRowMapper<DynaBean> createMapper(Map<String, Object> params) {
DynaBeanRowMapper<DynaBean> rowMapper = new DynaBeanRowMapper<>();
return rowMapper;
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.database.JdbcCursorItemReader;
@Log4j2
public class ByteDataBaseItemReaderFactory<T> extends JdbcCursorItemReader<T> implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
closeDatabase();
return stepExecution.getExitStatus();
}
private void closeDatabase() {
if (this.getDataSource() instanceof BasicDataSource) {
BasicDataSource dataSource = (BasicDataSource) this.getDataSource();
if (!dataSource.isClosed()) {
try {
dataSource.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
}
}
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.sql.DataSource;
import java.util.Map;
/**
* Params:
* -jdbc-driver
* -username
* -password
* -jdbc-url
* -query
*/
@Component
@Log4j2
public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, RowMapper<DynaBean>> {
@Override
public ItemReader<DynaBean> createReader(RowMapper<DynaBean> mapper, Map<String, Object> params) {
JdbcCursorItemReader<DynaBean> databaseReader;
databaseReader = new ByteDataBaseItemReaderFactory<>();
String jdbcDriver = params.containsKey("jdbc-driver") ? String.valueOf(params.get("jdbc-driver")): null;;
Assert.isTrue(jdbcDriver != null, "jdbc-driver is required!");
String username = params.containsKey("username") ? String.valueOf(params.get("username")): null;;
Assert.isTrue(username != null, "username is required!");
String password = params.containsKey("password") ? String.valueOf(params.get("password")): null;;
Assert.isTrue(password != null, "password is required!");
String jdbcURL = params.containsKey("jdbc-url") ? String.valueOf(params.get("jdbc-url")): null;;
Assert.isTrue(jdbcURL != null, "jdbc-url is required!");
String query = params.containsKey("query") ? String.valueOf(params.get("query")): null;;
Assert.isTrue(query != null, "query is required!");
DataSource dataSource = getBasicDataSource(jdbcDriver, username, password, jdbcURL);
databaseReader.setDataSource(dataSource);
databaseReader.setRowMapper(mapper);
databaseReader.setSql(query);
return databaseReader;
}
protected DataSource getBasicDataSource(String jdbcDriver, String username, String password, String jdbcURL) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(jdbcURL);
return dataSource;
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import org.springframework.batch.item.ItemReader;
import java.util.Map;
public interface ItemReaderFactory<T, E> {
ItemReader<T> createReader(E mapper, Map<String, Object> params);
}
package com.bytesw.bytebot.etl.batch.listener;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
@Log4j2
public class JobCompletionListener extends JobExecutionListenerSupport {
@Override
public void afterJob(JobExecution jobExecution) {
if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
log.debug("BATCH JOB COMPLETED SUCCESSFULLY");
}
}
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.mapper;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class DynaBeanRowMapper<T> implements RowMapper<T> {
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
DynaBean bean = new DynaBean();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String column = JdbcUtils.lookupColumnName(rsmd, i);
bean.putIfAbsent(column, JdbcUtils.getResultSetValue(rs, i));
}
return (T) bean;
}
}
package com.bytesw.bytebot.etl.batch.processor;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.batch.item.ItemProcessor;
public class ConvertToBeanProcessor implements ItemProcessor<DynaBean, DynaBean> {
private ObjectMapper mapper = new ObjectMapper();
@Override
public DynaBean process(DynaBean dynaBean) throws Exception {
Long id = new Long(String.valueOf(dynaBean.get("id")));
String data = (String) dynaBean.get("data");
String senderId = (String) dynaBean.get("sender_id");
EventBean eventBean = new EventBean();
eventBean.setId(id);
eventBean.setData(data);
eventBean.setSenderId(senderId);
dynaBean.put("bean", eventBean);
return dynaBean;
}
}
package com.bytesw.bytebot.etl.batch.service;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.batch.beans.TenantBatchBean;
import com.bytesw.bytebot.etl.batch.factory.mapper.RowMapperFactory;
import com.bytesw.bytebot.etl.batch.factory.reader.DataBaseItemReaderFactory;
import com.bytesw.bytebot.etl.batch.processor.ConvertToBeanProcessor;
import com.bytesw.bytebot.etl.batch.writer.ByteBotJPAWriter;
import com.bytesw.bytebot.etl.batch.writer.DataSensibleJPAWriter;
import com.bytesw.bytebot.etl.config.BatchProperties;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleLogRepository;
import com.bytesw.bytebot.etl.dao.EventHistoryRepository;
import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.enums.IntentTypeEnum;
import com.bytesw.bytebot.etl.services.DeleteSensMessageService;
import com.bytesw.bytebot.etl.services.ProcessMessageService;
import com.bytesw.bytebot.jdbc.DeleteDataSensJDBCRepository;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.FrequencyType;
import com.bytesw.bytebot.model.enums.ProcessETLEnum;
import com.bytesw.bytebot.repository.*;
import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor;
import net.javacrumbs.shedlock.core.LockingTaskExecutor;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.util.*;
import java.util.Calendar;
import java.util.concurrent.ScheduledFuture;
// Descomentar lo siguiente para que funcione
@Service
@Log4j2
@Component
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor="PT15M")
public class ScheduleService implements SchedulingConfigurer {
ScheduledTaskRegistrar scheduledTaskRegistrar;
Map<String, ScheduledFuture> futureMap = new HashMap<>();
@Autowired
@Qualifier("schedulerLockTaskScheduler")
TaskScheduler poolScheduler;
@Value("${application.byte-bot.batch.cron}")
private String cronExpression;
@Value("${application.byte-bot.batch.chunk:500}")
private int chunk;
@Value("${application.scheduler.cron}")
private String cronScheduler;
@Autowired
private JobExplorer jobExplorer;
@Autowired
@Qualifier("asyncJobLauncher")
JobLauncher asyncJobLauncher;
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
private DataBaseItemReaderFactory dataBaseItemReaderFactory;
@Autowired
private RowMapperFactory rowMapperFactory;
@Autowired
private JobExecutionListener listener;
@Autowired
private ProcessMessageService service;
@Autowired
private DeleteSensMessageService deleteSensMessageService;
@Autowired
private Gson gson;
@Autowired
private BatchProperties properties;
@Autowired
private EventHistoryRepository eventHistoryRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private DeleteDataSensJDBCRepository deleteDataSensJDBCRepository;
@Autowired
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
@Autowired
private DeleteDataSensibleLogRepository deleteDataSensibleLogRepository;
@Autowired
private IntentRepository intentRepository;
@Autowired
private ProcessETLRepository processETLRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private CalendarExceptionFullRepository calendarExceptionFullRepository;
@Autowired
private BusinessParameterService businessParameterService;
private boolean schedulerFlag = false;
private List<String> keys = new ArrayList<>();
private String tenant;
private ScheduledTaskRegistrar taskRegister;
private TimeZone timeZone;
@Value("${application.timezone.zone}")
private String parameter;
@Value("${application.timezone.default}")
private String zoneDefault;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (scheduledTaskRegistrar == null) {
scheduledTaskRegistrar = taskRegistrar;
}
if (taskRegistrar.getScheduler() == null) {
taskRegistrar.setScheduler(poolScheduler);
}
if (properties == null) {
throw new RuntimeException("batch properties not found");
}
if (properties.getTenants() == null) {
throw new RuntimeException("batch properties not found");
}
// identifier "prueba" Cambiar luego
properties.getTenants().stream().forEach(tenant -> {
ThreadLocalStorage.setTenantName(tenant.getId());
configureTask(tenant.getId(), "prueba", taskRegistrar);
});
//@TODO Falta añadir el modo multitenant
}
private void configureTask(String tenantIdentifier, String identifier, ScheduledTaskRegistrar taskRegistrar) {
tenant = tenantIdentifier;
taskRegister = taskRegistrar;
String zone = businessParameterService.getBusinessParameterForKey(parameter);
if (zone != null) {
timeZone = TimeZone.getTimeZone(zone);
} else {
timeZone = TimeZone.getTimeZone(zoneDefault);
}
/* Extraer el id del proceso - Delete */
ProcessETL processDelete = processETLRepository.findByName(ProcessETLEnum.PROCESS_DELETE.getName());
/* Busca las listas de SchedulerTask */
List<SchedulerTask> listSchedulerTask = schedulerTaskRepository.findByEtlId(processDelete.getId());
if (!listSchedulerTask.isEmpty()) {
for (SchedulerTask schedulerTask : listSchedulerTask) {
Trigger triggerDelete = new CronTrigger(schedulerTask.getCronExpression(), timeZone);
String keyScheduler = String.format("%s-%s-%s", tenantIdentifier, schedulerTask.getCalendarID().trim(), schedulerTask.getId());
futureMap.put(keyScheduler, taskRegistrar.getScheduler()
.schedule(() -> processDeleteData(tenantIdentifier, taskRegistrar, schedulerTask), triggerDelete));
}
} else {
String keyScheduler = "refresh-schdeduler-task";
Trigger triggerDelete = new CronTrigger(cronScheduler, timeZone);
futureMap.put(keyScheduler, taskRegistrar.getScheduler()
.schedule(() -> syncSchedulerTask(), triggerDelete));
}
}
private void syncSchedulerTask() {
List<SchedulerTask> schedulerTasks = (List) schedulerTaskRepository.findAll();
for (SchedulerTask model: schedulerTasks) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
if (!futureMap.containsKey(key)) {
Trigger trigger = new CronTrigger(model.getCronExpression(), timeZone);
futureMap.put(key, taskRegister.getScheduler()
.schedule(() -> processDeleteData(tenant, taskRegister, model), trigger));
}
}
}
public void restartTask(SchedulerTask model) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
Trigger trigger = new CronTrigger(model.getCronExpression(), timeZone);
if (futureMap.containsKey(key)) {
cancelTask(model);
}
futureMap.put(key, taskRegister.getScheduler()
.schedule(() -> processDeleteData(tenant, taskRegister, model), trigger));
}
public void cancelTaskDelete(Long id) {
String keyDataSens = String.format("deleteSensible-%s-%s", tenant, id);
if (futureMap.containsKey(keyDataSens)) {
ScheduledFuture future = futureMap.get(keyDataSens);
future.cancel(true);
futureMap.remove(keyDataSens);
if (keys.contains(keyDataSens)) {
keys.remove(keyDataSens);
}
}
}
public void cancelTask(SchedulerTask model) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
if (futureMap.containsKey(key)){
ScheduledFuture future = futureMap.get(key);
future.cancel(true);
futureMap.remove(key);
}
if (!keys.isEmpty()) {
for (String keyTask: keys) {
if (futureMap.containsKey(keyTask)) {
ScheduledFuture future = futureMap.get(keyTask);
future.cancel(true);
futureMap.remove(keyTask);
}
}
}
}
/*ETL eliminacion de data sensible*/
public void processDeleteData(String tenantIdentifier, ScheduledTaskRegistrar taskRegistrar, SchedulerTask schedulerTask) {
String zone = businessParameterService.getBusinessParameterForKey(parameter);
if (zone != null) {
timeZone = TimeZone.getTimeZone(zone);
} else {
timeZone = TimeZone.getTimeZone(zoneDefault);
}
Optional<SchedulerTask> schedulerTaskActual = schedulerTaskRepository.findById(schedulerTask.getId());
if (schedulerTaskActual.isPresent()) {
schedulerTask = schedulerTaskActual.get();
} else {
log.info(String.format("No se encuentra la tarea de %s regristrado.", schedulerTask.getDescription()));
cancelTask(schedulerTask);
return;
}
String calendarId = schedulerTask.getCalendarID().trim();
Optional<List<WeekScheduler>> dates = weekSchedulerRepository.findByCalendarId(calendarId);
OffsetTime actual = OffsetTime.now();
OffsetDateTime now = OffsetDateTime.now();
for(WeekScheduler weekScheduler: dates.get()) {
int day = now.getDayOfWeek().getValue() == 7? 1: (now.getDayOfWeek().getValue() + 1);
if(day != weekScheduler.getDayOfWeek()){
schedulerFlag = false;
continue;
}
if (actual.isBefore(weekScheduler.getTo()) && actual.isAfter(weekScheduler.getFrom())) {
Optional<List<CalendarExceptionFull>> calendarException = calendarExceptionFullRepository.findByCalendarId(calendarId);
if (calendarException.isPresent()){
schedulerFlag = validateException(calendarException.get());
} else {
schedulerFlag = true;
}
break;
} else {
schedulerFlag = false;
}
}
if (schedulerFlag) {
List<DeleteDataSensBean> deleteDataSensBeans = deleteDataSensJDBCRepository
.getListAgentChannel(AgentStatusEnum.DEPLOYED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
String keyDataSens = "";
for (DeleteDataSensBean data : deleteDataSensBeans) {
Trigger trigger = new CronTrigger(cronExpression, timeZone);
keyDataSens = String.format("deleteSensible-%s-%s", tenantIdentifier, data.getAgenId());
if (!futureMap.containsKey(keyDataSens)) {
keys.add(keyDataSens);
futureMap.put(keyDataSens, taskRegistrar.getScheduler()
.schedule(() -> scheduleCron(createJobDataSens(data), tenantIdentifier), trigger));
}
}
deleteDataSensBeans = deleteDataSensJDBCRepository.getListAgentChannel(AgentStatusEnum.DELETED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
if (!deleteDataSensBeans.isEmpty()) {
for (DeleteDataSensBean data : deleteDataSensBeans) {
cancelTaskDelete(data.getAgenId());
}
}
} else {
keys.forEach(x -> {
if (futureMap.containsKey(x)) {
ScheduledFuture future = futureMap.get(x);
future.cancel(true);
futureMap.remove(x);
}
});
}
}
private boolean validateException(List<CalendarExceptionFull> calendarException){
boolean result = true;
FrequencyType[] frecuencyType = FrequencyType.values();
OffsetDateTime now = OffsetDateTime.now();
for (CalendarExceptionFull exception : calendarException){
for (int i = 0; i < frecuencyType.length; i++) {
if (frecuencyType[i].getName().equals(exception.getFrequencyType())) {
if (exception.getFrequencyType().equals(FrequencyType.ANNUAL.getName())) {
if (now.getMonth().getValue() == exception.getMonth().intValue() && exception.getDayOfMonth().intValue() == now.getDayOfMonth()){
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.RANGE.getName())) {
if (now.isBefore(exception.getTo()) && now.isAfter(exception.getFrom())){
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.UNIQUE.getName())) {
if (now.toLocalDate().equals(exception.getDate())) {
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.UniqueWeekly.getName())) {
Calendar ca1 = Calendar.getInstance();
ca1.set(now.getYear(), now.getMonth().getValue(), now.getDayOfMonth());
ca1.setMinimalDaysInFirstWeek(1);
if (now.getMonth().getValue() == exception.getMonth().intValue() && exception.getDayOfWeek().intValue() == now.getDayOfWeek().getValue()
&& exception.getWeekOfMonth().intValue() == ca1.WEEK_OF_MONTH){
result = false;
}
}
break;
}
}
if (!result) {
break;
}
}
return result;
}
/* Métodos utilizados para ETL de dashboard */
@Scheduled(cron = "${application.byte-bot.batch.cron}")
@SchedulerLock(name = "Dashboard-ETL", lockAtLeastFor = "PT40S", lockAtMostFor = "PT50S")
protected void createJob() {
List<Agent> agentDeployed = agentRepository.findByStatus(AgentStatusEnum.DEPLOYED);
if (!agentDeployed.isEmpty()) {
ThreadLocalStorage.setTenantName(tenant);
Job job = jobBuilderFactory.get("processJob")
.incrementer(new RunIdIncrementer()).listener(listener)
.flow(createStep(tenant)).end().build();
scheduleCron(job, tenant);
} else {
log.info("No hay agentes deployados.");
}
}
private Step createStep(String tenantIdentifier) {
ByteBotJPAWriter writer = new ByteBotJPAWriter();
writer.setService(service);
return stepBuilderFactory.get("processByteBotData").<DynaBean, DynaBean>chunk(chunk)
.reader(getReader(tenantIdentifier))
.processor(new ConvertToBeanProcessor())
.writer(writer).build();
}
private ItemReader getReader(String tenantIdentifier) {
if (properties == null) {
throw new RuntimeException("Properties not found");
}
Optional<TenantBatchBean> tenantFound = findTenant(tenantIdentifier);
if (!tenantFound.isPresent()) {
throw new RuntimeException("Properties not found");
}
Long id = eventHistoryRepository.maxEventId();
Map<String, Object> params = new HashMap<>();
params.putAll(tenantFound.get().getDatasource());
params.put("query", String.format((String) params.get("query"), id != null ? id : 0));
return dataBaseItemReaderFactory.createReader(rowMapperFactory.createMapper(new HashMap<>()), params);
}
/* Métodos ETL de data sensible */
private Job createJobDataSens(DeleteDataSensBean data) {
log.info("ETL de eliminacion");
data = deleteDataSensJDBCRepository.getAgentChannelByAgentID(AgentStatusEnum.DEPLOYED.getName(),
AgentParameterEnum.ACCESS_TWILIO.getName(), data.getAgenId());
ThreadLocalStorage.setTenantName(tenant);
if (data == null) {
return null;
}
return jobBuilderFactory.get( String.format("processDataSensible-%d",data.getAgenId()))
.incrementer(new RunIdIncrementer()).listener(listener)
.flow(createStepDataSens(tenant, data)).end().build();
}
private Step createStepDataSens(String tenantIdentifier, DeleteDataSensBean data) {
DataSensibleJPAWriter writer = new DataSensibleJPAWriter();
List<String> intentByAgent = deleteDataSensJDBCRepository.getIntentByAgent(IntentTypeEnum.SENSIBLE.getName(), data.getAgenId());
writer.setIntentByAgent(intentByAgent);
writer.setAgent(data);
writer.setService(deleteSensMessageService);
writer.setIntentRepository(intentRepository);
writer.setDeleteDataSensibleControlRepository(deleteDataSensibleControlRepository);
writer.setDeleteDataSensibleLogRepository(deleteDataSensibleLogRepository);
return stepBuilderFactory.get("processByteBotDatasSens")
.<DynaBean, DynaBean>chunk(chunk)
.reader(getReaderDataSens(tenantIdentifier, data))
.processor(new ConvertToBeanProcessor())
.writer(writer).build();
}
private ItemReader getReaderDataSens(String tenantIdentifier, DeleteDataSensBean data) {
if (properties == null) {
throw new RuntimeException("Properties not found");
}
Optional<TenantBatchBean> tenantFound = findTenant(tenantIdentifier);
if (!tenantFound.isPresent()) {
throw new RuntimeException("Properties not found");
}
DeleteDataSensControlBean control = deleteDataSensJDBCRepository.getControl(data.getAgenId());
OffsetDateTime endDate = OffsetDateTime.now();
Long id = 0L;
Long differenceTime = 0L;
if (control != null) {
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(control.getDateDelete().toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate);
differenceTime = (difference.getSeconds() / 60);
if (differenceTime < data.getDeletePeriod()) {
log.info("Agente " + data.getValue() + " aun no cumple con el periodo de espera.");
id = null;
} else {
id = control.getEventId();
}
}
Map<String, Object> params = new HashMap<>();
params.putAll(tenantFound.get().getDatasource());
params.put("query", String.format((String) params.get("query"), id));
return dataBaseItemReaderFactory.createReader(rowMapperFactory.createMapper(new HashMap<>()), params);
}
/* Métodos generales */
private Optional<TenantBatchBean> findTenant(String tenantId) {
return properties.getTenants().stream().filter(x -> x.getId().equals(tenantId)).findFirst();
}
private void scheduleCron(Job job, String tenantId) {
UUID traceID = UUID.randomUUID();
Map<String, JobParameter> maps = new HashMap<>();
maps.put("time", new JobParameter(System.currentTimeMillis()));
maps.put("uuid", new JobParameter(traceID.toString()));
maps.put("tenantId", new JobParameter(tenantId));
JobParameters parameters = new JobParameters(maps);
Set<JobExecution> jobExecutions = new HashSet<>();
try {
if (job != null) {
jobExecutions = jobExplorer.findRunningJobExecutions(job.getName());
String JobInfo = String.format("Jobs {} en Ejecución: {}", job.getName(), jobExecutions.size());
log.info(JobInfo);
if (jobExecutions.isEmpty()) {
asyncJobLauncher.run(job, parameters);
} else {
log.info("El Job " + job.getName() + " no se ejecutará porque hay jobs pendientes: " + jobExecutions.size());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.bytesw.bytebot.etl.batch.service;
import com.bytesw.bytebot.etl.batch.beans.DBConfig;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class SchedulerConfiguration {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
DBConfig dbConfig = new DBConfig();
dataSource = dbConfig.dataSource();
return new JdbcTemplateLockProvider(dataSource);
}
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.writer;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean;
import com.bytesw.bytebot.etl.beans.ProcessMessageResult;
import com.bytesw.bytebot.etl.services.ProcessMessageService;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import javax.transaction.Transactional;
import java.util.List;
@Log4j2
public class ByteBotJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {
@Getter
@Setter
private ProcessMessageService service;
@Override
@Transactional
public void write(List<? extends DynaBean> list) throws Exception {
for (DynaBean dynaBean : list) {
EventBean eventBean = (EventBean) dynaBean.get("bean");
String json = (String) dynaBean.get("data");
ProcessMessageResult result = service.processMessage(json, eventBean.getSenderId());
log.debug(String.format("senderId: %s, processed: %s", eventBean.getSenderId(), result.isProcessed()));
service.saveHistory(eventBean.getId(), eventBean.getSenderId());
}
}
@Override
public void beforeStep(StepExecution stepExecution) {
String tenantId = stepExecution.getJobParameters().getString("tenantId");
ThreadLocalStorage.setTenantName(tenantId);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return stepExecution.getExitStatus();
}
}
package com.bytesw.bytebot.etl.batch.writer;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensRegistryBean;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleLogRepository;
import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.enums.EventTypeEnum;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleControl;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleLog;
import com.bytesw.bytebot.etl.model.Intent;
import com.bytesw.bytebot.etl.services.DeleteSensMessageService;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.*;
@Log4j2
public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {
@Getter
@Setter
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
@Getter
@Setter
private DeleteDataSensibleLogRepository deleteDataSensibleLogRepository;
@Getter
@Setter
private IntentRepository intentRepository;
@Getter
@Setter
private DeleteSensMessageService service;
@Getter
@Setter
private List<String> intentByAgent;
@Getter
@Setter
private DeleteDataSensBean agent;
@Override
@Transactional
public void write(List<? extends DynaBean> list) throws Exception {
Object numeros = JsonUtils.getFieldFromJson(agent.getChannelValue(), "$.telefono_despliegue");
List<String> numerosAgentes = numbersAgent((List<Map>) numeros);
for (DynaBean dynaBean : list) {
Long id = Long.parseLong(dynaBean.get("id").toString());
String json = (String) dynaBean.get("data");
String event = (String) JsonUtils.getFieldFromJson(json, "$.event");
String sender_id;
boolean update_control = false;
String presentDate = OffsetDateTime.now().toString().replace('T', ' ');
String timeZone = presentDate.substring(presentDate.length() - 6);
presentDate = presentDate.replace(timeZone, "");
if (EventTypeEnum.USER.getName().equals(event)) {
String toAgent = (String) JsonUtils.getFieldFromJson(json, "$.metadata.To");
String agentNumber = new String();
if (toAgent == null) {
continue;
}
if (!toAgent.isEmpty()) {
agentNumber = toAgent.split(":")[1];
}
if (numerosAgentes.contains(agentNumber)) {
String intent = (String) JsonUtils.getFieldFromJson(json, "$.parse_data.intent.name");
if (intentByAgent.contains(intent)) {
String SmSMessageSid = (String) JsonUtils.getFieldFromJson(json, "$.metadata.SmsMessageSid");
Optional<Intent> intenId = this.intentRepository.findIntenNameById(intent, agent.getAgenId());
if (!intenId.isPresent()) {
throw new Exception("Intent no esta presente");
}
try {
sender_id = (String) JsonUtils.getFieldFromJson(json, "$.sender_id");
log.info(sender_id);
} catch (Exception e) {
log.info(e.getMessage());
sender_id = (String) JsonUtils.getFieldFromJson(json, "$.metadata.sender_id");
}
List<DeleteDataSensRegistryBean> deleteSensibleBean = new ArrayList<>();
try {
deleteSensibleBean = service.deleteMessage(agent.getAgenId()
, SmSMessageSid, intenId.get().getId(), sender_id);
update_control = true;
} catch (NotFoundException e) {
update_control = true;
} catch (Exception e) {
update_control = false;
}
for (DeleteDataSensRegistryBean registry : deleteSensibleBean) {
DeleteDataSensibleLog reg = new DeleteDataSensibleLog();
reg.setIntenId(registry.getInten_id());
reg.setMessageId(registry.getMessage_sid());
reg.setMultimediaId(registry.getMultimedia_sid());
reg.setSendId(registry.getSender_id());
reg.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleLogRepository.save(reg);
}
}
}
} else {
update_control = true;
}
DeleteDataSensibleControl control = new DeleteDataSensibleControl();
Optional<DeleteDataSensibleControl> controlBd = deleteDataSensibleControlRepository.findEventIdByAgentId(agent.getAgenId());
if (update_control) {
if (controlBd.isPresent()) {
// Update
control.setId(controlBd.get().getId());
control.setAgentId(agent.getAgenId());
control.setEventId(id);
control.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleControlRepository.save(control);
} else {
// Create
control.setAgentId(agent.getAgenId());
control.setEventId(id);
control.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleControlRepository.save(control);
}
}
}
}
private List<String> numbersAgent(List<Map> listNumber){
List<String> result = new ArrayList<>();
for (Map map : listNumber){
String cod = (String) map.get("codigoInternacional");
String number = (String) map.get("numero");
String agent = "+" + cod + number;
result.add(agent);
}
return result;
}
@Override
public void beforeStep(StepExecution stepExecution) {
String tenantId = stepExecution.getJobParameters().getString("tenantId");
ThreadLocalStorage.setTenantName(tenantId);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return stepExecution.getExitStatus();
}
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class ActionBean {
@Expose
private Long id;
@Expose
private String identifier;
}
package com.bytesw.bytebot.etl.beans;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
@Getter @Setter @ToString
public class EventBean implements Serializable {
private Long id;
private String data;
private String senderId;
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class GoalBean {
@Expose
private Long id;
@Expose
private String identifier;
@Expose
private Long agenId;
}
\ No newline at end of file
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class GoalForActionsBean {
@Expose
private Long id;
@Expose
private Long goalId;
@Expose
private Long actionId;
}
package com.bytesw.bytebot.etl.beans;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class IntentBean {
private Long id;
private String identifier;
private String sensible;
private Long agenId;
}
package com.bytesw.bytebot.etl.beans;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class ProcessMessageResult {
private boolean processed = true;
private String message;
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
@Getter @Setter
public class SessionBean {
@Expose
private Long id;
@Expose
private Timestamp sessionDate;
@Expose
private Timestamp lastEventDate;
@Expose
private Timestamp responseDate;
@Expose
private Long userId;
@Expose
private Long channelId;
}
package com.bytesw.bytebot.etl.config;
import com.bytesw.bytebot.etl.batch.listener.JobCompletionListener;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
@Configuration
public class BatchConfig {
@Bean
public JobExecutionListener listener() {
return new JobCompletionListener();
}
@Bean("asyncJobLauncher")
public JobLauncher asyncJobLauncher(JobRepository jobRepository) {
final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
final SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
jobLauncher.setTaskExecutor(simpleAsyncTaskExecutor);
return jobLauncher;
}
}
package com.bytesw.bytebot.etl.config;
import com.bytesw.bytebot.etl.batch.beans.TenantBatchBean;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "batch")
public class BatchProperties {
@Getter @Setter
private List<TenantBatchBean> tenants;
}
package com.bytesw.bytebot.etl.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;
@ConfigurationProperties(prefix = "batch")
public class BatchPropertiesWithoutTenant {
@Getter @Setter
Map<String, String> datasource;
}
package com.bytesw.bytebot.etl.converter;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class MessageTypeConverter implements AttributeConverter<MessageTypeEnum, String> {
@Override
public String convertToDatabaseColumn(MessageTypeEnum agentTypeEnum) {
return (agentTypeEnum != null ? agentTypeEnum.getName() : null);
}
@Override
public MessageTypeEnum convertToEntityAttribute(String s) {
return MessageTypeEnum.fromString(s);
}
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Action;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface ActionRepository extends CrudRepository<Action, Long>, JpaSpecificationExecutor<Action> {
Optional<Action> findByIdentifier(String identifier);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleControl;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface DeleteDataSensibleControlRepository extends CrudRepository<DeleteDataSensibleControl, Long> {
@Query("SELECT s from DeleteDataSensibleControl s WHERE s.agentId = :agentId")
Optional<DeleteDataSensibleControl> findEventIdByAgentId(@Param("agentId") Long agentId);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleLog;
import org.springframework.data.repository.CrudRepository;
public interface DeleteDataSensibleLogRepository extends CrudRepository<DeleteDataSensibleLog, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.EventHistory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface EventHistoryRepository extends CrudRepository<EventHistory, Long> {
@Query("SELECT MAX(e.eventId) FROM EventHistory e")
Long maxEventId();
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Intent;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface IntentRepository extends CrudRepository<Intent, Long> {
Optional<Intent> findByIdentifier(String identifier);
@Query("SELECT s from Intent s WHERE s.identifier = :intenIdent and s.agenId = :agenId")
Optional<Intent> findIntenNameById(@Param("intenIdent") String intenIdent, @Param("agenId") Long agenId);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Message;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface MessageRepository extends CrudRepository<Message, Long> {
@Query("SELECT s from Message s WHERE s.sessionId = :sessionId")
Long findLastCorrelativeBySession(@Param("sessionId") Long sessionId);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Response;
import org.springframework.data.repository.CrudRepository;
public interface ResponseRepository extends CrudRepository<Response, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.SessionAction;
import org.springframework.data.repository.CrudRepository;
public interface SessionActionRepository extends CrudRepository<SessionAction, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Session;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.time.OffsetDateTime;
public interface SessionBotRepository extends CrudRepository<Session, Long> {
@Query("UPDATE Session s set s.lastEventDate = :lastEventDate WHERE s.id = :id")
void updateLastEventDateBySession(@Param("id") Long id, @Param("lastEventDate") OffsetDateTime dateTime);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.User;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByIdentifier(String identifier);
}
package com.bytesw.bytebot.etl.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum EventTypeEnum {
USER("user"), BOT("bot"), ACTION("action"), START_SESSION("action_session_start");
private final String name;
private static final Map<String, EventTypeEnum> map = new HashMap<>();
static {
for (EventTypeEnum type : EventTypeEnum.values()) {
map.put(type.name, type);
}
}
EventTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static EventTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.etl.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum IntentTypeEnum {
SENSIBLE("1"), NO_SENSIBLE("0");
private final String name;
private static final Map<String, IntentTypeEnum> map = new HashMap<>();
static {
for (IntentTypeEnum type : IntentTypeEnum.values()) {
map.put(type.name, type);
}
}
IntentTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static IntentTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.etl.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum MessageTypeEnum {
REJECTED("R"), ACCEPTED("A");
private final String name;
private static final Map<String, MessageTypeEnum> map = new HashMap<>();
static {
for (MessageTypeEnum type : MessageTypeEnum.values()) {
map.put(type.name, type);
}
}
MessageTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static MessageTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.etl.jdbc;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ETLMessageJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int getLastCorrelativeBySession(Long sessionId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLMessageMapper.getLastCorrelativeBySession", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.etl.jdbc;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ETLResponseJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int getLastCorrelativeBySession(Long sessionId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLResponseMapper.getLastCorrelativeBySession", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.etl.jdbc;
import com.bytesw.bytebot.etl.beans.SessionBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
@Component
public class ETLSessionBotJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public SessionBean getLastSessionByUser(Long userId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("userId", userId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.getLastSessionByUser", params);
} finally {
session.close();
}
}
public void updateLastEventDate(Long sessionID, OffsetDateTime lastEventDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionID);
params.put("lastEventDate", lastEventDate);
session.update("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.updateLastEventDate", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name = "AVB_ACTION")
@NamedQuery(name = "Action.findByPK", query = "Select p from Action p where p.id = ?1")
public class Action {
@Id
@Column(name = "action_id")
@SequenceGenerator(name = "AVB_ACTION_GENERATOR", sequenceName = "AVB_ACTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_ACTION_GENERATOR")
private Long id;
@Column(name = "action_ident")
private String identifier;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.sql.Timestamp;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name="avb_delete_sens_msg_control")
public class DeleteDataSensibleControl {
@Id
@Column(name = "dsmc_id")
@SequenceGenerator(name = "AVB_DELETE_MSG_SENS_CONTROL_GENERATOR", sequenceName = "AVB_DELETE_SENS_MSG_CONTROL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_DELETE_MSG_SENS_CONTROL_GENERATOR")
private Long id;
@Column(name = "agent_id")
private Long agentId;
@Column(name = "dsmc_date")
private Timestamp date;
@Column(name = "evnt_id")
private Long eventId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.sql.Timestamp;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name="avb_delete_sens_msg_log")
public class DeleteDataSensibleLog {
@Id
@Column(name = "dele_id")
@SequenceGenerator(name = "AVB_DELETE_MSG_SENS_LOG_GENERATOR", sequenceName = "AVB_DELETE_SENS_MSG_LOG_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_DELETE_MSG_SENS_LOG_GENERATOR")
private Long id;
@Column(name = "inten_id")
private Long intenId;
@Column(name = "send_id")
private String sendId;
@Column(name = "dele_smsg")
private String messageId;
@Column(name = "dele_msmsg")
private String multimediaId;
@Column(name = "dele_fecej")
private Timestamp date;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_event_history")
@NamedQuery(name = "EventHistory.findByPK", query = "Select p from EventHistory p where p.id = ?1")
public class EventHistory {
@Id
@Column(name = "evenh_id")
@SequenceGenerator(name = "AVB_EVENT_HISTORY_GENERATOR", sequenceName = "AVB_EVENT_HISTORY_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_EVENT_HISTORY_GENERATOR")
private Long id;
@Column(name = "evenh_sendid")
private String senderId;
@Column(name = "evenh_evid")
private Long eventId;
@Column(name = "evenh_date")
private OffsetDateTime date;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_goal")
@NamedQuery(name = "Goal.findByPK", query = "Select p from Goal p where p.id = ?1")
public class Goal {
@Id
@Column(name = "goal_id")
@SequenceGenerator(name = "AVB_GOAL_GENERATOR", sequenceName = "AVB_GOAL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_GOAL_GENERATOR")
private Long id;
@Column(name = "goal_ident")
private String identifier;
@Column(name = "agen_id")
private Long agenId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name = "avb_GoalForActions")
@NamedQuery(name = "GoalForActions.findByPK", query = "Select p from GoalForActions p where p.id = ?1")
public class GoalForActions {
@Id
@Column(name = "gfac_id")
@SequenceGenerator(name = "AVB_GOALFORACTIONS_GENERATOR", sequenceName = "AVB_GOALFORACTIONS_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_GOALFORACTIONS_GENERATOR")
private Long id;
@Column(name = "goal_id")
private Long goalId;
@Column(name = "action_id")
private Long actionId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_intent")
@NamedQuery(name = "Intent.findByPK", query = "Select p from Intent p where p.id = ?1")
public class Intent {
@Id
@Column(name = "inten_id")
@SequenceGenerator(name = "AVB_INTENT_DASHBOARD_GENERATOR", sequenceName = "AVB_INTENT_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_INTENT_DASHBOARD_GENERATOR")
private Long id;
@Column(name = "inten_ident")
private String identifier;
@Column(name = "intent_is_sensible")
private String sensible;
@Column(name = "agen_id")
private Long agenId;
}
package com.bytesw.bytebot.etl.model;
import com.bytesw.bytebot.etl.converter.MessageTypeConverter;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString @Builder
@Table(name="avb_message")
@NamedQuery(name = "Message.findByPK", query = "Select p from Message p where p.id = ?1")
public class Message {
@Id
@Column(name = "messa_id")
@SequenceGenerator(name = "AVB_MESSAGE_GENERATOR", sequenceName = "AVB_MESSAGE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_MESSAGE_GENERATOR")
private Long id;
@Column(name = "session_id")
private Long sessionId;
@Column(name = "messa_date")
private OffsetDateTime date;
@Column(name = "messa_cont")
private String content;
@Column(name = "messa_corre")
private int correlative;
@Column(name = "messa_prob")
private BigDecimal probability;
@Convert(converter = MessageTypeConverter.class)
@Column(name = "messa_type")
private MessageTypeEnum type;
@Column(name = "inten_id")
private Long intentId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_response")
@NamedQuery(name = "Response.findByPK", query = "Select p from Response p where p.id = ?1")
public class Response {
@Id
@Column(name = "respo_id")
@SequenceGenerator(name = "AVB_RESPONSE_GENERATOR", sequenceName = "AVB_RESPONSE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_RESPONSE_GENERATOR")
private Long id;
@Column(name = "respo_date")
private OffsetDateTime date;
@Column(name = "respo_cont")
private String content;
@Column(name = "respo_corr")
private int correlative;
@Column(name = "session_id")
private Long sessionId;
}
package com.bytesw.bytebot.etl.model;
import com.bytesw.bytebot.model.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_session")
@NamedQuery(name = "Session.findByPK", query = "Select p from Session p where p.id = ?1")
public class Session {
@Id
@Column(name = "session_id")
@SequenceGenerator(name = "AVB_SESSION_GENERATOR", sequenceName = "AVB_SESSION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_SESSION_GENERATOR")
private Long id;
@Column(name = "session_date", nullable = false)
private OffsetDateTime sessionDate;
@Column(name = "session_ledat", nullable = false)
private OffsetDateTime lastEventDate;
@Column(name = "session_frdat", nullable = false)
private OffsetDateTime responseDate;
@ManyToOne
@JoinColumn(name = "chan_id", referencedColumnName = "chan_id")
private Channel channel;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_action_session")
@NamedQuery(name = "SessionAction.findByPK", query = "Select p from SessionAction p where p.id = ?1")
public class SessionAction {
@Id
@Column(name = "asess_id")
@SequenceGenerator(name = "AVB_ACTION_SESSION_GENERATOR", sequenceName = "AVB_ACTION_SESSION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_ACTION_SESSION_GENERATOR")
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "action_id", referencedColumnName = "action_id")
private Action action;
@Column(name = "asess_date")
private OffsetDateTime date;
@Column(name = "session_id")
private Long sessionId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity @Getter @Setter @ToString
@Table(name="avb_user")
@NamedQuery(name = "User.findByPK", query = "Select p from User p where p.id = ?1")
public class User {
@Id
@Column(name = "user_id")
@SequenceGenerator(name = "AVB_USER_GENERATOR", sequenceName = "AVB_USER_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_USER_GENERATOR")
private Long id;
@Column(name = "user_ident")
private String identifier;
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
import com.bytesw.bytebot.etl.dao.SessionActionRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.Action;
import com.bytesw.bytebot.etl.model.SessionAction;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.util.Optional;
@Service
@Transactional
public class ActionMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private ETLSessionBotJDBCRepository ETLSessionBotJDBCRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ActionRepository actionRepository;
@Autowired
private SessionActionRepository sessionActionRepository;
@Value("${application.etl.action.user-field:sender_id}")
private String userIdentifierFieldName;
@Value("${application.etl.action.event-field:name}")
private String eventFieldName;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
this.fields.put(ACTION_FIELD_NAME, "$.name");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = ETLSessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
String actionIdentifier = (String) JsonUtils.getFieldFromJson(json, this.fields.get(ACTION_FIELD_NAME));
if (session != null && actionIdentifier != null && !actionIdentifier.isEmpty()) {
Optional<Action> actionFound = actionRepository.findByIdentifier(actionIdentifier);
if (!actionFound.isPresent()) {
return false;
}
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
SessionAction sessionAction = new SessionAction();
sessionAction.setAction(actionFound.get());
sessionAction.setSessionId(session.getId());
sessionAction.setDate(getOffsetDateTimeFromTimestampPython(timestamp));
sessionActionRepository.save(sessionAction);
updateEventDate(session.getId(), sessionAction.getDate());
return true;
}
}
return false;
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.ResponseRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.jdbc.ETLResponseJDBCRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.Response;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.util.Optional;
@Service
@Transactional
public class BotMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private UserRepository userRepository;
@Autowired
private ETLSessionBotJDBCRepository ETLSessionBotJDBCRepository;
@Autowired
private ETLResponseJDBCRepository responseJDBCRepository;
@Autowired
private ResponseRepository responseRepository;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(CONTENT_FIELD_NAME, "$.text");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = ETLSessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
if (session != null) {
int correlative = responseJDBCRepository.getLastCorrelativeBySession(session.getId());
String content = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CONTENT_FIELD_NAME));
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
if (content != null && timestamp != null) {
Response response = new Response();
response.setSessionId(session.getId());
response.setCorrelative(correlative++);
response.setContent(content);
response.setDate(getOffsetDateTimeFromTimestampPython(timestamp));
responseRepository.save(response);
updateEventDate(session.getId(), response.getDate());
updateFirstResponse(session, response.getDate());
return true;
}
}
}
return false;
}
private void updateFirstResponse(SessionBean session, OffsetDateTime date) {
if (session.getResponseDate() == null) {
Optional<Session> sessionFond = sessionBotRepository.findById(session.getId());
if (sessionFond.isPresent()) {
Session sessionDB = sessionFond.get();
sessionDB.setResponseDate(date);
sessionBotRepository.save(sessionDB);
}
}
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensRegistryBean;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Log4j2
public class DeleteSensMessageService {
@Autowired
private TwilioService twilioService;
@Autowired
DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
public List<DeleteDataSensRegistryBean> deleteMessage(Long agentId, String SmsMessage, Long inten_id, String sender_id) throws Exception {
List<DeleteDataSensRegistryBean> deleteMessages = new ArrayList<DeleteDataSensRegistryBean>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> params = new HashMap<>();
params.put("agent_id", agentId.intValue());
try {
Map<String, Object> result = new HashMap<>();
data = twilioService.generateInfo(SmsMessage, params);
if (data.isEmpty()) {
throw new Exception("Parámetros vacíos");
}
DeleteDataSensRegistryBean registry = new DeleteDataSensRegistryBean();
if (data.get("status") != null) {
List<String> images = new ArrayList<String>();
images = (List<String>) data.get("data");
for (String image : images) {
if (image.trim().isEmpty()) {
continue;
}
// Info del Bean
registry.setMultimedia_sid(image);
registry.setMessage_sid(SmsMessage);
registry.setUpdate_time(OffsetDateTime.now());
registry.setInten_id(inten_id);
registry.setSender_id(sender_id);
// Agregado a la lista
deleteMessages.add(registry);
}
}
return deleteMessages;
} catch (NotFoundException e) {
log.debug(e);
throw new NotFoundException(e.getMessage());
} catch (Exception e) {
log.debug(e);
throw new Exception(e.getMessage());
}
}
}
package com.bytesw.bytebot.etl.services;
@FunctionalInterface
public interface MessageProcessed {
boolean process(String json, String senderId);
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.dao.SessionBotRepository;
import com.bytesw.bytebot.etl.model.Session;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Log4j2
public abstract class MessageProcessedSupport {
protected static final String SENDER_ID_FIELD_NAME = "senderId";
protected static final String CONTENT_FIELD_NAME = "content";
protected static final String CONFIDENCE_FIELD_NAME = "confidence";
protected static final String CHANNEL_FIELD_NAME = "channel";
protected static final String TIMESTAMP_FIELD_NAME = "timestamp";
protected static final String ACTION_FIELD_NAME = "actionName";
protected static final String INTENT_NAME = "intentName";
protected Map<String, String> fields = new HashMap<>();
@Autowired
protected SessionBotRepository sessionBotRepository;
protected static final String PYTHON_TIMESTAMP_FORMAT = "^\\d*\\.?\\d*$";
protected static final Pattern pattern = Pattern.compile(PYTHON_TIMESTAMP_FORMAT);
protected OffsetDateTime getOffsetDateTimeFromTimestampPython(Object objectTimestamp) {
BigDecimal dateDecimal;
if (objectTimestamp instanceof Double) {
dateDecimal = new BigDecimal((Double) objectTimestamp);
} else {
if (!isValidTimestampFormat(String.valueOf(objectTimestamp), pattern)) {
return null;
}
dateDecimal = new BigDecimal(String.valueOf(objectTimestamp));
}
Long timestamp = (long) (dateDecimal.doubleValue() * 1000);
if (String.valueOf(timestamp).length() < 13) {
int numberOfZero = 13 - String.valueOf(timestamp).length();
for (int i = 0; i < numberOfZero; i++) {
timestamp = timestamp * 10;
}
}
OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
return date;
}
protected boolean isValidTimestampFormat(String text, Pattern pattern) {
Matcher matcher = pattern.matcher(text);
boolean matches = matcher.matches();
return matches;
}
protected void updateEventDate(Long sessionId, OffsetDateTime date) {
Optional<Session> sessionFond = sessionBotRepository.findById(sessionId);
if (sessionFond.isPresent()) {
Session session = sessionFond.get();
session.setLastEventDate(date);
sessionBotRepository.save(session);
}
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.ProcessMessageResult;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.EventHistoryRepository;
import com.bytesw.bytebot.etl.enums.EventTypeEnum;
import com.bytesw.bytebot.etl.model.EventHistory;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.xdf.config.AppContextManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
@Log4j2
@Service
public class ProcessMessageService {
@Autowired
private EventHistoryRepository eventHistoryRepository;
@Autowired
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
public void saveHistory(Long id, String senderId) {
EventHistory eventHistory = new EventHistory();
eventHistory.setDate(OffsetDateTime.now());
eventHistory.setEventId(id);
eventHistory.setSenderId(senderId);
eventHistoryRepository.save(eventHistory);
}
public ProcessMessageResult processMessage(String json, String senderId) throws Exception {
ProcessMessageResult result = new ProcessMessageResult();
MessageProcessed messageProcessed = detectType(json);
if (messageProcessed == null) {
result.setProcessed(false);
result.setMessage("Event type not support");
return result;
}
result.setProcessed(messageProcessed.process(json, senderId));
return result;
}
private MessageProcessed detectType(String json) {
MessageProcessed messageProcessed = null;
EventTypeEnum type;
try {
String event = (String) JsonUtils.getFieldFromJson(json, "$.event");
if (AppContextManager.getAppContext() != null && event != null) {
String name = (String) JsonUtils.getFieldFromJson(json, "$.name");
type = EventTypeEnum.fromString(event);
if (type != null) {
// Verify if message is valid
if (EventTypeEnum.USER.equals(type)) {
String message_id = (String) JsonUtils.getFieldFromJson(json, "$.message_id");
if (message_id == null) {
return null;
}
}
if (EventTypeEnum.ACTION.equals(type) && EventTypeEnum.START_SESSION.getName().equals(name)) {
type = EventTypeEnum.START_SESSION;
}
messageProcessed = (MessageProcessed) AppContextManager.getAppContext().getBean(getMessageProcessedName(type));
}
}
} catch (Exception e) {
log.debug(e);
}
return messageProcessed;
}
private String getMessageProcessedName(EventTypeEnum type) {
String[] words = type.toString().toLowerCase().split("_");
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String word : words) {
if (isFirst) {
sb.append(word);
isFirst = false;
} else {
sb.append(word.substring(0, 1).toUpperCase() + word.substring(1));
}
}
sb.append("MessageProcessed");
return sb.toString();
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
@Service
@Transactional
public class StartSessionMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private UserRepository userRepository;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
User user;
if (!userFound.isPresent()) {
user = new User();
user.setIdentifier(senderId);
user = userRepository.save(user);
} else {
user = userFound.get();
}
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
if (timestamp != null) {
// Validate if the below method is ok
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");
OffsetDateTime sessionDate = getOffsetDateTimeFromTimestampPython(timestamp);
if (sessionDate != null) {
Session session = new Session();
session.setSessionDate(sessionDate);
session.setUser(user);
session.setLastEventDate(sessionDate);
sessionBotRepository.save(session);
return true;
}
}
}
return false;
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.dao.MessageRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import com.bytesw.bytebot.etl.jdbc.ETLMessageJDBCRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.Intent;
import com.bytesw.bytebot.etl.model.Message;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.bytebot.jdbc.DeleteDataSensJDBCRepository;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.repository.ChannelRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Log4j2
@Service
@Transactional
public class UserMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private ETLSessionBotJDBCRepository sessionBotJDBCRepository;
@Autowired
private ETLMessageJDBCRepository messageJDBCRepository;
@Autowired
private ChannelRepository chanelRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private MessageRepository messageRepository;
@Autowired
private IntentRepository intentRepository;
@Autowired
private DeleteDataSensJDBCRepository deleteDataSensJDBCRepository;
@Value("${application.etl.text-user.threshold:0.5}")
private BigDecimal threshold;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(CONFIDENCE_FIELD_NAME, "$.parse_data.intent.confidence");
this.fields.put(CONTENT_FIELD_NAME, "$.text");
this.fields.put(CHANNEL_FIELD_NAME, "$.input_channel");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
this.fields.put(INTENT_NAME, "$.parse_data.intent.name");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = sessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
if (session != null) {
/* ID del agente */
Long agentId = identifierAgent(json);
if (agentId >= 1) {
Message message = cloneMessage(json, session.getId(), agentId);
if (message != null) {
int correlative = messageJDBCRepository.getLastCorrelativeBySession(message.getSessionId());
correlative++;
message.setCorrelative(correlative);
messageRepository.save(message);
String channel = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CHANNEL_FIELD_NAME));
updateSession(session.getId(), message.getDate(), channel);
return true;
}
}
}
}
return false;
}
private void updateSession(Long sessionId, OffsetDateTime date, String channelIdentifier) {
Optional<Session> sessionFond = sessionBotRepository.findById(sessionId);
if (sessionFond.isPresent()) {
Session session = sessionFond.get();
session.setLastEventDate(date);
if (channelIdentifier != null && session.getChannel() == null) {
Optional<Channel> channelFound = chanelRepository.findByName(channelIdentifier);
if (channelFound.isPresent()) {
session.setChannel(channelFound.get());
}
}
sessionBotRepository.save(session);
}
}
private Message cloneMessage(String json, Long sessionId, Long agentId) {
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
Object confidence = JsonUtils.getFieldFromJson(json, this.fields.get(CONFIDENCE_FIELD_NAME));
String content = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CONTENT_FIELD_NAME));
OffsetDateTime messageDate = getOffsetDateTimeFromTimestampPython(timestamp);
BigDecimal probability = null;
if (confidence instanceof Double) {
probability = new BigDecimal((Double) confidence);
} else if (confidence instanceof BigDecimal) {
probability = (BigDecimal) confidence;
}
if (messageDate == null || probability == null) {
return null;
}
Message message = Message.builder()
.content(content)
.sessionId(sessionId)
.date(messageDate)
.probability(new BigDecimal(String.valueOf(probability)))
.type((probability.compareTo(threshold) >= 0) ? MessageTypeEnum.ACCEPTED : MessageTypeEnum.REJECTED)
//.correlative()
.build();
if (MessageTypeEnum.ACCEPTED.equals(message.getType())) {
String intentName = (String) JsonUtils.getFieldFromJson(json, this.fields.get(INTENT_NAME));
Optional<Intent> optionalIntent = intentRepository.findIntenNameById(intentName, agentId);
if (optionalIntent.isPresent()) {
message.setIntentId(optionalIntent.get().getId());
}
}
return message;
}
//-------
private Long identifierAgent(String json){
Long agentId = 0l;
String number= (String) JsonUtils.getFieldFromJson(json, "$.metadata.To");
if (number != null) {
number = number.split(":")[1];
List<DeleteDataSensBean> deleteDataSensBeans = deleteDataSensJDBCRepository
.getListAgentChannel(AgentStatusEnum.DEPLOYED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
for (DeleteDataSensBean deleteDataSensBean: deleteDataSensBeans) {
Object numeros = JsonUtils.getFieldFromJson(deleteDataSensBean.getChannelValue(), "$.telefono_despliegue");
List<String> numerosAgentes = numbersAgent((List<Map>) numeros);
if (numerosAgentes.contains(number)) {
agentId = deleteDataSensBean.getAgenId();
break;
}
}
}
return agentId;
}
private List<String> numbersAgent(List<Map> listNumber){
List<String> result = new ArrayList<>();
for (Map map : listNumber){
String cod = (String) map.get("codigoInternacional");
String number = (String) map.get("numero");
String agent = "+" + cod + number;
result.add(agent);
}
return result;
}
//------
}
package com.bytesw.bytebot.etl.utils;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class JsonUtils {
public static Object getFieldFromJson(String json, String jsonPath) {
Object result = null;
try {
result = JsonPath.parse(json)
.read(jsonPath);
} catch (PathNotFoundException e) {
log.debug(e);
} catch (Exception e) {
log.error(e);
}
return result;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class FileValidationResponse {
private Long id;
private String uuid;
private String fileName;
private String status;
private String user;
private String uploadDate;
private String message;
private FileValidationResult fileValidationResult;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class FileValidationResult {
private ValidationStatusEnum status;
private Map<String, String> headersErrorMap;
private Map<Integer, Object> recordsErrorMap;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum ValidationStatusEnum {
OK("OK"),
ERROR("ERROR"),
DATA_INCOMPLETE ("DI"),
FORMAT_INCORRECT("FI"),
INCOMPATIBLE_EXTENSION("IE"),
HEADER_ERROR ("HE"),
CONTENT_ERROR("CE");
private final String name;
private static final Map<String, ValidationStatusEnum> map = new HashMap<>();
static {
for (ValidationStatusEnum type : ValidationStatusEnum.values()) {
map.put(type.name, type);
}
}
ValidationStatusEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static ValidationStatusEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.bean.ActionSummaryByGoalBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class ActionJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public List<ActionSummaryByGoalBean> getSummaryByGoals(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ActionMapper.getSummaryActionsByGoal", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class AgentJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlsession;
@Cacheable(value = "deploy_agents")
public List<DeploymentChannelParamValueBean> getCredentialsFromAgentStatus(String status) {
SqlSession session = sqlsession.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
return session.selectList("com.bytesw.bytebot.dao.jdbc.AgentMapper.getCredentialsFromAgentandChannel", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.jdbc;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.bytesw.bytebot.bean.SessionByClientBean;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
@Component
public class BotSessionJDCBRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.countSessionsInRange", params);
} finally {
session.close();
}
}
public Timestamp getLastDateInRage(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.getLastDateInRange", params);
} finally {
session.close();
}
}
public Double getAvgSessionByCustomerInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.avgSessionsByCustomerInRange", params);
} finally {
session.close();
}
}
public Object getAvgFirstResponseTime(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.avgFirstResponseTime", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class DeleteDataSensJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public List<DeleteDataSensBean> getListAgentChannel(String status, String channel){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
params.put("channel", channel);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getAgentChannel", params);
} finally {
session.close();
}
}
public DeleteDataSensBean getAgentChannelByAgentID(String status, String channel, Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
params.put("channel", channel);
params.put("agentId", id);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getAgentChannelByAgentId", params);
} finally {
session.close();
}
}
public DeleteDataSensControlBean getControl(Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("agenId", id);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getControl", params);
} finally {
session.close();
}
}
public List<String> getIntentByAgent(String sensible, Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sensible", sensible);
params.put("agenId", id);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getIntentByAgent", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.bean.MessageByIntentBean;
import com.bytesw.bytebot.bean.SummaryMessageByIntentBean;
import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean;
import com.bytesw.xdf.sql.beans.Pagination;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class MessageJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessagesInRange", params);
} finally {
session.close();
}
}
public int countMessageInRangeHour(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessagesInRangeForHour", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getSummaryByIntentAndSentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("initLimit", pagination.getCurrentPage() * pagination.getItemsPerPage());
params.put("itemsForPage", pagination.getItemsPerPage());
if (pagination.getSortFields() != null && pagination.getSortFields().length > 0) {
params.put("columnSort", pagination.getSortFields()[0].getField());
params.put("directionSort", pagination.getSortFields()[0].getDirection().toUpperCase());
} else {
params.put("columnSort", "count");
params.put("directionSort", "DESC");
}
completeDates(params, pagination.getFilterExpression());
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntentAndSentence", params);
} finally {
session.close();
}
}
public List<SummaryMessageByIntentBean> getSummaryByIntent(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntent", params);
} finally {
session.close();
}
}
/**
* Metodo que consulta el total de mensajes con intent asociado
* @return
*/
public int countByIntentAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countByIntentAndRange", params);
} finally {
session.close();
}
}
/**
* Metodo que consulta el total de frases sin intent asociado
* @return
*/
public int countBySentencesAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countBySentencesAndRange", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getSummaryBySentence(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
params.put("initLimit", 0);
params.put("itemsForPage", 4);
params.put("columnSort", "count");
params.put("directionSort", "DESC");
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryBySentence", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getMessageBySentencePage(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("initLimit", pagination.getCurrentPage() * pagination.getItemsPerPage());
params.put("itemsForPage", pagination.getItemsPerPage());
if (pagination.getSortFields() != null && pagination.getSortFields().length > 0) {
params.put("columnSort", pagination.getSortFields()[0].getField());
params.put("directionSort", pagination.getSortFields()[0].getDirection().toUpperCase());
} else {
params.put("columnSort", "count");
params.put("directionSort", "DESC");
}
completeDates(params, pagination.getFilterExpression());
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryBySentence", params);
} finally {
session.close();
}
}
public int countSummaryBySentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
completeDates(params, pagination.getFilterExpression());
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countSummaryBySentence", params);
} finally {
session.close();
}
}
/**
* obtiene el promedio intenciones por cliente y rango de fechas
* @return
*/
public Double avgIntentsByCustomerAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.avgIntentsByCustomerAndRange", params);
} finally {
session.close();
}
}
/**
* Obtiene la cantidad por cada intención en un periodo de tiempo
* @return
*/
public List<MessageByIntentBean> countMessageByIntent(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessageByIntent", params);
} finally {
session.close();
}
}
public int countSummaryByIntentAndSentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
completeDates(params, pagination.getFilterExpression());
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countSummaryByIntentAndSentence", params);
} finally {
session.close();
}
}
public int countCustomersBySentence(String sentence) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sentence", sentence);
Object result = session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countCustomersBySentence", params);
if (result instanceof Double) {
return ((Double) result).intValue();
} else if (result instanceof Integer) {
return (Integer) result;
}
return 0;
} finally {
session.close();
}
}
private void completeDates(Map<String, Object> params, String filterString) {
if (filterString == null || filterString.isEmpty()) {
return;
}
String[] filters = filterString.split("&&");
if (filters != null) {
for (String filter : filters) {
String[] filterValue = filter.split("=");
params.put(filterValue[0], OffsetDateTime.ofInstant(Instant.ofEpochMilli(new Long(filterValue[1])), ZoneId.systemDefault()));
}
}
}
}
package com.bytesw.bytebot.jdbc;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
@Component
public class ResponseJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ResponseMapper.countMessagesInRange", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.AgentStatusConverter;
import com.bytesw.bytebot.model.converters.AgentTypeConverter;
import com.bytesw.bytebot.model.converters.LanguageConverter;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import lombok.*;
import org.hibernate.annotations.Type;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Audited
@Entity
@Getter @Setter @EqualsAndHashCode(of = "id")
@NoArgsConstructor
@Table(name = "avb_agent")
@NamedQuery(name = "Agent.findByPK", query = "Select u from AgencyAgent u where u.id = ?1")
public class Agent implements Serializable {
@Id
@Column(name = "agen_id")
@SequenceGenerator(name = "AVB_AGENT_GENERATOR", sequenceName = "AVB_AGENT_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_AGENT_GENERATOR")
private Long id;
@Column(name = "agen_iden")
private String name;
@Column(name = "agen_descr")
private String description;
@Column(name = "agen_vers")
private String version;
@Column(name = "agen_lang")
@Convert(converter = LanguageConverter.class)
private LanguageEnum language;
@Column(name = "agen_tzone")
private String timezone;
@Column(name = "agen_delete_sensible_period")
private int period;
@Lob
@Type(type = "org.hibernate.type.TextType")
@Basic(fetch = FetchType.LAZY)
@Column(name = "agen_avat")
private String avatar;
@ManyToOne
@JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
private Country country;
@Column(name = "agen_state")
@Convert(converter = AgentStatusConverter.class)
private AgentStatusEnum status;
@Column(name = "agen_type")
@Convert(converter = AgentTypeConverter.class)
private AgentTypeEnum type;
@OneToMany(mappedBy = "agent")
private List<DeploymentChannel> deploymentChannels;
@OneToMany(mappedBy = "agent")
private List<FrequentQuestion> frequentQuestions;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
@Audited
@Entity
@DiscriminatorValue(value=AnnualCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "AnnualCalendarException.findByPK", query = "Select u from AnnualCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class AnnualCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "Y";
@Column(name = "CALE_EXC_MONTH", nullable = false)
private int month;
@Column(name = "CALE_EXC_DAYMO", nullable = false)
private int dayOfMonth;
}
package com.bytesw.bytebot.model;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Getter
@Setter
@ToString
@Table(name = "avb_bcd_control")
@NamedQuery(name = "BdcControl.findByPK", query = "Select u from BdcControl u where u.id = ?1")
public class BdcControl implements Serializable {
@Id
@Column(name = "bcd_id")
@SequenceGenerator(name = "AVB_BCD_CONTROL_GENERATOR", sequenceName = "AVB_BCD_CONTROL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BCD_CONTROL_GENERATOR")
private Long id;
@Column(name = "bcd_uuid")
private String uuid;
@Column(name = "bcd_file")
private String fileName;
@Column(name = "bcd_file_id")
private Long fileId;
@Column(name = "bcd_status")
private String status;
@Column(name = "bcd_user")
private String user;
@Column(name = "bcd_date")
private String date;
}
package com.bytesw.bytebot.model;
import com.bytesw.xdf.model.converter.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
@Audited
@Entity
@Table(name = "AVB_BUSINESS_PARAMETER")
@NamedQuery(name = "BusinessParameter.findByPK", query = "Select u from BusinessParameter u where u.id = ?1")
@Getter @Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class BusinessParameter implements Serializable {
@Id
@Column(name = "BUPA_ID")
@SequenceGenerator(name = "AVB_BUSINESS_PARAMETER_GENERATOR", sequenceName = "AVB_BUSINESS_PARAMETER_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BUSINESS_PARAMETER_GENERATOR")
private BigInteger id;
@Version
@Column(name = "VERSION")
@Basic(optional = false)
private long version;
@Column(name = "BUPA_KEY", nullable = false, unique = true)
private String key;
@Column(name = "BUPA_DESCR", nullable = false)
private String description;
@Column(name = "BUPA_REQUI", nullable = false)
@Convert(converter = BooleanToStringConverter.class)
private Boolean required;
@Column(name = "BUPA_DEFVA")
private String defaultValue;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
@Audited
@Entity
@Table(name = "AVB_BUSINESS_PARAMETER_CONFIG")
@NamedQuery(name = "BusinessParameterConfiguration.findByPK", query = "Select u from BusinessParameterConfiguration u where u.id = ?1")
@Getter @Setter @EqualsAndHashCode @ToString(exclude = "id")
public class BusinessParameterConfiguration implements Serializable, Comparable<BusinessParameterConfiguration> {
@Id
@Column(name = "BUPC_ID")
@SequenceGenerator(name = "AVB_BUSINESS_PARAMETER_CONFIG_GEN", sequenceName = "AVB_BUSINESS_PARAMETER_CONFIG_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BUSINESS_PARAMETER_CONFIG_GEN")
private BigInteger id;
@Version
@Column(name = "VERSION")
@Basic(optional = false)
private long version;
@Column(name = "BUPC_FROM", nullable = false)
private OffsetDateTime from;
@Column(name = "BUPC_TO")
private OffsetDateTime to;
@Column(name = "BUPC_VALUE", nullable = false)
private String value;
@ManyToOne(optional = false)
@JoinColumn(name = "BUPA_ID", referencedColumnName = "BUPA_ID", nullable = false)
private BusinessParameter businessParameter;
@Override
public int compareTo(BusinessParameterConfiguration o) {
return from.compareTo(o.getFrom());
}
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Audited
@Entity
@Table(name = "AVB_CALENDAR")
@NamedQuery(name = "Calendar.findByPK", query = "Select u from Calendar u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class Calendar implements Serializable {
@Id
@Column(name = "cale_id")
private String id;
@Version
@Column(name = "cale_version")
@Basic(optional = false)
private long version;
@Column(name = "cale_name", nullable = false)
private String name;
// @OneToMany(mappedBy = "calendar")
// private List<WeekScheduler> weekSchedulerList;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.CalendarExceptionTypeConverter;
import com.bytesw.bytebot.model.converters.FrequencyTypeConverter;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
@Audited
@Entity
@Inheritance(
strategy = InheritanceType.SINGLE_TABLE
)
@DiscriminatorColumn(name="CALE_EXC_FRECU", discriminatorType = DiscriminatorType.STRING)
@Table(name = "AVB_CALENDAR_EXCEPTION")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public abstract class CalendarException implements Serializable {
@Id
@Column(name = "CALE_EXC_ID")
@SequenceGenerator(name = "AVB_CALENDAR_EXCEPTION_GENERATOR", sequenceName = "AVB_CALENDAR_EXCEPTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CALENDAR_EXCEPTION_GENERATOR")
private BigInteger id;
@Version
@Column(name = "CALE_EXC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "CALE_EXC_TYPE")
@Convert(converter = CalendarExceptionTypeConverter.class)
private CalendarExceptionType calendarExceptionType;
@Column(name = "CALE_EXC_FRECU", insertable = false, updatable = false)
private String frequencyType;
@Column(name = "CALE_EXC_DESCR")
private String description;
@ManyToOne(optional = false)
@JoinColumn(name = "CALE_ID", referencedColumnName = "CALE_ID", nullable = false)
private Calendar calendar;
}
\ No newline at end of file
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.CalendarExceptionTypeConverter;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@Entity
@Inheritance(
strategy = InheritanceType.SINGLE_TABLE
)
@DiscriminatorColumn(name="CALE_EXC_FRECU", discriminatorType = DiscriminatorType.STRING)
@Table(name = "AVB_CALENDAR_EXCEPTION")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class CalendarExceptionFull implements Serializable {
@Id
@Column(name = "CALE_EXC_ID")
@SequenceGenerator(name = "AVB_CALENDAR_EXCEPTION_GENERATOR", sequenceName = "AVB_CALENDAR_EXCEPTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CALENDAR_EXCEPTION_GENERATOR")
private BigInteger id;
@Version
@Column(name = "CALE_EXC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "CALE_EXC_TYPE")
@Convert(converter = CalendarExceptionTypeConverter.class)
private CalendarExceptionType calendarExceptionType;
@Column(name = "CALE_EXC_FRECU", insertable = false, updatable = false)
private String frequencyType;
@Column(name = "CALE_EXC_DESCR")
private String description;
@Column(name = "CALE_ID")
private String calendarID;
@Column(name = "CALE_EXC_MONTH")
private BigInteger month;
@Column(name = "CALE_EXC_DAYMO")
private BigInteger dayOfMonth;
@Column(name = "CALE_EXC_WEEK")
private BigInteger weekOfMonth;
@Column(name = "CALE_EXC_DAYWE")
private BigInteger dayOfWeek;
@Column(name = "CALE_EXC_DATE")
private LocalDate date;
@Column(name = "CALE_EXC_FROM")
private OffsetDateTime from;
@Column(name = "CALE_EXC_TO")
private OffsetDateTime to;
}
\ No newline at end of file
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Table(name = "AVB_CHANNEL")
@Getter @Setter @ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class Channel {
@Id
@Column(name = "CHAN_ID")
@SequenceGenerator(name = "AVB_CHANNEL_GENERATOR", sequenceName = "AVB_CHANNEL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CHANNEL_GENERATOR")
private Long id;
@Column(name = "CHAN_IDEN")
private String name;
@Column(name = "CHAN_IMAG")
private String image;
@OneToMany(mappedBy = "channel")
private List<ChannelParam> parameters;
@Column(name = "CHAN_TITLE")
private String suggestTitle;
@Column(name = "CHAN_DETAIL")
private String suggestDetail;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Table(name = "AVB_CHANNEL_PARAM")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class ChannelParam {
@Id
@Column(name = "CHPA_ID")
@SequenceGenerator(name = "AVB_CHANNEL_PARAM_GENERATOR", sequenceName = "AVB_CHANNEL_PARAM_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CHANNEL_PARAM_GENERATOR")
private Long id;
@Column(name = "CHPA_IDEN")
private String name;
@ManyToOne
@JoinColumn(name = "CHAN_ID",referencedColumnName = "CHAN_ID")
private Channel channel;
@Column(name = "CHPA_ORDER")
private Integer order;
@Column(name = "CHPA_REQU")
@Convert(converter = BooleanToStringConverter.class)
private boolean required;
@Column(name = "CHPA_LABEL")
private String label;
@Column(name = "CHPA_TRADU")
private String traductions;
@Column(name = "CHPA_TYPE")
private String type;
@Column(name = "CHPA_MAXLE")
private Integer maxlength;
@Column(name = "CHPA_REGEX")
private String regex;
}
package com.bytesw.bytebot.model;
import lombok.*;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.List;
@Audited
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@Table(name = "avb_country")
@NamedQuery(name = "Country.findByPK", query = "Select u from Country u where u.id = ?1")
public class Country {
@Id
@Column(name = "coun_id")
@SequenceGenerator(name = "AVB_COUNTRY_GENERATOR", sequenceName = "AVB_COUNTRY_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_COUNTRY_GENERATOR")
private Long id;
@Column(name = "coun_name", nullable = false)
private String name;
@OneToMany(mappedBy = "country")
private List<Timezone> timezones;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.StatusConverter;
import com.bytesw.bytebot.model.enums.StatusEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Table(name = "AVB_DEPLOYMENT_CHANNEL")
@Getter
@Setter
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class DeploymentChannel {
@Id
@Column(name = "DCHA_ID")
@SequenceGenerator(name = "AVB_DEPLOYMENT_CHANNEL_GENERATOR", sequenceName = "AVB_DEPLOYMENT_CHANNEL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_DEPLOYMENT_CHANNEL_GENERATOR")
private Long id;
@Column(name = "DCHA_NAME")
private String name;
@ManyToOne
@JoinColumn(name = "AGEN_ID", referencedColumnName = "AGEN_ID")
private Agent agent;
@Column(name = "DCHA_STATE")
@Convert(converter = StatusConverter.class)
private StatusEnum status;
@ManyToOne
@JoinColumn(name = "CHAN_ID", referencedColumnName = "CHAN_ID")
private Channel channel;
@OneToMany(mappedBy = "deploymentChannel")
private List<DeploymentChannelParamValue> parameters;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Table(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class DeploymentChannelParamValue {
@Id
@Column(name = "CHPV_ID")
@SequenceGenerator(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR", sequenceName = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR")
private Long id;
@ManyToOne
@JoinColumn(name = "CHPA_ID", referencedColumnName = "CHPA_ID")
private ChannelParam parameter;
@ManyToOne
@JoinColumn(name = "DCHA_ID", referencedColumnName = "DCHA_ID")
private DeploymentChannel deploymentChannel;
@Column(name = "CHPV_VALUE")
private String value;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.FrequentQuestionStatusConverter;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.time.LocalDateTime;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Table(name = "AVB_FREQUENT_QUESTION")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
@NamedQuery(name = "FrequentQuestion.findByPK", query = "Select u from FrequentQuestion u where u.id = ?1")
public class FrequentQuestion {
@Id
@Column(name = "FQUE_ID")
@SequenceGenerator(name = "AVB_FREQUENT_QUESTION_GENERATOR", sequenceName = "AVB_FREQUENT_QUESTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_FREQUENT_QUESTION_GENERATOR")
private Long id;
@Column(name = "FQUE_UUID")
private String uuid;
@Column(name = "FQUE_NAME")
private String filename;
@Column(name = "FQUE_DESC")
private String description;
@Column(name = "FQUE_STATE")
@Convert(converter = FrequentQuestionStatusConverter.class)
private FrequentQuestionStatusEnum status;
@ManyToOne
@JoinColumn(name = "AGEN_ID", referencedColumnName = "AGEN_ID")
private Agent agent;
@Column(name = "FQUE_USER")
private String user;
@Column(name = "FQUE_LDATE", columnDefinition = "TIMESTAMP")
private LocalDateTime uploadDate;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
@Audited
@Entity
@Table(name = "avb_process_etl")
@NamedQuery(name = "ProcessETL.findByPK", query = "Select u from ProcessETL u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class ProcessETL implements Serializable {
@Id
@Column(name = "etl_id")
private int id;
@Version
@Column(name = "etl_version")
@Basic(optional = false)
private long version;
@Column(name = "etl_name", nullable = false)
private String name;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model;
import java.time.LocalDateTime;
import javax.persistence.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Type;
import org.hibernate.envers.Audited;
@Audited
@Entity
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
@NoArgsConstructor
@Table(name = "AVB_QUESTION_FILE")
@NamedQuery(name = "QuestionFile.findByPK", query = "Select u from QuestionFile u where u.id = ?1")
public class QuestionFile {
@Id
@Column(name = "QUFI_ID")
@SequenceGenerator(name = "AVB_QUESTION_FILE_GENERATOR", sequenceName = "AVB_QUESTION_FILE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_QUESTION_FILE_GENERATOR")
private Long id;
@Column(name = "QUFI_UUID", nullable = false)
private String uuid;
@Column(name = "QUFI_NAME", nullable = false)
private String name;
@Column(name = "QUFI_SIZE", nullable = false)
private Long size;
@Column(name = "QUFI_UDATE", columnDefinition = "TIMESTAMP")
private LocalDateTime uploadDate;
@Type(type="org.hibernate.type.BinaryType")
@Basic(fetch = FetchType.LAZY)
@Column(name = "QUFI_DATA", length= 100000, nullable = false)
private byte[] data;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import java.time.OffsetDateTime;
@Audited
@Entity
@DiscriminatorValue(value= RangeCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "RangeCalendarException.findByPK", query = "Select u from RangeCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class RangeCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "R";
@Column(name = "CALE_EXC_FROM", nullable = false)
private OffsetDateTime from;
@Column(name = "CALE_EXC_TO", nullable = false)
private OffsetDateTime to;
}
\ No newline at end of file
package com.bytesw.bytebot.model;
import com.bytesw.xdf.model.converter.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
@Audited
@Entity
@Table(name = "AVB_SCHEDULER_TASK")
@NamedQuery(name = "SchedulerTask.findByPK", query = "Select u from SchedulerTask u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class SchedulerTask implements Serializable {
@Id
@Column(name = "SHTA_ID")
@SequenceGenerator(name = "AVB_SCHEDULER_TASK_GENERATOR", sequenceName = "AVB_SCHEDULER_TASK_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_SCHEDULER_TASK_GENERATOR")
private BigInteger id;
@Version
@Column(name = "SHTA_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "SHTA_DESCR", nullable = false)
private String description;
@Column(name = "SHTA_INTER", nullable = false)
@Convert(converter = BooleanToStringConverter.class)
private Boolean internals;
@Column(name = "SHTA_CROEX", nullable = false)
private String cronExpression;
@Column(name = "SHTA_PARAM")
private String stringParameters;
@Column(name= "cale_id")
private String calendarID;
// @ManyToOne(optional = false)
// @NotFound(action = NotFoundAction.IGNORE)
// @JoinColumn(name = "CALE_ID", referencedColumnName = "CALE_ID", nullable = false)
// private Calendar calendar;
/*@ManyToOne(optional = false)
@JoinColumn(name = "ETL_ID", referencedColumnName = "ETL_ID", nullable = false)
private ProcessETL processETL;*/
@Column(name = "etl_id")
private Integer processETL;
}
package com.bytesw.bytebot.model;
import lombok.*;
import org.hibernate.envers.Audited;
import javax.persistence.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Audited
@Entity
@Getter @Setter
@NoArgsConstructor
@Table(name = "avb_timezone")
@NamedQuery(name = "Timezone.findByPK", query = "Select u from Timezone u where u.id = ?1")
public class Timezone {
@Id
@Column(name = "tzon_id")
@SequenceGenerator(name = "avb_timezone_generator", sequenceName = "AVB_TIMEZONE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "avb_timezone_generator")
private Long id;
@Column(name = "tzon_zone", nullable = false)
private String timezone;
@ManyToOne
@JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
private Country country;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import java.time.LocalDate;
@Audited
@Entity
@DiscriminatorValue(value= UniqueCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "UniqueCalendarException.findByPK", query = "Select u from UniqueCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class UniqueCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "U";
@Column(name = "CALE_EXC_DATE", nullable = true)
private LocalDate date;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
@Audited
@Entity
@DiscriminatorValue(value= UniqueWeeklyCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "UniqueWeeklyCalendarException.findByPK", query = "Select u from UniqueWeeklyCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class UniqueWeeklyCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "W";
@Column(name = "CALE_EXC_MONTH", nullable = false)
private int month;
@Column(name = "CALE_EXC_WEEK", nullable = false)
private int weekOfMonth;
@Column(name = "CALE_EXC_DAYWE", nullable = false)
private int dayOfWeek;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
@Audited
@Entity
@Table(name = "AVB_WEEK_SCHEDULER")
@NamedQuery(name = "WeekScheduler.findByPK", query = "Select u from WeekScheduler u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "calendar")
public class WeekScheduler implements Serializable {
@Id
@Column(name = "WESC_ID")
@SequenceGenerator(name = "AVB_WEEK_SCHEDULER_GENERATOR", sequenceName = "AVB_WEEK_SCHEDULER_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_WEEK_SCHEDULER_GENERATOR")
private BigInteger id;
@Version
@Column(name = "WESC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "WESC_DAY", nullable = false)
private int dayOfWeek;
@Column(name = "WESC_FROM", nullable = false)
private OffsetTime from;
@Column(name = "WESC_TO", nullable = false)
private OffsetTime to;
@Column(name = "CALE_ID")
private String calendarID;
// @ManyToOne(optional = false)
// @NotFound(action = NotFoundAction.IGNORE)
// @JoinColumn(name = "cale_id", referencedColumnName = "cale_id", nullable = false)
// private Calendar calendar;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "ag_agents")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AgencyAgent {
@Id
@Column(name = "agent_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "agent_name", length = 30)
private String name;
@Column(name = "agent_lastname", length = 30)
private String lastname;
@Column(name = "agent_details", length = 255)
private String details;
@Column(name = "agent_deleted_at")
private LocalDate deletedAt;
@OneToOne(cascade = CascadeType.ALL)
private User user;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "ag_aircrafts")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Aircraft {
@Id
@Column(name = "aircraft_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "aircraft_name", length = 30)
private String name;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "ag_airlines")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Airline {
@Id
@Column(name = "airline_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "airline_name", length = 30)
private String name;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "ag_airports")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Airport {
@Id
@Column(name = "airport_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "airport_name")
private String name;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "ag_costs")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Cost {
@Id
@Column(name = "cost_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "flight_id", referencedColumnName = "flight_id")
private Flight flight;
@Column(name = "cost_departure_date")
private LocalDateTime departureDate;
@Column(name = "cost_arrival_date")
private LocalDateTime arrivalDate;
@Column(name = "cost_amount", precision = 10, scale = 2)
private Double amount;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "ag_flights")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Flight {
@Id
@Column(name = "flight_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "airline_id", referencedColumnName = "airline_id")
private Airline airline;
@ManyToOne
@JoinColumn(name = "aircraft_id", referencedColumnName = "aircraft_id")
private Aircraft aircraft;
@ManyToOne
@JoinColumn(name = "airport_origin_id", referencedColumnName = "airport_id")
private Airport airportOrigin;
@ManyToOne
@JoinColumn(name = "airport_destination_id", referencedColumnName = "airport_id")
private Airport airportDestination;
@Column(name = "flight_departure_date")
private LocalDateTime departureDate;
@Column(name = "flight_arrival_date")
private LocalDateTime arrivalDate;
@OneToMany(cascade = CascadeType.ALL)
private List<Scale> scales;
@OneToMany(cascade = CascadeType.ALL)
private List<Cost> costs;
@Column(name = "flight_deleted_at")
private LocalDate deletedAt;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "ag_passengers")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Passenger {
@Id()
@Column(name = "passenger_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "passenger_name", length = 30)
private String name;
@Column(name = "passenger_lastname", length = 30)
private String lastname;
@Column(name = "passenger_phone", length = 12)
private String phone;
@Column(name = "passenger_country", length = 30)
private String country;
@Column(name = "passenger_city", length = 30)
private String city;
@Column(name = "passenger_address")
private String address;
@Column(name = "passenger_deleted_at")
private LocalDate deletedAt;
@OneToOne(cascade = CascadeType.ALL)
private User user;
}
package com.bytesw.bytebot.model.agency;
import com.bytesw.bytebot.model.agency.converters.PaymentStatusConverter;
import com.bytesw.bytebot.model.agency.enums.PaymentStatusEnum;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Date;
@Entity
@Table(name = "ag_payments")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Payment {
@Id
@Column(name = "payment_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "payment_status")
@Convert(converter = PaymentStatusConverter.class)
private PaymentStatusEnum status;
@Column(name = "payment_amount", precision = 10, scale = 2)
private Double amount;
@Column(name = "payment_date")
private LocalDate date;
}
package com.bytesw.bytebot.model.agency;
import com.bytesw.bytebot.model.agency.converters.ReservationStatusConverter;
import com.bytesw.bytebot.model.agency.converters.TicketTypeConverter;
import com.bytesw.bytebot.model.agency.converters.TravelClassConverter;
import com.bytesw.bytebot.model.agency.enums.ReservationStatusEnum;
import com.bytesw.bytebot.model.agency.enums.TicketTypeEnum;
import com.bytesw.bytebot.model.agency.enums.TravelClassEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.minidev.json.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonBackReference;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "ag_reservations")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Reservation {
@Id
@Column(name = "reservation_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "passenger_id", referencedColumnName = "passenger_id")
private Passenger passenger;
@ManyToOne
@JoinColumn(name = "agent_id", referencedColumnName = "agent_id")
private AgencyAgent agencyAgent;
@Column(name = "reservation_ticket_type")
@Convert(converter = TicketTypeConverter.class)
private TicketTypeEnum ticketType;
@Column(name = "reservation_travel_class")
@Convert(converter = TravelClassConverter.class)
private TravelClassEnum travelClass;
@Column(name = "reservation_status")
@Convert(converter = ReservationStatusConverter.class)
private ReservationStatusEnum status;
@Column(name = "reservation_departure_date")
private LocalDateTime departureDate;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "payment_id", referencedColumnName = "payment_id")
private Payment payment;
@ManyToOne
@JoinColumn(name = "flight_id", referencedColumnName = "flight_id")
private Flight flight;
@Column(name = "created_date")
private LocalDate createdDate;
@Column(name = "reservation_deleted_at")
private LocalDate deletedAt;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "ag_scales")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Scale {
@Id
@Column(name = "scale_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "flight_id", referencedColumnName = "flight_id")
private Flight flight;
@ManyToOne
@JoinColumn(name = "airport_origin_id", referencedColumnName = "airport_id")
private Airport airportOrigin;
@ManyToOne
@JoinColumn(name = "airport_destination_id", referencedColumnName = "airport_id")
private Airport airportDestination;
@Column(name = "scale_departure_date")
private LocalDateTime departureDate;
@Column(name = "scale_arrival_date")
private LocalDateTime arrivalDate;
}
package com.bytesw.bytebot.model.agency;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "ag_supervisors")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Supervisor {
@Id
@Column(name = "supervisor_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "supervisor_name", length = 30)
private String name;
@Column(name = "supervisor_lastname", length = 30)
private String lastname;
@Column(name = "supervisor_details", length = 255)
private String details;
@Column(name = "supervisor_deleted_at")
private LocalDate deletedAt;
@OneToOne(cascade = CascadeType.ALL)
private User user;
}
package com.bytesw.bytebot.model.agency;
import com.bytesw.bytebot.model.agency.converters.RoleConverter;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity
@Table(name = "ag_users")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "user_role")
@Convert(converter = RoleConverter.class)
private RoleEnum role;
@Column(name = "user_email", length = 100)
private String email;
@Column(name = "user_password", length = 45)
private String password;
}
package com.bytesw.bytebot.model.agency.converters;
import com.bytesw.bytebot.model.agency.enums.PaymentStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class PaymentStatusConverter implements AttributeConverter<PaymentStatusEnum, String> {
@Override
public String convertToDatabaseColumn(PaymentStatusEnum attribute) {
return attribute.getName();
}
@Override
public PaymentStatusEnum convertToEntityAttribute(String dbData) {
return PaymentStatusEnum.fromString(dbData);
}
}
package com.bytesw.bytebot.model.agency.converters;
import com.bytesw.bytebot.model.agency.enums.ReservationStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class ReservationStatusConverter implements AttributeConverter<ReservationStatusEnum, String> {
@Override
public String convertToDatabaseColumn(ReservationStatusEnum attribute) {
return attribute.getName();
}
@Override
public ReservationStatusEnum convertToEntityAttribute(String dbData) {
return ReservationStatusEnum.fromString(dbData);
}
}
package com.bytesw.bytebot.model.agency.converters;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class RoleConverter implements AttributeConverter<RoleEnum, String> {
@Override
public String convertToDatabaseColumn(RoleEnum userRole) {
return userRole.getName();
}
@Override
public RoleEnum convertToEntityAttribute(String s) {
return RoleEnum.fromString(s);
}
}
package com.bytesw.bytebot.model.agency.converters;
import com.bytesw.bytebot.model.agency.enums.TicketTypeEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class TicketTypeConverter implements AttributeConverter<TicketTypeEnum, String> {
@Override
public String convertToDatabaseColumn(TicketTypeEnum attribute) {
return attribute.getName();
}
@Override
public TicketTypeEnum convertToEntityAttribute(String dbData) {
return TicketTypeEnum.fromString(dbData);
}
}
package com.bytesw.bytebot.model.agency.converters;
import com.bytesw.bytebot.model.agency.enums.TravelClassEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class TravelClassConverter implements AttributeConverter<TravelClassEnum, String> {
@Override
public String convertToDatabaseColumn(TravelClassEnum attribute) {
return attribute.getName();
}
@Override
public TravelClassEnum convertToEntityAttribute(String dbData) {
return TravelClassEnum.fromString(dbData);
}
}
package com.bytesw.bytebot.model.agency.enums;
import com.bytesw.bytebot.model.enums.StatusEnum;
import java.util.HashMap;
import java.util.Map;
public enum PaymentStatusEnum {
PAID("PAID"),
CANCELED("CANCELED"),
WAITING("WAITING");
private static final Map<String, PaymentStatusEnum> map = new HashMap<>();
private final String name;
PaymentStatusEnum(String name) {
this.name = name;
}
public String getName() { return name; }
static {
for (PaymentStatusEnum type : PaymentStatusEnum.values()) {
map.put(type.getName(), type);
}
}
public static PaymentStatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.agency.enums;
import java.util.HashMap;
import java.util.Map;
public enum ReservationStatusEnum {
PAID("PAID"),
CANCELED("CANCELED"),
RESERVED("RESERVED");
private static final Map<String, ReservationStatusEnum> map = new HashMap<>();
private final String name;
ReservationStatusEnum(String name) {
this.name = name;
}
public String getName() { return name; }
static {
for (ReservationStatusEnum type : ReservationStatusEnum.values()) {
map.put(type.getName(), type);
}
}
public static ReservationStatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.agency.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum RoleEnum {
PASSENGER("PASSENGER"),
SUPERVISOR("SUPERVISOR"),
AGENT("AGENT");
private static final Map<String, RoleEnum> map = new HashMap<>();
private final String name;
RoleEnum(String name) {
this.name = name;
}
public String getName() { return name; }
static {
for (RoleEnum type : RoleEnum.values()) {
map.put(type.getName(), type);
}
}
public static RoleEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException("Role not found!");
}
}
package com.bytesw.bytebot.model.agency.enums;
import java.util.HashMap;
import java.util.Map;
public enum TicketTypeEnum {
FIRST_CLASS("FIRST-CLASS"),
ECONOMIC("ECONOMIC"),
BUSINESS("BUSINESS");
private static final Map<String, TicketTypeEnum> map = new HashMap<>();
private final String name;
TicketTypeEnum(String name) {
this.name = name;
}
public String getName() { return name; }
static {
for (TicketTypeEnum type : TicketTypeEnum.values()) {
map.put(type.getName(), type);
}
}
public static TicketTypeEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.agency.enums;
import java.util.HashMap;
import java.util.Map;
public enum TravelClassEnum {
FIRST_CLASS("FIRST-CLASS"),
ECONOMIC("ECONOMIC"),
BUSINESS("BUSINESS");
private static final Map<String, TravelClassEnum> map = new HashMap<>();
private final String name;
TravelClassEnum(String name) {
this.name = name;
}
public String getName() { return name; }
static {
for (TravelClassEnum type : TravelClassEnum.values()) {
map.put(type.getName(), type);
}
}
public static TravelClassEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class AgentStatusConverter implements AttributeConverter<AgentStatusEnum, String> {
@Override
public String convertToDatabaseColumn(AgentStatusEnum value) {
return value.getName();
}
@Override
public AgentStatusEnum convertToEntityAttribute(String value) {
return AgentStatusEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class AgentTypeConverter implements AttributeConverter<AgentTypeEnum, String> {
@Override
public String convertToDatabaseColumn(AgentTypeEnum agentTypeEnum) {
if (agentTypeEnum == null) return null;
return agentTypeEnum.getName();
}
@Override
public AgentTypeEnum convertToEntityAttribute(String s) {
return AgentTypeEnum.fromString(s);
}
}
package com.bytesw.bytebot.model.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {
public BooleanToStringConverter() {
}
public String convertToDatabaseColumn(Boolean value) {
return value != null && value ? "Y" : "N";
}
public Boolean convertToEntityAttribute(String value) {
return "Y".equals(value);
}
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* @author Renzo Carranza
* @version 26/08/2021
* <p>
* Copyright (c) 2019 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class CalendarExceptionTypeConverter implements AttributeConverter<CalendarExceptionType, String> {
@Override
public String convertToDatabaseColumn(CalendarExceptionType calendarExceptionType) {
if (calendarExceptionType == null) return null;
return calendarExceptionType.getName();
}
@Override
public CalendarExceptionType convertToEntityAttribute(String s) {
return CalendarExceptionType.fromString(s);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.FileQuestionStatusEnum;
import javax.persistence.AttributeConverter;
import org.apache.camel.Converter;
/**
* @author Hernán Uriarte Melchor
* @version 13-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class FileQuestionStatusConverter implements AttributeConverter<FileQuestionStatusEnum, String> {
@Override
public String convertToDatabaseColumn(FileQuestionStatusEnum value) {
return value.getName();
}
@Override
public FileQuestionStatusEnum convertToEntityAttribute(String value) {
return FileQuestionStatusEnum.fromString(value);
}
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.FrequencyType;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class FrequencyTypeConverter implements AttributeConverter<FrequencyType, String> {
@Override
public String convertToDatabaseColumn(FrequencyType frequencyType) {
if (frequencyType == null) return null;
return frequencyType.getName();
}
@Override
public FrequencyType convertToEntityAttribute(String s) {
return FrequencyType.fromString(s);
}
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class FrequentQuestionStatusConverter implements AttributeConverter<FrequentQuestionStatusEnum, String> {
@Override
public String convertToDatabaseColumn(FrequentQuestionStatusEnum value) {
if (value == null) {
return null;
}
return value.getName();
}
@Override
public FrequentQuestionStatusEnum convertToEntityAttribute(String value) {
return FrequentQuestionStatusEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class LanguageConverter implements AttributeConverter<LanguageEnum, String> {
@Override
public String convertToDatabaseColumn(LanguageEnum value) {
return value.getName();
}
@Override
public LanguageEnum convertToEntityAttribute(String value) {
return LanguageEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.StatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class StatusConverter implements AttributeConverter<StatusEnum, String> {
@Override
public String convertToDatabaseColumn(StatusEnum value) {
if (value == null) {
return null;
}
return value.getName();
}
@Override
public StatusEnum convertToEntityAttribute(String value) {
return StatusEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum AgentParameterEnum {
ACCESS_ID("account-identifier"),
ACCESS_TOKEN("authentication-token"),
ACCESS_TWILIO("twillio-number");
private static final Map<String, AgentParameterEnum> map = new HashMap<>();
private String name;
AgentParameterEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (AgentParameterEnum type : AgentParameterEnum.values()) {
map.put(type.name, type);
}
}
public static AgentParameterEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
public enum AgentStatusEnum {
CREATED("CR"),
PENDING_SYNCHRONIZED("PS"),
DEPLOYED("DP"),
DELETED("DE");
private static final Map<String, AgentStatusEnum> map = new HashMap<>();
private String name;
AgentStatusEnum(String name) {
this.name = name;
}
static {
for (AgentStatusEnum type : AgentStatusEnum.values()) {
map.put(type.name, type);
}
}
public static AgentStatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum AgentTypeEnum {
FREQUENT_QUESTION("FQ");
private final String name;
private static final Map<String, AgentTypeEnum> map = new HashMap<>();
static {
for (AgentTypeEnum type : AgentTypeEnum.values()) {
map.put(type.name, type);
}
}
AgentTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static AgentTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum CalendarExceptionType {
HOLIDAY("H"), WORK_EXCEPTION("W"), NO_WORK_EXCEPTION("N");
private final String name;
private static final Map<String, CalendarExceptionType> map = new HashMap<>();
static {
for (CalendarExceptionType type : CalendarExceptionType.values()) {
map.put(type.name, type);
}
}
CalendarExceptionType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static CalendarExceptionType fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum ChannelEnum {
WHATSAPP("WhatsApp"),
MESSENGER("Facebook Messenger");
private static final Map<String, ChannelEnum> map = new HashMap<>();
private String name;
ChannelEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (ChannelEnum type : ChannelEnum.values()) {
map.put(type.name, type);
}
}
public static ChannelEnum fromString(String name) {
return map.get(name);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
/**
* @author Hernán Uriarte Melchor
* @version 13-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
public enum FileQuestionStatusEnum {
ACTIVE("AC"),
LOADED("LO"),
DISABLED("DI");
private static final Map<String, FileQuestionStatusEnum> map = new HashMap<>();
private String name;
FileQuestionStatusEnum(String name) {
this.name = name;
}
static {
for (FileQuestionStatusEnum type : FileQuestionStatusEnum.values()) {
map.put(type.name, type);
}
}
public static FileQuestionStatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import com.bytesw.bytebot.model.AnnualCalendarException;
import com.bytesw.bytebot.model.RangeCalendarException;
import com.bytesw.bytebot.model.UniqueCalendarException;
import com.bytesw.bytebot.model.UniqueWeeklyCalendarException;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum FrequencyType {
ANNUAL(AnnualCalendarException.DISCRIMINATOR_VALUE),
UNIQUE(UniqueCalendarException.DISCRIMINATOR_VALUE),
UniqueWeekly(UniqueWeeklyCalendarException.DISCRIMINATOR_VALUE),
RANGE(RangeCalendarException.DISCRIMINATOR_VALUE);
private final String name;
private static final Map<String, FrequencyType> map = new HashMap<>();
static {
for (FrequencyType type : FrequencyType.values()) {
map.put(type.name, type);
}
}
FrequencyType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static FrequencyType fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
public enum FrequentQuestionStatusEnum {
PENDING_SYNCHRONIZED("PS"),
UPLOADED("LO"),
DELETED("DE"),
ERROR("ER"),
CORRECTO("OK");
private static final Map<String, FrequentQuestionStatusEnum> map = new HashMap<>();
private String name;
FrequentQuestionStatusEnum(String name) {
this.name = name;
}
static {
for (FrequentQuestionStatusEnum type : FrequentQuestionStatusEnum.values()) {
map.put(type.name, type);
}
}
public static FrequentQuestionStatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum LanguageEnum {
SPANISH("ES");
private final String name;
private static final Map<String, LanguageEnum> map = new HashMap<>();
static {
for (LanguageEnum type : LanguageEnum.values()) {
map.put(type.name, type);
}
}
LanguageEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static LanguageEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum MetricMessageTypeEnum {
RECEIVED("received"),
SENT("sent"),
SESSION("session");
private static final Map<String, MetricMessageTypeEnum> map = new HashMap<>();
private String name;
MetricMessageTypeEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (MetricMessageTypeEnum type : MetricMessageTypeEnum.values()) {
map.put(type.name, type);
}
}
public static MetricMessageTypeEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum ProcessETLEnum {
PROCESS_DELETE ( "Eliminación de Data Sensible");
private final String name;
private static final Map<String, ProcessETLEnum> map = new HashMap<>();
static {
for (ProcessETLEnum type : ProcessETLEnum.values()) {
map.put(type.name, type);
}
}
ProcessETLEnum (String name) {
this.name = name;
}
public String getName() {
return name;
}
public static ProcessETLEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum ProviderErrorEnum {
AUTHENTICATE("Authenticate"),
CONEXION("name resolution");
private static final Map<String, ProviderErrorEnum> map = new HashMap<>();
private String name;
ProviderErrorEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (ProviderErrorEnum type : ProviderErrorEnum.values()) {
map.put(type.name, type);
}
}
public static ProviderErrorEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum StatusBcdEnum {
CARGANDO("Cargando"),
CARGADO("Cargado"),
INDEXANDO("Indexando"),
INDEXADO("Indexado");
private static final Map<String, StatusBcdEnum> map = new HashMap<>();
private String name;
StatusBcdEnum(String name) {
this.name = name;
}
static {
for (StatusBcdEnum type : StatusBcdEnum.values()) {
map.put(type.name, type);
}
}
public static StatusBcdEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Getter
public enum StatusEnum {
ACTIVE("AC"),
INACTIVE("IN"),
DELETED("DE");
private static final Map<String, StatusEnum> map = new HashMap<>();
private String name;
StatusEnum(String name) {
this.name = name;
}
static {
for (StatusEnum type : StatusEnum.values()) {
map.put(type.name, type);
}
}
public static StatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface AgentRepository extends CrudRepository<Agent, Long>, JpaSpecificationExecutor<Agent> {
List<Agent> findByStatus(AgentStatusEnum status);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.BdcControl;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface BdcControlRepository extends CrudRepository<BdcControl, Long>, JpaSpecificationExecutor<BdcControl> {
@Query("select s from BdcControl s where s.uuid = :uuid")
Optional<BdcControl> findByUuid(@Param("uuid") String uuid);
}
package com.bytesw.bytebot.repository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface BusinessParameterConfigurationRepository extends CrudRepository<BusinessParameterConfiguration, BigInteger>, JpaSpecificationExecutor<BusinessParameterConfiguration> {
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :fromDate and b.to >= :fromDate) OR (b.to is null))")
List<BusinessParameterConfiguration> findValidByKey(@Param("key") String key, @Param("fromDate") OffsetDateTime fromDate);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :currentDate and b.to >= :currentDate) OR (b.from < :currentDate and b.to is null))")
Optional<BusinessParameterConfiguration> findCurrentValueByKey(@Param("key") String key, @Param("currentDate") OffsetDateTime currentDate);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id")
List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameter(@Param("id") BigInteger id);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id and (b.to > :toDate or b.to is null) order by b.from desc")
List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameterWithLowestDateFrom(@Param("id") BigInteger id, @Param("toDate") OffsetDateTime toDate);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.BusinessParameter;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.Optional;
/**
* @author Renzo Carranza
* @version 26/08/2021
* <p>
* Copyright (c) 2019 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface BusinessParameterRepository extends CrudRepository<BusinessParameter, BigInteger>, JpaSpecificationExecutor<BusinessParameter> {
@Query("select b from BusinessParameter b where b.key = :key")
Optional<BusinessParameter> findByKey(@Param("key") String key);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.CalendarExceptionFull;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface CalendarExceptionFullRepository extends CrudRepository<CalendarExceptionFull, BigInteger>, JpaSpecificationExecutor<CalendarExceptionFull> {
@Query("select s from CalendarExceptionFull s where s.calendarID = :calendarId")
Optional<List<CalendarExceptionFull>> findByCalendarId(@Param("calendarId") String calendarId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface CalendarExceptionRepository extends CrudRepository<CalendarException, BigInteger>, JpaSpecificationExecutor<CalendarException> {
@Query("select s from RangeCalendarException s where s.calendar.id = :calendarId and s.from < :date and s.to > :date and s.calendarExceptionType = :type")
Optional<CalendarException> findByRangeExceptionByCalendarIdAndDateAndType(@Param("calendarId") String calendarId, @Param("date") OffsetDateTime date, @Param("type") CalendarExceptionType type);
@Query("select s from AnnualCalendarException s where s.calendar.id = :calendarId and s.month = :month and s.dayOfMonth = :dayOfMonth")
Optional<CalendarException> findByAnnualExceptionByCalendarIdAndYearAndDay(@Param("calendarId") String calendarId, @Param("month") int month, @Param("dayOfMonth") int dayOfMonth);
@Query("select s from UniqueCalendarException s where s.calendar.id = :calendarId and s.date = :date")
Optional<CalendarException> findByUniqueExceptionByCalendarIdAndDate(@Param("calendarId") String calendarId, @Param("date") LocalDate date);
@Query("select s from UniqueWeeklyCalendarException s where s.calendar.id = :calendarId and s.month = :month and s.dayOfWeek = :dayOfWeek and s.weekOfMonth = :weekOfMonth")
Optional<CalendarException> findByUniqueWeeklyExceptionByCalendarIdAndDayOfWeekAndWeekOfMonth(@Param("calendarId") String calendarId, @Param("month") int month, @Param("dayOfWeek") int dayOfWeek, @Param("weekOfMonth") int weekOfMonth);
@Query("select s from RangeCalendarException s where s.calendar.id = :calendarId and s.from >= :date and s.calendarExceptionType = :type")
Optional<CalendarException> findByRangeExceptionByCalendarIdFromDateAndType(@Param("calendarId") String calendarId, @Param("date") OffsetDateTime date, @Param("type") CalendarExceptionType type);
@Query("select s from CalendarException s where s.calendar.id = :calendarId")
Optional<List<CalendarException>> findByCalendarId(@Param("calendarId") String calendarId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Calendar;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
public interface CalendarRepository extends CrudRepository<Calendar, String>, JpaSpecificationExecutor<Calendar> {
}
\ No newline at end of file
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface ChannelParamRepository extends CrudRepository<ChannelParam, Long> {
Optional<ChannelParam> findByNameAndChannelId(String name, Long id);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Channel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface ChannelRepository extends CrudRepository<Channel, Long> {
Optional<Channel> findByName(String name);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Country;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface CountryRepository extends CrudRepository<Country, Long> {
@Query("select c from Country c order by c.name")
List<Country> findAllOrder();
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface DeploymentChannelParamValueRepository extends CrudRepository<DeploymentChannelParamValue, Long> {
@Query("select d from DeploymentChannelParamValue d where d.deploymentChannel.id = :id order by d.id asc")
List<DeploymentChannelParamValue> getParameter(@Param("id") Long id);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannel;
import org.springframework.data.repository.CrudRepository;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface DeploymentChannelRepository extends CrudRepository<DeploymentChannel, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannel;
import com.bytesw.bytebot.model.FrequentQuestion;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface FrequentQuestionRepository extends CrudRepository<FrequentQuestion, Long> {
public List<FrequentQuestion> findAllByAgentIdAndStatus(Long id, FrequentQuestionStatusEnum status);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.GoalForActions;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;
public interface GoalForActionsRepository extends CrudRepository<GoalForActions, Long>, JpaSpecificationExecutor<GoalForActions> {
@Query("select s from GoalForActions s where s.goalId= :goalId")
Optional<List<GoalForActions>> findGoalForActionsByGoalId(@Param("goalId") Long goalId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.Goal;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface GoalRepository extends CrudRepository<Goal, Long>, JpaSpecificationExecutor<Goal> {
@Query("select s from Goal s where s.agenId = :agentId and s.identifier = :identifier")
Optional<Goal> findByAgentAndIdent(@Param("agentId") Long agentId, @Param("identifier") String identifier);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.ProcessETL;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface ProcessETLRepository extends CrudRepository<ProcessETL, Integer>, JpaSpecificationExecutor<ProcessETL> {
@Query("select b from ProcessETL b where b.name = :etlName")
ProcessETL findByName(@Param("etlName") String etlName);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.QuestionFile;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.Optional;
/**
* @author Hernán Uriarte Melchor.
* @version 13-sep-2020
* <p>
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface QuestionFileRepository extends CrudRepository<QuestionFile, Long> {
public Optional<QuestionFile> findByUuid(String uuid);
@Query("Select q.uploadDate from QuestionFile q where q.uuid = :uuid")
LocalDateTime findUploadDateByUuid(@Param("uuid") String uuid);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.SchedulerTask;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
public interface SchedulerTaskRepository extends CrudRepository<SchedulerTask, BigInteger>, JpaSpecificationExecutor<SchedulerTask> {
@Query("select b from SchedulerTask b where b.calendarID = :calendarId")
Optional<List<SchedulerTask>> findByCalendarId(@Param("calendarId") String calendarId);
@Query("select b from SchedulerTask b where b.processETL = :processId")
List<SchedulerTask> findByEtlId(@Param("processId") int processId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.WeekScheduler;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
public interface WeekSchedulerRepository extends CrudRepository<WeekScheduler, BigInteger>, JpaSpecificationExecutor<WeekScheduler> {
@Query("select b from WeekScheduler b where b.calendarID = :caleId")
Optional<List<WeekScheduler>> findByCalendarId(@Param("caleId") String caleId);
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.AgencyAgent;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface AgencyAgentRepository extends CrudRepository<AgencyAgent, Integer>, JpaSpecificationExecutor<AgencyAgent> {
Optional<AgencyAgent> findByUser_Id(Integer userId);
Optional<AgencyAgent> findByIdAndDeletedAtIsNull(Integer id);
List<AgencyAgent> findAllByDeletedAtIsNull();
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.AgencyAgent;
import com.bytesw.bytebot.model.agency.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface AgencyUserRepository extends JpaRepository<User, Integer> {
Optional<User> findByEmail(String email);
Optional<User> findByEmailAndPassword(String email, String password);
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Aircraft;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface AircraftRepository extends JpaRepository<Aircraft, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Airline;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface AirlineRepository extends JpaRepository<Airline, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Airport;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface AirportRepository extends JpaRepository<Airport, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Cost;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CostRepository extends CrudRepository<Cost, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Flight;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
public interface FlightRepository extends CrudRepository<Flight, Integer>, JpaSpecificationExecutor<Flight> {
@Query(value = "SELECT f FROM Flight f WHERE f.airportOrigin.id = ?1 AND f.airportDestination.id = ?2 AND (?3 BETWEEN f.departureDate AND f.arrivalDate) AND f.deletedAt IS NULL")
List<Flight> searchFlights
(Integer airportOriginId, Integer airportDestinationId, LocalDateTime startDate);
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Passenger;
import com.bytesw.bytebot.model.agency.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface PassengerRepository extends CrudRepository<Passenger, Integer>, JpaSpecificationExecutor<Passenger> {
Optional<Passenger> findByUser_Id(Integer userId);
List<Passenger> findAllByDeletedAtIsNull();
Optional<Passenger> findByIdAndDeletedAtIsNull(Integer id);
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Payment;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PaymentRepository extends CrudRepository<Payment, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Reservation;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface ReservationRepository extends CrudRepository<Reservation, Integer>, JpaSpecificationExecutor<Reservation> {
Optional<Reservation> findByIdAndDeletedAtIsNull(Integer id);
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Scale;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ScaleRepository extends CrudRepository<Scale, Integer> {
}
package com.bytesw.bytebot.repository.agency;
import com.bytesw.bytebot.model.agency.Supervisor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.awt.print.Pageable;
import java.util.List;
import java.util.Optional;
@Repository
public interface SupervisorRepository extends CrudRepository<Supervisor, Integer>, JpaSpecificationExecutor<Supervisor> {
Optional<Supervisor> findByUser_Id(Integer userId);
Optional<Supervisor> findByIdAndDeletedAtIsNull(Integer id);
List<Supervisor> findAllByDeletedAtIsNull();
}
package com.bytesw.bytebot.routes;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SFTPRoute extends RouteBuilder {
@Value("${application.AVB-integration.ftp.username}")
private String username;
@Value("${application.AVB-integration.ftp.password}")
private String password;
@Value("${application.AVB-integration.ftp.directory:}")
private String directory;
@Value("${application.AVB-integration.ftp.host}")
private String host;
@Value("${application.AVB-integration.ftp.passiveMode:true}")
private boolean passiveMode;
@Value("${application.services.multi-tenant:false}")
private boolean multitenant;
@Override
public void configure() throws Exception {
from("direct:transferFile")
.toF("ftp://%s@%s/%s?password=%s&binary=true&passiveMode=%s", username, host, getDirectory(), password, passiveMode)
.log("Transfered file .${file:name} ");
}
private String getDirectory() {
if (!multitenant || ThreadLocalStorage.getTenantName() == null) {
return directory;
}
return ThreadLocalStorage.getTenantName() + "/" + directory;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.ActionBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
import com.bytesw.bytebot.etl.model.Action;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Log4j2
public class ActionService extends XDFService<Action, ActionBean, Long> {
protected ActionService(ActionRepository repository) {
super(repository);
}
@Override
protected Action toModel(Action model, ActionBean bean) {
if (model == null) {
model = new Action();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected ActionBean toBean(Action model) {
ActionBean bean = new ActionBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.etl.batch.service.ScheduleService;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.jdbc.AgentJDBCRepository;
import com.bytesw.bytebot.model.enums.*;
import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.config.AppContextManager;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.sql.beans.Pagination;
import lombok.extern.log4j.Log4j2;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Service
@Transactional
@Log4j2
public class AgentService extends CustomPaginationService<Agent> {
@Autowired
private AgentRepository agentRepository;
@Autowired
private AgentJDBCRepository agentJDBCRepository;
@Autowired
private CountryRepository countryRepository;
@Autowired
private DeploymentChannelRepository deploymentChannelRepository;
@Autowired
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@Autowired
private ChannelRepository channelRepository;
@Autowired
private ChannelParamRepository channelParamRepository;
@Autowired
private FrequentQuestionRepository frequentQuestionRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private ProducerTemplate producerTemplate;
@Autowired
private ScheduleService scheduleService;
public List<DeploymentChannelParamValueBean> GetKeysFromAgents(AgentStatusEnum status){
List<DeploymentChannelParamValueBean> values = agentJDBCRepository.getCredentialsFromAgentStatus(status.getName());
if (values == null){
values = new ArrayList<>();
}
//log.debug(values);
return values;
}
public void searchByPagination(Pagination<AgentBean> pagination) {
if (pagination.getItemsPerPage() == 0) {
pagination.setItemsPerPage(10);
}
Sort sort = null;
if (pagination.getSortFields() != null) {
sort = createSort(pagination);
}
Pageable pageable = null;
if (sort != null) {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage(), sort);
} else {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage());
}
Specification<Agent> specification = (Specification<Agent>) (root, query, criteriaBuilder)
-> criteriaBuilder.notEqual(root.get("status"), AgentStatusEnum.DELETED);
if (pagination.getFilterExpression() != null && pagination.getFilterExpression().length() > 0) {
specification = createSpecification(pagination.getFilterExpression()).and(specification);
}
Page<Agent> page = agentRepository.findAll(specification, pageable);
pagination.setTotalItems(page.getTotalElements());
pagination.setTotalPages(page.getTotalPages());
// Clone to array
List<AgentBean> list = new ArrayList<>();
for (Agent agent : page.getContent()) {
list.add(AgentBean.miniClone(agent));
}
pagination.setData(list);
}
@Transactional(propagation = Propagation.REQUIRED)
@CacheEvict(value="deploy_agents",allEntries = true)
public void save(AgentBean agent) {
boolean isModify = true;
Agent agentBD = null;
if (agent.getId() != null) {
Optional<Agent> agentFound = agentRepository.findById(agent.getId());
if (agentFound.isPresent()) {
agentBD = agentFound.get();
}
}
if (agentBD == null) {
agentBD = new Agent();
agentBD.setStatus(AgentStatusEnum.CREATED);
isModify = false;
} else {
agentBD.setStatus(AgentStatusEnum.fromString(agent.getStatus()));
}
// General Information
agentBD.setName(agent.getName());
agentBD.setDescription(agent.getDescription());
agentBD.setLanguage(LanguageEnum.fromString(agent.getLanguage()));
agentBD.setTimezone(agent.getTimezone());
agentBD.setVersion(agent.getVersion());
agentBD.setType(AgentTypeEnum.fromString(agent.getType()));
agentBD.setAvatar(agent.getAvatar());
agentBD.setPeriod(agent.getPeriod());
if (agent.getCountryId() != null) {
Optional<Country> countryFound = countryRepository.findById(agent.getCountryId());
if (countryFound.isPresent()) {
agentBD.setCountry(countryFound.get());
}
} else {
agentBD.setCountry(null);
}
agentBD = agentRepository.save(agentBD);
// Frequent questions
if (agent.getFrequentQuestions() == null) {
agent.setFrequentQuestions(new ArrayList<>());
}
if (agentBD.getFrequentQuestions() != null) {
for (FrequentQuestion frequentQuestionBD : agentBD.getFrequentQuestions()) {
boolean found = false;
for (FrequentQuestionBean frequentQuestionBean : agent.getFrequentQuestions()) {
if (frequentQuestionBean.getId() != null && frequentQuestionBD.getId().compareTo(frequentQuestionBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
frequentQuestionRepository.delete(frequentQuestionBD);
}
}
}
boolean changeToPendingSynchronized = false;
for (FrequentQuestionBean frequentQuestionBean : agent.getFrequentQuestions()) {
FrequentQuestion frequentQuestionBD = null;
boolean existInDB = false;
if (frequentQuestionBean.getId() != null) {
Optional<FrequentQuestion> frequentQuestionFound = frequentQuestionRepository.findById(frequentQuestionBean.getId());
if (frequentQuestionFound.isPresent()) {
existInDB = true;
frequentQuestionBD = frequentQuestionFound.get();
}
}
if (frequentQuestionBD == null) {
frequentQuestionBD = new FrequentQuestion();
frequentQuestionBD.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestionBD.setUuid(frequentQuestionBean.getUuid());
changeToPendingSynchronized = true;
}
frequentQuestionBD.setAgent(agentBD);
frequentQuestionBD.setDescription(frequentQuestionBean.getDescription());
frequentQuestionBD.setFilename(frequentQuestionBean.getFilename());
frequentQuestionBD.setStatus(FrequentQuestionStatusEnum.fromString(frequentQuestionBean.getStatus()));
frequentQuestionBD.setUser(frequentQuestionBean.getUser());
if (!existInDB) {
LocalDateTime uploadDate = questionFileRepository.findUploadDateByUuid(frequentQuestionBean.getUuid());
frequentQuestionBD.setUploadDate(uploadDate);
}
frequentQuestionRepository.save(frequentQuestionBD);
}
if (changeToPendingSynchronized) {
agentBD.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentBD = agentRepository.save(agentBD);
}
// Deployment channels
if (agent.getDeploymentChannels() == null) {
agent.setDeploymentChannels(new ArrayList<>());
}
if (agentBD.getDeploymentChannels() != null) {
for (DeploymentChannel deploymentChannelBD : agentBD.getDeploymentChannels()) {
boolean found = false;
for (DeploymentChannelBean deploymentChannelBean : agent.getDeploymentChannels()) {
if (deploymentChannelBean.getId() != null && deploymentChannelBD.getId().compareTo(deploymentChannelBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
deploymentChannelParamValueRepository.deleteAll(deploymentChannelBD.getParameters());
deploymentChannelRepository.delete(deploymentChannelBD);
}
}
}
for (DeploymentChannelBean deploymentChannelBean : agent.getDeploymentChannels()) {
DeploymentChannel deploymentChannelBD = null;
boolean existInBD = false;
if (deploymentChannelBean.getId() != null) {
Optional<DeploymentChannel> deploymentChannelFound = deploymentChannelRepository.findById(deploymentChannelBean.getId());
if (deploymentChannelFound.isPresent()) {
deploymentChannelBD = deploymentChannelFound.get();
existInBD = true;
}
}
if (deploymentChannelBD == null) {
deploymentChannelBD = new DeploymentChannel();
}
deploymentChannelBD.setAgent(agentBD);
deploymentChannelBD.setStatus(StatusEnum.fromString(deploymentChannelBean.getStatus()));
if (deploymentChannelBean.getChannelId() != null) {
Optional<Channel> channelFound = channelRepository.findById(deploymentChannelBean.getChannelId());
if (channelFound.isPresent()) {
deploymentChannelBD.setChannel(channelFound.get());
if (!existInBD) {
deploymentChannelBD.setName(agentBD.getName() + "_" + channelFound.get().getName());
}
}
} else {
deploymentChannelBD.setName(agentBD.getName() + "_" + UUID.randomUUID());
deploymentChannelBD.setChannel(null);
}
deploymentChannelRepository.save(deploymentChannelBD);
// Deployment Channel parameters
if (deploymentChannelBean.getParameters() == null) {
deploymentChannelBean.setParameters(new ArrayList<>());
}
if (deploymentChannelBD.getParameters() != null) {
for (DeploymentChannelParamValue deploymentChannelParamValueBD : deploymentChannelBD.getParameters()) {
boolean found = false;
for (DeploymentChannelParamValueBean deploymentChannelParamValueBean : deploymentChannelBean.getParameters()) {
if (deploymentChannelParamValueBean.getId() != null &&
deploymentChannelParamValueBD.getId().compareTo(deploymentChannelParamValueBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
deploymentChannelParamValueRepository.delete(deploymentChannelParamValueBD);
}
}
}
for (DeploymentChannelParamValueBean deploymentChannelParamValueBean : deploymentChannelBean.getParameters()) {
DeploymentChannelParamValue deploymentChannelParamValue = null;
if (deploymentChannelParamValueBean.getId() != null) {
Optional<DeploymentChannelParamValue> deploymentChannelParamValueFound = deploymentChannelParamValueRepository
.findById(deploymentChannelParamValueBean.getId());
if (deploymentChannelParamValueFound.isPresent()) {
deploymentChannelParamValue = deploymentChannelParamValueFound.get();
}
}
if (deploymentChannelParamValue == null) {
deploymentChannelParamValue = new DeploymentChannelParamValue();
}
deploymentChannelParamValue.setDeploymentChannel(deploymentChannelBD);
deploymentChannelParamValue.setValue(deploymentChannelParamValueBean.getValue());
if (deploymentChannelParamValueBean.getChannelParamName() != null) {
Optional<ChannelParam> channelParamFound = channelParamRepository.findByNameAndChannelId(
deploymentChannelParamValueBean.getChannelParamName(), deploymentChannelBean.getChannelId());
if (channelParamFound.isPresent()) {
deploymentChannelParamValue.setParameter(channelParamFound.get());
}
} else {
deploymentChannelParamValue.setParameter(null);
}
deploymentChannelParamValueRepository.save(deploymentChannelParamValue);
}
}
}
public AgentBean getAgent(Long id) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
AgentBean bean = null;
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
bean = new AgentBean();
bean.setId(agent.getId());
bean.setName(agent.getName());
bean.setDescription(agent.getDescription());
bean.setVersion(agent.getVersion());
bean.setLanguage(agent.getLanguage().getName());
bean.setTimezone(agent.getTimezone());
bean.setType(agent.getType().getName());
bean.setStatus(agent.getStatus().getName());
bean.setAvatar(agent.getAvatar());
bean.setPeriod(agent.getPeriod());
if (agent.getCountry() != null) {
bean.setCountryName(agent.getCountry().getName());
bean.setCountryId(agent.getCountry().getId());
}
// Deployment channel
bean.setFrequentQuestions(new ArrayList<>());
for (FrequentQuestion frequentQuestion : agent.getFrequentQuestions()) {
FrequentQuestionBean frequentQuestionBean = new FrequentQuestionBean();
frequentQuestionBean.setId(frequentQuestion.getId());
frequentQuestionBean.setUuid(frequentQuestion.getUuid());
frequentQuestionBean.setDescription(frequentQuestion.getDescription());
frequentQuestionBean.setUser(frequentQuestion.getUser());
frequentQuestionBean.setFilename(frequentQuestion.getFilename());
frequentQuestionBean.setStatus(frequentQuestion.getStatus().getName());
if(frequentQuestion.getUploadDate() != null) {
frequentQuestionBean.setUploadDate(frequentQuestion.getUploadDate().format(formatter));
}
bean.getFrequentQuestions().add(frequentQuestionBean);
}
// Deployment channel
bean.setDeploymentChannels(new ArrayList<>());
for (DeploymentChannel deploymentChannel : agent.getDeploymentChannels()) {
DeploymentChannelBean deploymentChannelBean = new DeploymentChannelBean();
deploymentChannelBean.setId(deploymentChannel.getId());
deploymentChannelBean.setName(deploymentChannel.getName());
deploymentChannelBean.setStatus(deploymentChannel.getStatus().getName());
deploymentChannelBean.setParameters(new ArrayList<>());
if (deploymentChannel.getChannel() != null) {
deploymentChannelBean.setChannelId(deploymentChannel.getChannel().getId());
deploymentChannelBean.setChannelName(deploymentChannel.getChannel().getName());
}
//Parameters
List<DeploymentChannelParamValue> list = deploymentChannelParamValueRepository.getParameter(deploymentChannel.getId());
for (DeploymentChannelParamValue parameter : list) {
DeploymentChannelParamValueBean parameterBean = new DeploymentChannelParamValueBean();
parameterBean.setId(parameter.getId());
parameterBean.setValue(parameter.getValue());
if (parameter.getParameter() != null) {
parameterBean.setChannelParamName(parameter.getParameter().getName());
}
deploymentChannelBean.getParameters().add(parameterBean);
}
bean.getDeploymentChannels().add(deploymentChannelBean);
}
}
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public boolean delete(Long id) {
boolean isValid = true;
if (id != null) {
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
agent.setStatus(AgentStatusEnum.DELETED);
scheduleService.cancelTaskDelete(id);
agentRepository.save(agent);
}
}
else{
isValid = false;
}
return isValid;
}
public List<CountryBean> getCountries() {
List<CountryBean> countriesBean = new ArrayList<>();
List<Country> countries = countryRepository.findAllOrder();
for (Country country : countries) {
countriesBean.add(CountryBean.clone(country));
}
return countriesBean;
}
public List<ChannelBean> getChannels() {
List<ChannelBean> channelsBean = new ArrayList<>();
List<Channel> channels = (List<Channel>) channelRepository.findAll();
for (Channel channel : channels) {
List<ChannelParam> channelParamList = channel.getParameters();
for (ChannelParam channelParam : channelParamList) {
channelParam.setTraductions(channelParam.getTraductions().replace("\\", ""));
}
channelsBean.add(ChannelBean.clone(channel));
}
return channelsBean;
}
@Transactional(propagation = Propagation.REQUIRED)
public void synchronizeFiles(Long id, String user) {
if (AppContextManager.getAppContext() == null) {
return;
}
FileConverter fileConverter = (FileConverter) AppContextManager.getAppContext().getBean("xlsToCsvFileConverter");
List<FrequentQuestion> frequentQuestions = frequentQuestionRepository.findAllByAgentIdAndStatus(id, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
Map<String, Object> headers = new HashMap<>();
for (FrequentQuestion frequentQuestion : frequentQuestions) {
Optional<QuestionFile> questionFileFound = questionFileRepository.findByUuid(frequentQuestion.getUuid());
if (questionFileFound.isPresent()) {
headers.put("CamelFileName", fileConverter.getFileName(questionFileFound.get().getName()));
// try {
// FileUtils.writeByteArrayToFile(new File("/home/schicoma/Escritorio/" + questionFileFound.get().getName()), questionFileFound.get().getData());
// } catch (IOException e) {
// e.printStackTrace();
// }
producerTemplate.sendBodyAndHeaders("direct:transferFile", fileConverter.convert(questionFileFound.get().getData(), questionFileFound.get().getName()), headers);
}
frequentQuestion.setStatus(FrequentQuestionStatusEnum.UPLOADED);
//frequentQuestion.setUser(user);
//frequentQuestion.setUploadDate(LocalDateTime.now());
frequentQuestionRepository.save(frequentQuestion);
}
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
agent.setStatus(AgentStatusEnum.DEPLOYED);
agentRepository.save(agent);
}
}
public List<Map> getAgentAll() {
List<Agent> lista = (List<Agent>) agentRepository.findAll();
if (lista.size() <= 0) {
throw new NotFoundException("Error al listar agentes.");
}
List<Map> result = new ArrayList<>();
for(Agent agent: lista) {
Map<String, Object> map = new HashMap<>();
map.put("id", agent.getId());
map.put("name", agent.getName());
map.put("description", agent.getDescription());
map.put("version", agent.getVersion());
map.put("status", agent.getStatus().getName());
map.put("period", agent.getPeriod());
map.put("timezone", agent.getTimezone());
result.add(map);
}
return result;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.BdcControlBean;
import com.bytesw.bytebot.model.BdcControl;
import com.bytesw.bytebot.repository.BdcControlRepository;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Log4j2
public class BcdControlService extends XDFService<BdcControl, BdcControlBean, Long> {
protected BcdControlService(BdcControlRepository repository) {
super(repository);
}
@Override
protected BdcControl toModel(BdcControl model, BdcControlBean bean) {
if (model == null) {
model = new BdcControl();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected BdcControlBean toBean(BdcControl model) {
BdcControlBean bean = new BdcControlBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
}
package com.bytesw.bytebot.service;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
@Service
@Log4j2
public class BucketService {
@Value("${application.bucket.tenant}")
private String tenant;
@Value("${application.bucket.region}")
private String region;
@Value("${application.bucket.fileBucket}")
private String fileDir;
@Value("${application.bucket.modelBucket}")
private String modelDir;
@Value("${application.bucket.version}")
private String version;
@Value("${application.bucket.parameter}")
private String parameter;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private BusinessParameterService businessParameterService;
private AmazonS3 getS3Client() {
return AmazonS3ClientBuilder.standard()
.withRegion(region)
.build();
}
public boolean generate(byte[] file, FileValidationResponse response) {
String bucketName = businessParameterService.getBusinessParameterForKey(parameter);
if (bucketName == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
boolean result = false;
File mainFile = new File(response.getFileName());
try {
FileOutputStream stream = new FileOutputStream(mainFile);
stream.write(file);
String newFile = String.format("%s/%s/%s/%s/%s",tenant, response.getUuid(), version, fileDir, mainFile.getName());
PutObjectRequest request = new PutObjectRequest(bucketName, newFile, mainFile);
AmazonS3 amazonS3 = getS3Client();
amazonS3.putObject(request);
String modelFile = String.format("%s/%s/%s/%s",tenant, response.getUuid(), version, modelDir);
createFolder(bucketName, modelFile, amazonS3);
mainFile.delete();
result = true;
} catch (Exception e) {
log.error("Error al cargar archivo");
}
return result;
}
public static void createFolder(String bucketName, String folderName, AmazonS3 client) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
folderName+"/", emptyContent, metadata);
client.putObject(putObjectRequest);
}
public void delete(String uuid) {
String bucketName = businessParameterService.getBusinessParameterForKey(parameter);
if (bucketName == null) {
throw new NotFoundException();
}
try {
AmazonS3 s3Client = getS3Client();
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (!questionFile.isPresent()) {
throw new NotFoundException();
}
String keyName = String.format("%s/%s/%s/%s/%s",tenant, uuid, version, fileDir, questionFile.get().getName());
s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
keyName = String.format("%s/%s/%s/%s/",tenant, uuid, version, modelDir);
s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
} catch (AmazonServiceException e) {
e.printStackTrace();
} catch (SdkClientException e) {
e.printStackTrace();
}
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.Optional;
@Service
@Transactional
public class BusinessParameterConfigurationService extends XDFService<BusinessParameterConfiguration, BusinessParameterConfigurationBean, BigInteger> {
@Autowired
private BusinessParameterService gatewayBusinessParameterService;
@Autowired
private BusinessParameterRepository businessParameterRepository;
@Autowired
private BusinessParameterConfigurationRepository businessParameterConfigurationRepository;
protected BusinessParameterConfigurationService(BusinessParameterConfigurationRepository repository) {
super(repository);
}
@Override
protected BusinessParameterConfiguration toModel(BusinessParameterConfiguration model, BusinessParameterConfigurationBean bean) {
if (model == null) {
model = new BusinessParameterConfiguration();
}
BeanUtils.copyProperties(bean, model);
if (bean.getBusinessParameters() == null) {
throw new NotFoundException("BusinessParameter can not be null");
}
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findById(bean.getBusinessParameters().getId());
if (!businessParameterOptional.isPresent()) {
throw new NotFoundException("BusinessParameter not found " + bean.getBusinessParameters().getId());
}
model.setBusinessParameter(businessParameterOptional.get());
return model;
}
@Override
protected BusinessParameterConfigurationBean toBean(BusinessParameterConfiguration model) {
BusinessParameterConfigurationBean bean = new BusinessParameterConfigurationBean();
BeanUtils.copyProperties(model, bean);
bean.setBusinessParameters(gatewayBusinessParameterService.toBean(model.getBusinessParameter()));
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.bean.BusinessParameterBean;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.bytebot.bean.BusinessParameterValueBean;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.*;
@Service
@Transactional
public class BusinessParameterService extends XDFService<BusinessParameter, BusinessParameterBean, BigInteger> {
@Autowired
BusinessParameterRepository businessParameterRepository;
@Autowired
BusinessParameterConfigurationRepository businessParameterConfigurationRepository;
@Autowired
private BusinessParameterService businessParameterService;
@Autowired
private BusinessParameterConfigurationService businessParameterConfigurationService;
protected BusinessParameterService(BusinessParameterRepository repository) {
super(repository);
}
@Override
protected BusinessParameter toModel(BusinessParameter model, BusinessParameterBean bean) {
if (model == null) {
model = new BusinessParameter();
}
BeanUtils.copyProperties(bean, model);
model.setRequired("Y".equals(bean.getRequired()));
return model;
}
@Override
protected BusinessParameterBean toBean(BusinessParameter model) {
BusinessParameterBean bean = new BusinessParameterBean();
BeanUtils.copyProperties(model, bean);
bean.setRequired(model.getRequired() ? "Y" : "N");
BusinessParameterConfigurationBean businessParameterConfigurationBean = getBusinessConfiguration(model.getId());
bean.setCurrentValue(businessParameterConfigurationBean.getValue());
bean.setDateFrom(businessParameterConfigurationBean.getFrom());
bean.setDateApplyFrom(businessParameterConfigurationBean.getTo());
bean.setProgrammedValue(businessParameterConfigurationBean.getProgrammedValue());
bean.setCurrentConfigurationId(businessParameterConfigurationBean.getCurrentConfigurationId());
bean.setProgrammedConfigurationId(businessParameterConfigurationBean.getProgrammedConfigurationId());
return bean;
}
/**
* Permite crear un parámetro general utilizando el valor y la fecha de aplicación. Si la fecha no viene entonces se utiliza la fecha actual.
* <p></p>
*
* @param bean
* @return
*/
public BusinessParameterValueBean createWithValue(BusinessParameterValueBean bean) {
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findByKey(bean.getKey());
if (businessParameterOptional.isPresent()) {
String message = String.format("BusinessParameter is already created: %s. ", bean.getKey());
throw new AlreadyExistsException(message);
}
BusinessParameter businessParameter = new BusinessParameter();
businessParameter.setKey(bean.getKey());
businessParameter.setDescription(bean.getDescription());
businessParameter.setRequired(bean.isRequired());
businessParameter.setDefaultValue(bean.getDefaultValue());
businessParameter = businessParameterRepository.save(businessParameter);
if (bean.getFrom() == null) {
bean.setFrom(OffsetDateTime.now());
}
BusinessParameterConfiguration businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameter, bean.getValue(), bean.getFrom());
businessParameterConfiguration.setBusinessParameter(businessParameter);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
bean.setId(businessParameter.getId());
return bean;
}
/**
* Este método parte de que solo se puede un valor actual y/o un valor programado.
*
* @param key
* @param value
* @return
*/
public void addValue(String key, String value, OffsetDateTime from) {
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findByKey(key);
if (!businessParameterOptional.isPresent()) {
String message = String.format("BusinessParameter %s not found.", key);
throw new NotFoundException(message);
}
if (from == null) {
from = OffsetDateTime.now();
} else if (from.compareTo(OffsetDateTime.now()) < 0) {
String message = String.format("New date (%s) for the parameter (%s) cannot be less than the current", key, from.toString());
throw new NotFoundException(message);
}
List<BusinessParameterConfiguration> businessParameterConfigurationList = businessParameterConfigurationRepository.findValidByKey(key, from);
if (businessParameterConfigurationList.isEmpty()) {
BusinessParameterConfiguration businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameterOptional.get(), value, from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
} else {
Collections.sort(businessParameterConfigurationList);
OffsetDateTime temporallyTo = null;
for (BusinessParameterConfiguration businessParameterConfiguration : businessParameterConfigurationList) {
if (businessParameterConfiguration.getTo() != null) {
if (temporallyTo != null) {
businessParameterConfiguration.setFrom(temporallyTo);
}
temporallyTo = businessParameterConfiguration.getTo();
businessParameterConfiguration.setTo(from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
continue;
}
if (temporallyTo != null) {
businessParameterConfiguration.setFrom(from);
businessParameterConfiguration.setValue(value);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
} else {
businessParameterConfiguration.setTo(from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameterOptional.get(), value, from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
}
}
}
}
private BusinessParameterConfiguration prepareBusinessParameterConfiguration(BusinessParameter businessParameter, String value, OffsetDateTime from) {
BusinessParameterConfiguration businessParameterConfiguration = new BusinessParameterConfiguration();
businessParameterConfiguration.setValue(value);
if (from == null) {
businessParameterConfiguration.setFrom(OffsetDateTime.now());
} else {
businessParameterConfiguration.setFrom(from);
}
businessParameterConfiguration.setBusinessParameter(businessParameter);
return businessParameterConfiguration;
}
public String getCurrentValueParameterByKey(String key) {
String value = businessParameterService.getCurrentValueParameterByKey(key);
// String value = businessParameterService.getCurrentValue(key);
if (Objects.isNull(value)) {
throw new RuntimeException(String.format("Parameter %s not found", key));
}
return value;
}
@Override
public void delete(BigInteger id) {
List<BusinessParameterConfiguration> businessParameterConfigurationList = businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameter(id);
for (BusinessParameterConfiguration businessParameterConfiguration : businessParameterConfigurationList) {
businessParameterConfigurationRepository.delete(businessParameterConfiguration);
}
Optional<BusinessParameter> found = this.repository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
} else {
this.repository.delete(found.get());
}
}
@Override
public BusinessParameterBean update(BusinessParameterBean bean, BigInteger id) {
Optional<BusinessParameter> found = this.repository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
} else {
BusinessParameter businesParameter = this.toModel(found.get(), bean);
BeanUtils.copyProperties(businesParameter, found.get());
businesParameter = (BusinessParameter) this.repository.save(found.get());
if (bean.getDateFrom() != null) {
if (bean.getCurrentConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationCurrent = businessParameterConfigurationRepository.findById(bean.getCurrentConfigurationId());
businessParameterConfigurationCurrent.get().setFrom(bean.getDateFrom());
businessParameterConfigurationCurrent.get().setTo(bean.getDateApplyFrom());
businessParameterConfigurationCurrent.get().setValue(bean.getCurrentValue());
businessParameterConfigurationRepository.save(businessParameterConfigurationCurrent.get());
} else {
BusinessParameterConfiguration businessParameterConfigurationCurrent = new BusinessParameterConfiguration();
businessParameterConfigurationCurrent.setFrom(bean.getDateFrom());
businessParameterConfigurationCurrent.setTo(bean.getDateApplyFrom());
businessParameterConfigurationCurrent.setValue(bean.getCurrentValue());
businessParameterConfigurationCurrent.setBusinessParameter(businesParameter);
businessParameterConfigurationRepository.save(businessParameterConfigurationCurrent);
}
} else if (bean.getCurrentConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationCurrent = businessParameterConfigurationRepository.findById(bean.getCurrentConfigurationId());
businessParameterConfigurationRepository.delete(businessParameterConfigurationCurrent.get());
}
if (bean.getDateApplyFrom() != null) {
if (bean.getProgrammedConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationProgrammed = businessParameterConfigurationRepository.findById(bean.getProgrammedConfigurationId());
businessParameterConfigurationProgrammed.get().setFrom(bean.getDateApplyFrom());
businessParameterConfigurationProgrammed.get().setValue(bean.getProgrammedValue());
businessParameterConfigurationRepository.save(businessParameterConfigurationProgrammed.get());
} else {
BusinessParameterConfiguration businessParameterConfigurationProgrammed = new BusinessParameterConfiguration();
businessParameterConfigurationProgrammed.setFrom(bean.getDateApplyFrom());
businessParameterConfigurationProgrammed.setValue(bean.getProgrammedValue());
businessParameterConfigurationProgrammed.setBusinessParameter(businesParameter);
businessParameterConfigurationRepository.save(businessParameterConfigurationProgrammed);
}
} else if (bean.getProgrammedConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationProgrammed = businessParameterConfigurationRepository.findById(bean.getProgrammedConfigurationId());
businessParameterConfigurationRepository.delete(businessParameterConfigurationProgrammed.get());
}
return this.toBean(businesParameter);
}
}
//@Override
public BusinessParameterBean createBP(BusinessParameterBean bean) {
BusinessParameter model = new BusinessParameter();
BusinessParameterConfiguration businessParameterConfiguration = new BusinessParameterConfiguration();
if (this.existsByUK(bean)) {
throw new AlreadyExistsException();
}
model = this.businessParameterRepository.save(this.toModel(model, bean));
if (bean.getCurrentValue() != null && !bean.getCurrentValue().isEmpty()) {
businessParameterConfiguration.setTo(bean.getDateApplyFrom());
businessParameterConfiguration.setFrom(bean.getDateFrom());
businessParameterConfiguration.setValue(bean.getCurrentValue());
businessParameterConfiguration.setBusinessParameter(model);
this.businessParameterConfigurationRepository.save(businessParameterConfiguration);
}
if (bean.getProgrammedValue() != null && !bean.getProgrammedValue().isEmpty()) {
BusinessParameterConfiguration programmedValue = new BusinessParameterConfiguration();
programmedValue.setFrom(bean.getDateApplyFrom());
programmedValue.setValue(bean.getProgrammedValue());
programmedValue.setBusinessParameter(model);
this.businessParameterConfigurationRepository.save(programmedValue);
}
return this.toBean(model);
}
public BusinessParameterConfigurationBean getBusinessConfiguration(BigInteger id) {
List<BusinessParameterConfiguration> businessConfigurationList = businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameterWithLowestDateFrom(id, OffsetDateTime.now());
BusinessParameterConfigurationBean bean = new BusinessParameterConfigurationBean();
if (!businessConfigurationList.isEmpty()) {
BusinessParameterConfiguration businessParameterConfigurationFirst = businessConfigurationList.get(0);
if (businessConfigurationList.size() == 1) {
bean.setValue(businessParameterConfigurationFirst.getValue());
bean.setFrom(businessParameterConfigurationFirst.getFrom());
bean.setCurrentConfigurationId(businessParameterConfigurationFirst.getId());
} else {
for (BusinessParameterConfiguration bpc : businessConfigurationList) {
if (businessParameterConfigurationFirst.getFrom().equals(bpc.getTo())) {
bean.setValue(bpc.getValue());
bean.setFrom(bpc.getFrom());
bean.setTo(bpc.getTo());
bean.setProgrammedValue(businessParameterConfigurationFirst.getValue());
bean.setCurrentConfigurationId(bpc.getId());
bean.setProgrammedConfigurationId(bpc.getId());
bean.setCurrentConfigurationId(businessParameterConfigurationFirst.getId());
}
}
}
}
return bean;
}
public boolean validateKey(BusinessParameterBean bean) {
Optional<BusinessParameter> businessParameterOptional = this.businessParameterRepository.findByKey(bean.getKey());
if (businessParameterOptional.isPresent()) {
BusinessParameterBean businessParameterBeanOptional = toBean(businessParameterOptional.get());
if (!businessParameterBeanOptional.getId().equals(bean.getId())) {
return true;
}
}
return false;
}
public List<BusinessParameterConfigurationBean> getConfigurationParametersList(BigInteger busnessKey) {
List<BusinessParameterConfiguration> businessParametersConfigurationModelList = this.businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameter(busnessKey);
List<BusinessParameterConfigurationBean> beanList = new ArrayList<>();
if (!businessParametersConfigurationModelList.isEmpty()) {
for (BusinessParameterConfiguration model : businessParametersConfigurationModelList) {
BusinessParameterConfigurationBean businessParametersConfigurationBean = businessParameterConfigurationService.toBean(model);
beanList.add(businessParametersConfigurationBean);
}
return beanList;
}
return beanList;
}
public String getBusinessParameterForKey(String parameter) {
Optional<BusinessParameter> businessParameter = businessParameterRepository.findByKey(parameter);
if(!businessParameter.isPresent()) {
return null;
}
String parameterResult = null;
if (businessParameter.get().getRequired()) {
parameterResult = businessParameter.get().getDefaultValue();
}
List<BusinessParameterConfiguration> parameterConfig = businessParameterConfigurationRepository
.findBusinessParameterConfigurationListByBusinessParameter(businessParameter.get().getId());
if (parameterConfig.isEmpty()) {
return parameterResult;
}
OffsetDateTime nowTime = OffsetDateTime.now();
for (BusinessParameterConfiguration config: parameterConfig) {
if (config.getTo() == null) {
if (nowTime.isAfter(config.getFrom())) {
parameterResult = config.getValue();
break;
}
} else {
if (config.getFrom().equals(config.getTo())) {
if (config.getFrom().isBefore(nowTime)) {
parameterResult = config.getValue();
break;
}
}
if (config.getFrom().isBefore(config.getTo()) && nowTime.isAfter(config.getFrom()) && config.getTo().isAfter(nowTime)) {
parameterResult = config.getValue();
break;
}
}
}
return parameterResult;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import com.bytesw.bytebot.repository.CalendarExceptionRepository;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.xdf.dao.rsql.CustomRsqlVisitor;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import cz.jirutka.rsql.parser.RSQLParser;
import cz.jirutka.rsql.parser.ast.Node;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.*;
@Service
@Transactional
public class CalendarExceptionService extends XDFService<CalendarException, CalendarExceptionBean, BigInteger> {
@Autowired
CalendarRepository calendarRepository;
@Autowired
CalendarService calendarService;
@Autowired
CalendarExceptionRepository calendarExceptionRepository;
protected CalendarExceptionService(CalendarExceptionRepository repository) {
super(repository);
}
@Override
protected CalendarException toModel(CalendarException model, CalendarExceptionBean bean) {
if (model == null) {
model = getCalendarException(bean);
}
BeanUtils.copyProperties(bean, model);
if (bean.getCalendar() == null) {
throw new NotFoundException("Calendar can not be null");
}
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendar().getId());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendar().getId());
}
if (bean.getCalendarExceptionType() == null) {
throw new NotFoundException("Calendar Exception Type can not be null");
}
model.setCalendar(calendarOptional.get());
model.setCalendarExceptionType(CalendarExceptionType.fromString(bean.getCalendarExceptionType()));
return model;
}
public static CalendarException getCalendarException(CalendarExceptionBean bean) {
CalendarException model;
switch (bean.getFrequencyType()) {
case UniqueCalendarException.DISCRIMINATOR_VALUE:
model = new UniqueCalendarException();
break;
case AnnualCalendarException.DISCRIMINATOR_VALUE:
model = new AnnualCalendarException();
break;
case RangeCalendarException.DISCRIMINATOR_VALUE:
model = new RangeCalendarException();
break;
default:
model = new UniqueWeeklyCalendarException();
}
return model;
}
@Override
protected CalendarExceptionBean toBean(CalendarException model) {
CalendarExceptionBean bean = new CalendarExceptionBean();
BeanUtils.copyProperties(model, bean);
bean.setCalendar(this.calendarService.toBean(model.getCalendar()));
bean.setCalendarExceptionType(model.getCalendarExceptionType().getName());
bean.setFrequencyType(model.getFrequencyType());
return bean;
}
public List<CalendarExceptionBean> getCalendarExceptionbyID(Map<String, String> parametersCalendar) {
String sortDirection = parametersCalendar.get("sortDirection");
String columnName = parametersCalendar.get("columnName");
String caleId = parametersCalendar.get("caleId");
String filterExpresion = parametersCalendar.get("filterExpresion");
Specification<CalendarException> calendarExceptionSpecification = null;
Sort sort;
switch (sortDirection) {
case "desc":
sort = Sort.by(Sort.Direction.DESC, columnName);
break;
case "asc":
sort = Sort.by(Sort.Direction.ASC, columnName);
break;
default:
sort = Sort.by(Sort.Direction.ASC, "description");
}
if (filterExpresion != null) {
if (!filterExpresion.isEmpty()) {
filterExpresion = filterExpresion + ";";
}
filterExpresion = filterExpresion + String.format("calendar.id=='%s'", caleId);
calendarExceptionSpecification = createSpecification(filterExpresion);
}
List<CalendarException> optionalCalendarExceptionList = calendarExceptionRepository.findAll(calendarExceptionSpecification, sort);
List<CalendarExceptionBean> calendarExceptionBeanList = new ArrayList<>();
for (int i = 0; i < optionalCalendarExceptionList.size(); i++) {
CalendarExceptionBean aux = new CalendarExceptionBean();
BeanUtils.copyProperties(optionalCalendarExceptionList.get(i), aux);
calendarExceptionBeanList.add(i, toBean(optionalCalendarExceptionList.get(i)));
}
return calendarExceptionBeanList;
}
private Specification<CalendarException> createSpecification(String filterExpression) {
Node rootNode = (new RSQLParser()).parse(filterExpression);
return (Specification) rootNode.accept(new CustomRsqlVisitor<>());
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.bean.WeekSchedulerBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.SchedulerTask;
import com.bytesw.bytebot.model.WeekScheduler;
import com.bytesw.bytebot.repository.CalendarExceptionRepository;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.SchedulerTaskRepository;
import com.bytesw.bytebot.repository.WeekSchedulerRepository;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.exception.ReferentialIntegrityException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CalendarService extends XDFService<Calendar, CalendarBean, String> {
@Autowired
private WeekSchedulerService weekSchedulerService;
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private CalendarExceptionRepository calendarExceptionRepository;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private CalendarExceptionService calendarExceptionService;
protected CalendarService(CalendarRepository repository) {
super(repository);
}
@Override
protected Calendar toModel(Calendar model, CalendarBean bean) {
if (model == null) {
model = new Calendar();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected CalendarBean toBean(Calendar model) {
CalendarBean bean = new CalendarBean();
BeanUtils.copyProperties(model, bean);
bean.setWeekSchedulerBeanList(this.weekSchedulerService.getWeekSchedulerByCalId(model.getId().trim()));
/**/
return bean;
}
@Override
public void delete(String id) {
Optional<Calendar> found = this.calendarRepository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
}
Optional<List<SchedulerTask>> schedulerTaskList = this.schedulerTaskRepository.findByCalendarId(id);
if (schedulerTaskList.isPresent()) {
throw new ReferentialIntegrityException("CALENDAR_EXCEPTION_DELETE_SCHEDULER_TASK");
}
Optional<List<CalendarException>> calendarExceptionList = this.calendarExceptionRepository.findByCalendarId(id);
calendarExceptionList.ifPresent(list -> this.calendarExceptionRepository.deleteAll(list));
Optional<List<WeekScheduler>> weekSchedulerList = this.weekSchedulerRepository.findByCalendarId(id);
weekSchedulerList.ifPresent(list -> this.weekSchedulerRepository.deleteAll(list));
this.calendarRepository.delete(found.get());
}
@Override
public CalendarBean create(CalendarBean bean) {
if (this.calendarRepository.existsById(bean.getId())) {
throw new AlreadyExistsException("errors.form.duplicated.id");
}
Calendar model = new Calendar();
model = this.calendarRepository.save(this.toModel(model, bean));
saveWeekScheduler(bean, model);
saveCalendarException(bean, model);
return this.toBean(model);
}
@Override
public CalendarBean update(CalendarBean bean, String id) {
Optional<Calendar> found = this.calendarRepository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
}
Calendar calendar = this.toModel(found.get(), bean);
BeanUtils.copyProperties(calendar, found.get());
calendar = this.calendarRepository.save(found.get());
saveWeekScheduler(bean, calendar);
saveCalendarException(bean, calendar);
return this.toBean(calendar);
}
private void saveWeekScheduler(CalendarBean bean, Calendar calendar) {
List<WeekSchedulerBean> weekSchedulerBeanList = bean.getWeekSchedulerBeanList();
Optional<List<WeekScheduler>> weekSchedulerBeanListBD = weekSchedulerRepository.findByCalendarId(calendar.getId().trim());
List<BigInteger> weekIds = new ArrayList<>();
for (WeekSchedulerBean weekSchedulerBean : weekSchedulerBeanList) {
WeekScheduler weekScheduler;
boolean delete = weekSchedulerBean.getFrom() == null;
if (weekSchedulerBean.getId() != null) {
Optional<WeekScheduler> weekSchedulerOptional = this.weekSchedulerRepository.findById(weekSchedulerBean.getId());
if (weekSchedulerOptional.isPresent()) {
weekIds.add(weekSchedulerOptional.get().getId());
if (delete) {
this.weekSchedulerRepository.delete(weekSchedulerOptional.get());
continue;
}
weekScheduler = weekSchedulerOptional.get();
} else {
weekScheduler = new WeekScheduler();
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
}
// weekScheduler.setCalendar(calendar);
weekScheduler.setCalendarID(calendar.getId());
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
} else if (!delete) {
weekScheduler = new WeekScheduler();
// weekScheduler.setCalendar(calendar);
weekScheduler.setCalendarID(calendar.getId());
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
}
}
if (weekSchedulerBeanListBD.isPresent()){
for (WeekScheduler weekScheduler: weekSchedulerBeanListBD.get()) {
if (!weekIds.contains(weekScheduler.getId())) {
weekSchedulerRepository.deleteById(weekScheduler.getId());
}
}
}
}
private void saveCalendarException(CalendarBean bean, Calendar calendar) {
List<CalendarExceptionBean> calendarExceptionBeanList = bean.getCalendarExceptionBeanList();
Optional<List<CalendarException>> calendarExceptionListBD = calendarExceptionRepository.findByCalendarId(calendar.getId().trim());
List<BigInteger> exceptionIds = new ArrayList<>();
CalendarException calendarException = null;
for (CalendarExceptionBean calendarExceptionBean : calendarExceptionBeanList) {
if (calendarExceptionBean.getId() != null) {
Optional<CalendarException> calendarExceptionOptional = calendarExceptionRepository.findById(calendarExceptionBean.getId());
if (calendarExceptionOptional.isPresent()) {
exceptionIds.add(calendarExceptionBean.getId());
}
if (calendarExceptionBean.isDelete()) {
calendarExceptionRepository.delete(calendarExceptionOptional.get());
continue;
}
// modificar
if (!calendarExceptionOptional.get().getFrequencyType().equals(calendarExceptionBean.getFrequencyType())) {
calendarExceptionRepository.delete(calendarExceptionOptional.get());
} else {
calendarExceptionBean.setCalendar(bean);
calendarException = calendarExceptionService.toModel(calendarExceptionOptional.get(), calendarExceptionBean);
calendarExceptionRepository.save(calendarException);
continue;
}
}
// Nueva excepción
calendarException = calendarExceptionService.getCalendarException(calendarExceptionBean);
calendarExceptionBean.setCalendar(bean);
calendarException = calendarExceptionService.toModel(calendarException, calendarExceptionBean);
calendarException.setCalendar(calendar);
calendarExceptionRepository.save(calendarException);
}
if (calendarExceptionListBD.isPresent()){
for (CalendarException calException: calendarExceptionListBD.get()) {
if (!exceptionIds.contains(calException.getId())) {
calendarExceptionRepository.deleteById(calException.getId());
}
}
}
}
}
package com.bytesw.bytebot.service;
import com.bytesw.xdf.dao.rsql.CustomRsqlVisitor;
import com.bytesw.xdf.sql.beans.Pagination;
import com.bytesw.xdf.sql.beans.SortField;
import cz.jirutka.rsql.parser.RSQLParser;
import cz.jirutka.rsql.parser.ast.Node;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann
* @version 9-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*
*/
public abstract class CustomPaginationService<T> {
public Specification<T> createSpecification(final String filterExpression) {
Node rootNode = new RSQLParser().parse(filterExpression);
return rootNode.accept(new CustomRsqlVisitor<>());
}
public Sort createSort(Pagination pagination) {
List<Sort.Order> orderList = new ArrayList<>();
for (SortField sortField : pagination.getSortFields()) {
if ("asc".equalsIgnoreCase(sortField.getDirection())) {
orderList.add(Sort.Order.asc(sortField.getField()));
} else {
orderList.add(Sort.Order.desc(sortField.getField()));
}
}
return Sort.by(orderList);
}
}
\ No newline at end of file
package com.bytesw.bytebot.service;
public interface FileConverter {
byte[] convert(byte[] inputFile, String fileName);
String getFileName(String fileName);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.amazonaws.services.dynamodbv2.xspec.S;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.FileValidationResult;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.bytebot.utils.Utilities;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@Service
@Transactional
@Log4j2
public class FileManagementService {
String[] validExtensions = new String[]{"xls", "xlsx", "csv"};
String[] fileHeaders = new String[]{"Class", "Question", "Answer"};
@Autowired
private QuestionFileRepository questionFileRepository;
public FileValidationResponse saveFile(String uuid, MultipartFile file) throws IOException {
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
//@Validaciones: Tipo de Extension
boolean acceptedExtension = false;
String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
for (String validExension : validExtensions) {
if (validExension.equalsIgnoreCase(fileExtension.trim())) {
acceptedExtension = true;
break;
}
}
if (!acceptedExtension) {
log.info("La extension [" + fileExtension + "] es inválida");
result.setStatus(ValidationStatusEnum.INCOMPATIBLE_EXTENSION);
response.setFileValidationResult(result);
return response;
}
switch (fileExtension) {
case "csv":
response = validateCsv(uuid, file);
break;
case "xls":
case "xlsx":
response = validateAndSaveFile(uuid, file);
break;
}
return response;
}
@Transactional(propagation = Propagation.REQUIRED)
public FileValidationResponse validateAndSaveFile(String uuid, MultipartFile file) throws IOException {
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
//@Validaciones: De Estructura del Excel (Cabeceras)
byte[] fileData = file.getBytes();
log.debug("File Size: [" + file.getSize() + "]");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);
Workbook workbook = WorkbookFactory.create(byteArrayInputStream);
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
//@HU: Llenando los headers encontrados
Map<String, Integer> headersXPosition = new HashMap<>();
List<String> headersList = new ArrayList<>();
//Cabeceras vacias
if (headerRow == null) {
Map<String, String> headerErrorMap = new HashMap<>();
for (String key : fileHeaders) {
headerErrorMap.put(key, "HEADER.NOT.FOUND.FIRST.ROW");
}
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
response.setFileValidationResult(result);
return response;
}
Iterator<Cell> cells = headerRow.cellIterator();
int position = 0;
while (cells.hasNext()) {
Cell cell = (Cell) cells.next();
RichTextString value = cell.getRichStringCellValue();
headersXPosition.put(value.getString(), position++);
headersList.add(value.getString());
}
Map<String, String> headerErrorMap = validateHeaders(headersList);
if (!headerErrorMap.isEmpty()) {
log.info("Se encontraron los siguientes errores: " + headerErrorMap.values());
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
result.setHeadersErrorMap(headerErrorMap);
response.setFileValidationResult(result);
return response;
}
//@Validaciones: De Contenido(Todos deben tener valor)
int rowNumber = 0;
int rowError = 0;
Iterator<Row> rowIterator = sheet.iterator();
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
if (rowNumber == 0) {
rowNumber++;
continue;
}
log.debug("Row number: [" + rowNumber + "]");
Iterator<String> columnsIterator = headersXPosition.keySet().iterator();
Map<String, Object> recordsXRow = new HashMap<>();
while (columnsIterator.hasNext()) {
String name = columnsIterator.next();
log.debug("Read columnName [" + name + "]");
if (!isFileHeader(name.toUpperCase().trim())) {
log.debug("Skip columnName [" + name + "] - not required in format");
continue;
}
Cell cell = row.getCell(headersXPosition.get(name));
if (cell == null) {
recordsXRow.put(name, null);
continue;
}
CellType cellType = row.getCell(headersXPosition.get(name)).getCellType();
switch (cellType) {
case STRING:
RichTextString cellValue = row.getCell(headersXPosition.get(name)).getRichStringCellValue();
String value = (cellValue != null ? cellValue.getString().trim() : null);
recordsXRow.put(name, value);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(row.getCell(headersXPosition.get(name)))) {
Date date = row.getCell(headersXPosition.get(name)).getDateCellValue();
recordsXRow.put(name, Utilities.convertDateToString(date, "dd-MMM-yyyy"));
} else {
double numericVal = row.getCell(headersXPosition.get(name)).getNumericCellValue();
recordsXRow.put(name, numericVal);
}
break;
case BLANK:
recordsXRow.put(name, null);
break;
default:
log.info(" CellType not supported yet [" + row.getCell(headersXPosition.get(name)).getCellType() + "]");
log.info(" Value [" + row.getCell(headersXPosition.get(name)).getStringCellValue() + "]");
}
}
Map<String, String> recordsErrorMap = validateRecordsXRow(recordsXRow);
if (!recordsErrorMap.isEmpty()) {
if (recordsErrorMap.size() != fileHeaders.length){
recordsRowErrorMap.put(rowNumber + 1, recordsErrorMap);
} else {
Map<String, String> rowErrorResult = new HashMap<>();
rowErrorResult.put("ROW.NULL", "ROW.DATA.NULL");
recordsRowErrorMap.put(rowNumber, rowErrorResult);
}
}
rowNumber++;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.CONTENT_ERROR);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
//@HU: Proceder a guardar en BD el archivo subido
result.setStatus(ValidationStatusEnum.OK);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(file.getOriginalFilename());
questionFileBD.setSize(file.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(fileData);
questionFileBD = questionFileRepository.save(questionFileBD);
response.setId(questionFileBD.getId());
response.setUuid(questionFileBD.getUuid());
response.setFileName(questionFileBD.getName());
response.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
response.setUploadDate(getUploadDate(questionFileBD.getUploadDate()));
response.setFileValidationResult(result);
return response;
}
private String getUploadDate(LocalDateTime uploadDate) {
if (uploadDate != null) {
return uploadDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}
return null;
}
public FileValidationResponse validateCsv(String uuid, MultipartFile file) throws IOException{
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
List<List<String>> rows = new ArrayList<>();
try {
String line;
InputStream is = file.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> headerErrorMap = new HashMap<>();
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
int rowData = 1;
while ((line = br.readLine()) != null) {
List<String> row = new ArrayList<>();
String[] data = line.split(";");
if (data.length <= 1) {
headerErrorMap.put("FORMAT.SEPARATION", "ERROR.SEPARATION.FORMAT");
}
if (data.length < fileHeaders.length) {
Map<String, String> recordsErrorMap = new HashMap<>();
recordsErrorMap.put(ValidationStatusEnum.DATA_INCOMPLETE.getName(), "DATA.INCOMPLETE");
recordsRowErrorMap.put(rowData, recordsErrorMap);
}
for (String dato : data) {
if (validateData(dato)) {
headerErrorMap.put("FORMAT.DATA", "WRONG.DATA.INCORRECT");
}
row.add(dato);
}
rowData++;
rows.add(row);
}
if(!headerErrorMap.isEmpty()) {
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.FORMAT_INCORRECT);
response.setFileValidationResult(result);
return response;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.DATA_INCOMPLETE);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
List<String> headersList = new ArrayList<>();
for (String header: rows.get(0)) {
headersList.add(header.replace('"', ' '));
}
headerErrorMap = validateHeaders(headersList);
if (!headerErrorMap.isEmpty()) {
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
response.setFileValidationResult(result);
return response;
}
rows.remove(0);
} catch (IOException e) {
System.err.println(e.getMessage());
}
int rowNumber = 0;
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
for (List<String> item: rows) {
Map<String, Object> recordsXRow = new HashMap<>();
Map<String, String> recordsErrorMap = validateRecordsXRow(recordsXRow);
if (!recordsErrorMap.isEmpty()) {
if (recordsErrorMap.size() != fileHeaders.length){
recordsRowErrorMap.put(rowNumber + 1, recordsErrorMap);
}
}
rowNumber++;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.CONTENT_ERROR);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
result.setStatus(ValidationStatusEnum.OK);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(file.getOriginalFilename());
questionFileBD.setSize(file.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(file.getBytes());
questionFileBD = questionFileRepository.save(questionFileBD);
response.setId(questionFileBD.getId());
response.setUuid(questionFileBD.getUuid());
response.setFileName(questionFileBD.getName());
response.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
response.setUploadDate(getUploadDate(questionFileBD.getUploadDate()));
response.setFileValidationResult(result);
return response;
}
private boolean validateData (String data) {
if (data.charAt(0) == '"' && data.charAt(data.length()-1) == '"') {
return false;
}
return true;
}
private Map<String, String> validateHeaders(List<String> headersList) {
Map<String, Integer> headerOcurrencesMap = new HashMap<>();
Map<String, String> headerErrorMap = new HashMap<>();
Map<String, Integer> headerOrganized = new HashMap<>();
int index = 0;
for (String fileHeader : fileHeaders) {
String keyHeader = fileHeader.toUpperCase().trim();
if (headerOcurrencesMap.get(keyHeader) == null) {
headerOcurrencesMap.put(keyHeader, 0);
}
for (String header : headersList) {
if (header.toUpperCase().trim().equals(keyHeader)) {
int ocurrences = headerOcurrencesMap.get(keyHeader);
headerOcurrencesMap.put(keyHeader, ocurrences + 1);
headerOrganized.put(keyHeader, index);
}
index++;
}
index = 0;
}
for (String keyHeader : headerOcurrencesMap.keySet()) {
int ocurrences = headerOcurrencesMap.get(keyHeader);
if (ocurrences == 0) {
headerErrorMap.put(keyHeader, "HEADER.NOT.FOUND");
} else if (ocurrences >= 1) {
if (ocurrences > 1){
headerErrorMap.put(keyHeader, "HEADER.REPETEAD");
} else if (!keyHeader.equalsIgnoreCase(fileHeaders[headerOrganized.get(keyHeader)])) {
headerErrorMap.put(keyHeader, "HEADER.NOT.ORGANIZED");
}
}
index ++;
}
return headerErrorMap;
}
private Map<String, String> validateRecordsXRow(Map<String, Object> recordsXRow) {
Map<String, String> recordsErrorMap = new HashMap<>();
for (String headerName : recordsXRow.keySet()) {
String keyHeader = headerName.toUpperCase().trim();
if (!isFileHeader(keyHeader)) {
continue;
}
if (recordsErrorMap.get(keyHeader) != null) {
continue;
}
if (recordsXRow.get(headerName) == null) {
recordsErrorMap.put(keyHeader, "NOT.FOUND.VALUE");
} else {
Object recordRowValue = recordsXRow.get(headerName);
if (recordRowValue instanceof String) {
String record = (String) recordRowValue;
if (record.trim().equals("")) {
recordsErrorMap.put(keyHeader, "EMPTY.VALUE");
}
}
}
}
return recordsErrorMap;
}
private boolean isFileHeader(String keyHeader) {
boolean isFileHeader = false;
for (String fileHeader : fileHeaders) {
if (keyHeader.equals(fileHeader.toUpperCase().trim())) {
isFileHeader = true;
break;
}
}
return isFileHeader;
}
@Transactional(propagation = Propagation.REQUIRED)
public void deleteGoalForAction(Long id) {
Optional<QuestionFile> file = questionFileRepository.findById(id);
if (!file.isPresent()) {
throw new NotFoundException("File no econtrado.");
}
questionFileRepository.delete(file.get());
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.GoalForActionsBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
import com.bytesw.bytebot.etl.model.Action;
import com.bytesw.bytebot.etl.model.GoalForActions;
import com.bytesw.bytebot.repository.GoalForActionsRepository;
import com.bytesw.bytebot.repository.GoalRepository;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
@Transactional
@Log4j2
public class GoalForActionService extends XDFService<GoalForActions, GoalForActionsBean, Long> {
@Autowired
private GoalRepository goalRepository;
@Autowired
private ActionRepository actionRepository;
@Autowired
private GoalForActionsRepository goalForActionsRepository;
protected GoalForActionService(GoalForActionsRepository repository) {
super(repository);
}
@Override
protected GoalForActions toModel(GoalForActions model, GoalForActionsBean bean) {
if (model == null) {
model = new GoalForActions();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected GoalForActionsBean toBean(GoalForActions model) {
GoalForActionsBean bean = new GoalForActionsBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public void saveGoalForAction(Long idGoal, List<Object> actions) {
if (!goalRepository.existsById(idGoal)) {
throw new NotFoundException("Goal no registrado.");
}
Map<String, String> dataAction = new HashMap<String, String>();
for(Object action : actions){
GoalForActions goalForActions = new GoalForActions();
goalForActions.setGoalId(idGoal);
dataAction = (HashMap) action;
if (!actionRepository.existsById(Long.valueOf(dataAction.get("IdAction").toString()))) {
continue;
}
goalForActions.setActionId(Long.valueOf(dataAction.get("IdAction").toString()));
goalForActions = goalForActionsRepository.save(goalForActions);
}
}
@Transactional(propagation = Propagation.REQUIRED)
public void deleteGoalForAction(Long goalId) {
Optional<List<GoalForActions>> listGoalForActions = goalForActionsRepository.findGoalForActionsByGoalId(goalId);
if (!listGoalForActions.isPresent()) {
throw new NotFoundException("GoalForActions no econtrados.");
}
for (GoalForActions goalForActions: listGoalForActions.get()) {
goalForActionsRepository.delete(goalForActions);
}
}
@Transactional(propagation = Propagation.REQUIRED)
public void updateGoalForAction(Long idGoal, List<Object> actions) {
Optional<List<GoalForActions>> listActual = goalForActionsRepository.findGoalForActionsByGoalId(idGoal);
if (!listActual.isPresent()) {
throw new NotFoundException("GoalForActions no encontrados.");
}
Map<String, String> dataAction = new HashMap<>();
List<Long> idActions = new ArrayList<>();
for (Object object: actions) {
dataAction = (HashMap) object;
idActions.add(Long.valueOf(dataAction.get("IdAction")));
}
for (GoalForActions goalForActions : listActual.get()) {
if (!idActions.contains(goalForActions.getActionId())) {
goalForActionsRepository.delete(goalForActions);
} else {
idActions.remove(goalForActions.getActionId());
}
}
for (Long id: idActions) {
GoalForActions newGoalForActions = new GoalForActions();
newGoalForActions.setGoalId(idGoal);
newGoalForActions.setActionId(id);
goalForActionsRepository.save(newGoalForActions);
}
}
public List<Map> getGoalForAction(Long id) {
List<Map> list = new ArrayList<>();
Optional<List<GoalForActions>> goalForActions = goalForActionsRepository.findGoalForActionsByGoalId(id);
if (!goalForActions.isPresent()) {
throw new NotFoundException("No se encontraron actions.");
}
for (GoalForActions actions : goalForActions.get()) {
Action action = actionRepository.findById(actions.getActionId()).get();
if (action == null) {
log.debug("No se encontró la accion.");
continue;
}
Map<String, String> map = new HashMap<>();
map.put("IdAction", String.valueOf(action.getId()));
list.add(map);
}
return list;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.GoalBean;
import com.bytesw.bytebot.etl.model.Goal;
import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
@Transactional
@Log4j2
public class GoalService extends XDFService<Goal, Map, Long> {
@Autowired
private GoalRepository goalRepository;
@Autowired
private GoalForActionsRepository goalForActionsRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private GoalForActionService goalForActionService;
protected GoalService(GoalRepository repository) {
super(repository);
}
@Override
protected Goal toModel(Goal model, Map map) {
if (model == null) {
model = new Goal();
}
model.setId((Long) map.get("id"));
model.setIdentifier(String.valueOf(map.get("identifier")));
model.setAgenId((Long) map.get("agentId"));
return model;
}
@Override
protected Map toBean(Goal model) {
Map<String, Object> map = new HashMap<>();
map.put("id",model.getId());
map.put("identifier", model.getIdentifier());
map.put("agentId", model.getAgenId());
return map;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Map create(Map body) {
Goal goal = new Goal();
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
List<Object> actions = (List) body.get("actionList");
if (actions.isEmpty()) {
throw new NotFoundException("Debe poseer minimo un action.");
}
Long agenId = Long.valueOf(body.get("agentId").toString());
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
String ident = body.get("identifier").toString();
Optional<Goal> goalOptional= goalRepository.findByAgentAndIdent(agenId, ident);
if (goalOptional.isPresent()) {
throw new AlreadyExistsException("Goal ya existe en la base de datos.");
}
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.saveGoalForAction(goal.getId(), actions);
return toBean(goal);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void delete(Long goalId) {
if (!goalRepository.existsById(goalId)){
throw new NotFoundException("Goal no registrado.");
}
goalForActionService.deleteGoalForAction(goalId);
goalRepository.deleteById(goalId);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Map update(Map body, Long goalId) {
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
if (!goalRepository.existsById(goalId)) {
throw new NotFoundException("Goal no se encuenta registrado");
}
List<Object> actions = (List) body.get("actionList");
if (actions.isEmpty()) {
throw new NotFoundException("Debe poseer minimo un action.");
}
Long agenId = Long.valueOf(body.get("agentId").toString());
String ident = body.get("identifier").toString();
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
Optional<Goal> goalOptional= goalRepository.findByAgentAndIdent(agenId, ident);
if (goalOptional.isPresent()) {
if (goalOptional.get().getId() != goalId) {
throw new AlreadyExistsException("Goal ya existe en la base de datos para el agente ingresado.");
}
}
Goal goal = new Goal();
goal.setId(goalId);
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.updateGoalForAction(goal.getId(), actions);
return toBean(goal);
}
@Override
public Map getById(Long id){
Map<String, Object> result = new HashMap<>();
Optional<Goal> goal = goalRepository.findById(id);
if (!goal.isPresent()) {
throw new NotFoundException("Goal no se encuenta registrado");
}
List<Map> listAction = goalForActionService.getGoalForAction(id);
if (listAction.isEmpty()) {
throw new NotFoundException("Actions no encontrados");
}
result.put("id", goal.get().getId());
result.put("agentId", goal.get().getAgenId());
result.put("identifier", goal.get().getIdentifier());
result.put("actionList", listAction);
return result;
}
@Override
public List<Map> getAll(){
List<Map> result = new ArrayList<>();
List<Goal> list = (List<Goal>) goalRepository.findAll();
for (Goal goal: list) {
result.add(getById(goal.getId()));
}
return result;
}
}
\ No newline at end of file
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.bytebot.http.FileValidationResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
@Log4j2
public class KnowledgeService {
@Value("${application.bucket.tenant}")
private String tenant;
@Value("${application.knowledge.url}")
private String url;
@Value("${application.bucket.version}")
private String version;
public boolean generate(FileValidationResponse response) throws IOException {
boolean result = false;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(String.format("%s/clients/%s/versions/%s", url, tenant, version));
String json = String.format("{\"filename_csv\": \"%s\", \"index_name\": \"%s\"}",response.getFileName(), response.getUuid());
StringEntity entity = new StringEntity(json);
try {
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = resp -> {
int status = resp.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entityRes = resp.getEntity();
return entityRes != null ? EntityUtils.toString(entityRes) : null;
} else {
throw new ClientProtocolException("Error inesperado: " + status);
}
};
String res = httpclient.execute(httppost, responseHandler);
String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
httpclient.close();
if (status.equals("success")){
result = true;
}
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}
public boolean delete(String uuid) {
boolean result = false;
try {
HttpDelete httpDelete = new HttpDelete(String.format("%s/clients/%s/indexes/%s/versions/%s", url, tenant, uuid, version));
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Error inesperado: " + status);
}
};
CloseableHttpClient httpclient = HttpClients.createDefault();
String res = httpclient.execute(httpDelete, responseHandler);
httpclient.close();
String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
if (status.equals("success")){
result = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.FileValidationResult;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.BdcControl;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.model.enums.StatusBcdEnum;
import com.bytesw.bytebot.repository.BdcControlRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;
@Service
@Transactional
@Log4j2
public class OrquestadorService {
@Autowired
private FileManagementService fileManagementService;
@Autowired
private BucketService bucketService;
@Autowired
private BdcControlRepository bdcControlRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private KnowledgeService knowledgeService;
@Autowired
private BusinessParameterService businessParameterService;
@Value("${application.bucket.deployment}")
private String parameter;
public FileValidationResponse executeGenerateBCD(String uuid, MultipartFile file) {
BdcControl model = new BdcControl();
FileValidationResponse response = new FileValidationResponse();
boolean step = false;
try{
//Modo de despliegue
String modeDeployment = businessParameterService.getBusinessParameterForKey(parameter);
if (modeDeployment == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
//Valida y guarda en base de datos
response = fileManagementService.saveFile(uuid, file);
if(response.getFileValidationResult().getStatus().getName() != ValidationStatusEnum.OK.getName()) {
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
return response;
}
model.setUuid(response.getUuid());
model.setFileId(response.getId());
model.setFileName(response.getFileName());
model.setDate(response.getUploadDate());
model.setStatus(StatusBcdEnum.CARGADO.getName());
model = bdcControlRepository.save(model);
if (modeDeployment.equalsIgnoreCase("onCloud")) {
//Carga archivo a bucket
step = bucketService.generate(file.getBytes(), response);
if (!step) {
response.setMessage("NOT.FOUND.BUCKET");
throw new NotFoundException();
}
step = false;
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
}
//Generacion del modelo
step = knowledgeService.generate(response);
if (!step) {
response.setMessage("NOT.FOUND.KNOWLEDGE");
throw new NotFoundException();
}
response.setStatus(FrequentQuestionStatusEnum.CORRECTO.getName());
model.setStatus(StatusBcdEnum.INDEXADO.getName());
model = bdcControlRepository.save(model);
}catch (Exception e) {
if (response.getMessage() == null) {
response.setMessage("ERROR.UPLOAD");
}
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
}
return response;
}
public FileValidationResponse retry(String uuid) {
Optional<BdcControl> modelBdc = bdcControlRepository.findByUuid(uuid);
if (!modelBdc.isPresent()) {
throw new NotFoundException("NOT.FOUND.DATA.CONTROL");
}
boolean step = false;
BdcControl model = modelBdc.get();
FileValidationResponse response = modelToFileValidation(model);
try {
String modeDeployment = businessParameterService.getBusinessParameterForKey(parameter);
if (modeDeployment == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
if (model.getStatus().equals(StatusBcdEnum.CARGADO.getName())) {
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (!questionFile.isPresent()) {
response.setMessage("NOT.FOUND.DATA");
throw new NotFoundException();
}
if (modeDeployment.equalsIgnoreCase("onCloud")) {
step = bucketService.generate(questionFile.get().getData(), response);
if (!step) {
response.setMessage("NOT.FOUND.BUCKET");
throw new NotFoundException();
}
}
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
step = false;
}
if (model.getStatus().equals(StatusBcdEnum.INDEXANDO.getName())) {
step = knowledgeService.generate(response);
if (!step) {
response.setMessage("NOT.FOUND.KNOWLEDGE");
throw new NotFoundException();
}
}
model.setStatus(StatusBcdEnum.INDEXADO.getName());
model = bdcControlRepository.save(model);
response.setStatus(FrequentQuestionStatusEnum.CORRECTO.getName());
} catch (Exception e) {
if (response.getMessage() == null) {
response.setMessage("ERROR.UPLOAD");
}
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
}
return response;
}
public void deleteBcd(String uuid) {
Optional<BdcControl> bdcControl = bdcControlRepository.findByUuid(uuid);
if (!bdcControl.isPresent()) {
throw new NotFoundException();
}
BdcControl model = bdcControl.get();
if (model.getStatus().equals(StatusBcdEnum.INDEXADO.getName())) {
boolean step = knowledgeService.delete(uuid);
if (!step) {
throw new NotFoundException();
}
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
}
if (model.getStatus().equals(StatusBcdEnum.INDEXANDO.getName())) {
bucketService.delete(uuid);
model.setStatus(StatusBcdEnum.CARGADO.getName());
model = bdcControlRepository.save(model);
}
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (questionFile.isPresent()) {
questionFileRepository.deleteById(bdcControl.get().getFileId());
}
bdcControlRepository.delete(model);
}
private FileValidationResponse modelToFileValidation(BdcControl model){
FileValidationResponse response = new FileValidationResponse();
response.setId(model.getId());
response.setStatus(model.getStatus());
response.setUuid(model.getUuid());
response.setFileName(model.getFileName());
response.setUploadDate(model.getDate());
FileValidationResult result = new FileValidationResult();
result.setStatus(ValidationStatusEnum.OK);
response.setFileValidationResult(result);
return response;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.ProcessETLBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.ProcessETL;
import com.bytesw.bytebot.repository.ProcessETLRepository;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ProcessETLService extends XDFService<ProcessETL, ProcessETLBean, Integer> {
protected ProcessETLService(ProcessETLRepository repository) {
super(repository);
}
@Override
protected ProcessETL toModel(ProcessETL model, ProcessETLBean bean) {
if (model == null) {
model = new ProcessETL();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected ProcessETLBean toBean(ProcessETL model) {
ProcessETLBean bean = new ProcessETLBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.SchedulerTaskBean;
import com.bytesw.bytebot.etl.batch.service.ScheduleService;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.SchedulerTask;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.SchedulerTaskRepository;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.*;
@Service
@Transactional
public class SchedulerTaskService extends XDFService<SchedulerTask, SchedulerTaskBean, BigInteger> {
@Autowired
private CalendarService CalendarService;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private ScheduleService scheduleService;
protected SchedulerTaskService(SchedulerTaskRepository repository) {
super(repository);
}
@Override
protected SchedulerTask toModel(SchedulerTask model, SchedulerTaskBean bean) {
if (model == null) {
model = new SchedulerTask();
}
BeanUtils.copyProperties(bean, model);
model.setInternals("Y".equals(bean.getInternals()));
model.setProcessETL(bean.getEtlId());
if (bean.getCalendarID() == null) {
throw new NotFoundException("Calendar can not be null");
}
bean.setCalendarID(bean.getCalendarID().trim());
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendarID());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
// model.setCalendar(calendarOptional.get());
return model;
}
@Override
protected SchedulerTaskBean toBean(SchedulerTask model) {
SchedulerTaskBean bean = new SchedulerTaskBean();
BeanUtils.copyProperties(model, bean);
bean.setInternals(model.getInternals().booleanValue() ? "Y" : "N");
bean.setCalendarID(bean.getCalendarID().trim());
bean.setEtlId(model.getProcessETL());
// CalendarBean found = this.CalendarService.getById(bean.getCalendarID());
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendarID());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
bean.setCalendarName(calendarOptional.get().getName());
return bean;
}
public Map<String, List> getInitialData() {
List<CalendarBean> calendarBeanList = this.CalendarService.getAll();
Map<String, List> initialData = new HashMap<>();
initialData.put("calendarList", calendarBeanList);
return initialData;
}
@Override
public SchedulerTaskBean create(SchedulerTaskBean schedulerTaskBean) {
SchedulerTask schedulerTask = new SchedulerTask();
schedulerTask = toModel(schedulerTask, schedulerTaskBean);
schedulerTask = schedulerTaskRepository.save(schedulerTask);
scheduleService.restartTask(schedulerTask);
return toBean(schedulerTask);
}
@Override
public SchedulerTaskBean update(SchedulerTaskBean bean, BigInteger id) {
Optional<SchedulerTask> model = schedulerTaskRepository.findById(id);
if (!model.isPresent()) {
throw new NotFoundException();
}
SchedulerTask schedulerTask = new SchedulerTask();
schedulerTask = toModel(schedulerTask, bean);
schedulerTask = schedulerTaskRepository.save(schedulerTask);
scheduleService.restartTask(schedulerTask);
return toBean(schedulerTask);
}
@Override
public void delete (BigInteger id) {
Optional<SchedulerTask> model = schedulerTaskRepository.findById(id);
if (!model.isPresent()) {
throw new NotFoundException();
}
scheduleService.cancelTask(model.get());
schedulerTaskRepository.deleteById(id);
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.WeekSchedulerBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.WeekScheduler;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.WeekSchedulerRepository;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class WeekSchedulerService extends XDFService<WeekScheduler, WeekSchedulerBean, BigInteger> {
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private CalendarService calendarService;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private CalendarService CalendarService;
protected WeekSchedulerService(WeekSchedulerRepository repository) {
super(repository);
}
@Override
protected WeekScheduler toModel(WeekScheduler model, WeekSchedulerBean bean) {
if (model == null) {
model = new WeekScheduler();
}
BeanUtils.copyProperties(bean, model);
if (bean.getCalendarID() == null) {
throw new NotFoundException("Calendar can not be null");
}
bean.setCalendarID(bean.getCalendarID().trim());
Optional<Calendar> calendarOptional = calendarRepository.findById(bean.getCalendarID().trim());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
// model.setCalendarID(calendarOptional.get());
return model;
}
@Override
protected WeekSchedulerBean toBean(WeekScheduler model) {
WeekSchedulerBean bean = new WeekSchedulerBean();
BeanUtils.copyProperties(model, bean);
bean.setCalendarID(model.getCalendarID());
CalendarBean found = this.CalendarService.getById(bean.getCalendarID().trim());
if(found != null){
bean.setCalendarName(found.getName());
}
return bean;
}
public List<WeekSchedulerBean> getWeekSchedulerByCalId(String caleID) {
List<WeekSchedulerBean> weekSchedulerBeanList = new ArrayList<>(7);
Optional<List<WeekScheduler>> weekSchedulerOptional = this.weekSchedulerRepository.findByCalendarId(caleID.trim());
if (!weekSchedulerOptional.isPresent()) {
for (int i = 0; i < 7; i++) {
weekSchedulerBeanList.add(i, new WeekSchedulerBean());
}
} else {
for (int i = 0; i < 7; i++) {
WeekSchedulerBean aux = new WeekSchedulerBean();
for (int j = 0; j < weekSchedulerOptional.get().size(); j++){
aux.setDayOfWeek(i+1);
if(weekSchedulerOptional.get().get(j).getDayOfWeek() == i+1){
BeanUtils.copyProperties(weekSchedulerOptional.get().get(j), aux);
}
}
weekSchedulerBeanList.add(i, aux);
}
}
return weekSchedulerBeanList;
}
}
package com.bytesw.bytebot.service;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
@Component("xlsToCsvFileConverter")
public class XlsToCsvFileConverter implements FileConverter {
private static final String FILE_EXTENSION = ".csv";
@Value("${application.service.file-converter.xls-to-csv.separator:$$}")
private String separator;
@Override
public byte[] convert(byte[] inputFile, String fileName) {
StringBuffer data = new StringBuffer();
InputStream fis = null;
Workbook workbook = null;
try {
//FileOutputStream fos = new FileOutputStream();
// Get the workbook object for XLSX file
fis = new ByteArrayInputStream(inputFile);
String ext = FilenameUtils.getExtension(fileName);
if (ext.equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (ext.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(fis);
}
// Get first sheet from the workbook
int numberOfSheets = workbook.getNumberOfSheets();
Row row;
Cell cell;
// Iterate through each rows from first sheet
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case BOOLEAN:
data.append(cell.getBooleanCellValue() + separator);
break;
case NUMERIC:
data.append(cell.getNumericCellValue() + separator);
break;
case STRING:
data.append(cell.getStringCellValue() + separator);
break;
case BLANK:
data.append("" + separator);
break;
default:
data.append(cell + separator);
}
}
data.setLength(data.length() - separator.length());
data.append('\n'); // appending new line after each row
}
}
return data.toString().getBytes();
//fos.write(data.toString().getBytes());
//fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (Exception e) {}
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {}
}
}
return new byte[]{};
}
@Override
public String getFileName(String fileName) {
int position = fileName.lastIndexOf(".");
String fileNameWithoutExtension = fileName.substring(0, position);
return fileNameWithoutExtension + FILE_EXTENSION;
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.AgentBean;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.UpdatePasswordBean;
import com.bytesw.bytebot.model.agency.AgencyAgent;
import com.bytesw.bytebot.model.agency.Passenger;
import com.bytesw.bytebot.model.agency.Supervisor;
import com.bytesw.bytebot.model.agency.User;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import com.bytesw.bytebot.repository.agency.AgencyAgentRepository;
import com.bytesw.bytebot.repository.agency.AgencyUserRepository;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class AgencyAgentService {
private final AgencyAgentRepository agentRepository;
private final AgencyUserRepository userRepository;
public AgencyAgentService(AgencyAgentRepository agentRepository, AgencyUserRepository userRepository) {
this.agentRepository = agentRepository;
this.userRepository = userRepository;
}
public List<AgentBean> getAll() {
List<AgencyAgent> agents = agentRepository.findAllByDeletedAtIsNull();
List<AgentBean> agentBeans = new ArrayList<>();
for (AgencyAgent agent: agents) {
agentBeans.add(AgentBean.miniClone(agent));
}
return agentBeans;
}
public CustomPaginationBean<AgentBean> getByPagination(CustomPaginationBean<AgentBean> pagination) {
Pageable pageable = CustomPaginationBean.buildPageable(pagination);
Specification<AgencyAgent> specification = (Specification<AgencyAgent>) (root, query, criteriaBuilder)
-> criteriaBuilder.isNull(root.get("deletedAt"));
Page<AgencyAgent> page = agentRepository.findAll(specification, pageable);
Page<AgentBean> beanPage = convertPage(page);
return CustomPaginationBean.fromPage(beanPage);
}
public Page<AgentBean> convertPage(Page<AgencyAgent> originalPage) {
List<AgentBean> agentBeans = originalPage.getContent().stream()
.map(AgentBean::miniClone)
.collect(Collectors.toList());
return new PageImpl<>(agentBeans, originalPage.getPageable(), originalPage.getTotalElements());
}
public AgentBean getByUserId(Integer userId) {
Optional<AgencyAgent> agent = agentRepository.findByUser_Id(userId);
if (!agent.isPresent())
throw new RuntimeException("Agent not found!");
return AgentBean.miniClone(agent.get());
}
public AgentBean getById(Integer id) {
Optional<AgencyAgent> agent = agentRepository.findByIdAndDeletedAtIsNull(id);
if (!agent.isPresent())
throw new RuntimeException("Agent not found!");
return AgentBean.miniClone(agent.get());
}
public AgentBean create(SignUpBean up) {
AgencyAgent agent = new AgencyAgent();
User user = new User();
user.setEmail(up.getEmail());
user.setPassword(up.getPassword());
user.setRole(RoleEnum.AGENT);
agent.setName(up.getName());
agent.setLastname(up.getLastname());
agent.setDetails(up.getDetails());
agent.setUser(user);
return AgentBean.miniClone(agentRepository.save(agent));
}
public AgentBean update(UpdatePasswordBean passwordBean, Integer id) {
Optional<AgencyAgent> agent = agentRepository.findByIdAndDeletedAtIsNull(id);
if (!agent.isPresent())
throw new RuntimeException("Agent not found!");
agent.get().getUser().setPassword(passwordBean.getPassword());
return AgentBean.miniClone(agentRepository.save(agent.get()));
}
public AgentBean delete(Integer id) {
Optional<AgencyAgent> agent = agentRepository.findByIdAndDeletedAtIsNull(id);
if (!agent.isPresent())
throw new RuntimeException("Agent not found!");
agent.get().setDeletedAt(LocalDate.now());
return AgentBean.miniClone(agentRepository.save(agent.get()));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.AircraftBean;
import com.bytesw.bytebot.model.agency.Aircraft;
import com.bytesw.bytebot.repository.agency.AircraftRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class AircraftService {
private final AircraftRepository aircraftRepository;
public AircraftService(AircraftRepository aircraftRepository) {
this.aircraftRepository = aircraftRepository;
}
public List<AircraftBean> getAll() {
List<Aircraft> aircrafts = this.aircraftRepository.findAll();
List<AircraftBean> aircraftBeans = new ArrayList<>();
for(Aircraft aircraft: aircrafts) {
aircraftBeans.add(AircraftBean.miniClone(aircraft));
}
return aircraftBeans;
}
public AircraftBean save(AircraftBean bean) {
Aircraft aircraft = new Aircraft();
aircraft.setName(bean.getLabel());
return AircraftBean.miniClone(this.aircraftRepository.save(aircraft));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.bean.agency.AirlineBean;
import com.bytesw.bytebot.model.agency.Airline;
import com.bytesw.bytebot.repository.agency.AirlineRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
@Log4j2
public class AirlinesService {
private final AirlineRepository airlineRepository;
public AirlinesService(AirlineRepository airlineRepository) {
this.airlineRepository = airlineRepository;
}
public List<AirlineBean> findAll() {
List<Airline> airlines = airlineRepository.findAll();
List<AirlineBean> list = new ArrayList<>();
for (Airline airline : airlines) {
list.add(AirlineBean.miniClone(airline));
}
return list;
}
public AirlineBean save(AirlineBean dto) {
Airline airline = new Airline();
airline.setName(dto.getLabel());
return AirlineBean.miniClone(this.airlineRepository.save(airline));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.AirportBean;
import com.bytesw.bytebot.model.agency.Airport;
import com.bytesw.bytebot.repository.agency.AirportRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class AirportService {
private final AirportRepository airportRepository;
public AirportService(AirportRepository airportRepository) {
this.airportRepository = airportRepository;
}
public List<AirportBean> getAll() {
List<Airport> airports = this.airportRepository.findAll();
List<AirportBean> airportBeans = new ArrayList<>();
for (Airport airport: airports) {
airportBeans.add(AirportBean.miniClone(airport));
}
return airportBeans;
}
public AirportBean save(AirportBean airportBean) {
Airport airport = new Airport();
airport.setId(airportBean.getValue());
airport.setName(airportBean.getLabel());
return AirportBean.miniClone(airportRepository.save(airport));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.bean.agency.*;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.agency.*;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.repository.agency.*;
import com.bytesw.bytebot.service.CustomPaginationService;
import com.bytesw.xdf.dao.rsql.CustomRsqlVisitor;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.bytesw.xdf.sql.beans.SortField;
import cz.jirutka.rsql.parser.RSQLParser;
import cz.jirutka.rsql.parser.ast.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class FlightService extends XDFService<Flight, FlightBean, Integer>{
@Autowired
private AirlineRepository airlineRepository;
@Autowired
private AircraftRepository aircraftRepository;
@Autowired
private AirportRepository airportRepository;
@Autowired
private FlightRepository flightRepository;
protected FlightService(FlightRepository repository) {
super(repository);
}
@Override
protected Flight toModel(Flight flight, FlightBean flightBean) {
return super.toModel(flight, flightBean);
}
@Override
protected FlightBean toBean(Flight model) {
return FlightBean.miniClone(model);
}
@Override
public FlightBean getById(Integer id) {
Optional flight = repository.findById(id);
if (!flight.isPresent())
throw new NotFoundException("Flight not found!");
return FlightBean.miniClone((Flight) flight.get());
}
public Sort createSort(Pagination pagination) {
List<Sort.Order> orderList = new ArrayList<>();
for (SortField sortField : pagination.getSortFields()) {
if ("asc".equalsIgnoreCase(sortField.getDirection())) {
orderList.add(Sort.Order.asc(sortField.getField()));
} else {
orderList.add(Sort.Order.desc(sortField.getField()));
}
}
return Sort.by(orderList);
}
public Specification<Flight> createSpecification(final String filterExpression) {
Node rootNode = new RSQLParser().parse(filterExpression);
return rootNode.accept(new CustomRsqlVisitor<>());
}
@Override
public void searchByPagination(Pagination<FlightBean> pagination) {
if (pagination.getItemsPerPage() == 0) {
pagination.setItemsPerPage(10);
}
Sort sort = null;
if (pagination.getSortFields() != null) {
sort = createSort(pagination);
}
Pageable pageable = null;
if (sort != null) {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage(), sort);
} else {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage());
}
Specification<Flight> specification = (Specification<Flight>) (root, query, criteriaBuilder)
-> criteriaBuilder.isNull(root.get("deletedAt"));
if (pagination.getFilterExpression() != null && pagination.getFilterExpression().length() > 0) {
specification = createSpecification(pagination.getFilterExpression()).and(specification);
}
Page<Flight> page = flightRepository.findAll(specification, pageable);
pagination.setTotalItems(page.getTotalElements());
pagination.setTotalPages(page.getTotalPages());
// Clone to array
List<FlightBean> list = new ArrayList<>();
for (Flight flight : page.getContent()) {
list.add(FlightBean.miniClone(flight));
}
pagination.setData(list);
}
public List<FlightSearchBean> searchFlights(Integer airportOriginId, Integer airportDestinationId, String departureDate) {
System.out.println(departureDate);
LocalDateTime startDate = LocalDateTime.parse(departureDate);
List<Flight> flights = flightRepository.searchFlights(airportOriginId, airportDestinationId, startDate);
return flights.stream()
.map(flight -> FlightSearchBean.miniClone(flight, startDate)).collect(Collectors.toList());
}
@Override
public FlightBean create(FlightBean flightBean) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
Optional<Airline> airline = airlineRepository.findById(flightBean.getAirlineId());
Optional<Aircraft> aircraft = aircraftRepository.findById(flightBean.getAircraftId());
if (!airline.isPresent())
throw new NotFoundException("Airline not found!");
if (!aircraft.isPresent())
throw new NotFoundException("Aircraft not found!");
LocalDateTime departureDate = LocalDateTime.parse(flightBean.getDepartureDate());
LocalDateTime arrivalDate = LocalDateTime.parse(flightBean.getArrivalDate());
if (departureDate.isAfter(arrivalDate) || departureDate.equals(arrivalDate))
throw new IllegalArgumentException("Departure date invalid!");
if (flightBean.getScales().isEmpty())
throw new IllegalArgumentException("Scales can't be empty!");
if (flightBean.getCosts().isEmpty())
throw new IllegalArgumentException("Costs can't be empty!");
Flight flight = new Flight();
List<ScaleBean> scales = flightBean.getScales();
List<Scale> scalesModel = new ArrayList<>();
for (ScaleBean scale: scales) {
Optional<Airport> airportOrigin = airportRepository.findById(scale.getAirportOriginId());
Optional<Airport> airportDestination = airportRepository.findById(scale.getAirportDestinationId());
if (!airportOrigin.isPresent() || !airportDestination.isPresent())
throw new NotFoundException("Airport not found!");
LocalDateTime scaleDeparture = LocalDateTime.parse(scale.getDepartureDate());
LocalDateTime scaleArrival = LocalDateTime.parse(scale.getArrivalDate());
if (scaleDeparture.isAfter(scaleArrival) ||
scaleDeparture.isEqual(scaleArrival))
throw new IllegalArgumentException("Departure date invalid!");
Scale scaleModel = new Scale();
scaleModel.setAirportOrigin(airportOrigin.get());
scaleModel.setAirportDestination(airportDestination.get());
scaleModel.setDepartureDate(scaleDeparture);
scaleModel.setArrivalDate(scaleArrival);
scaleModel.setFlight(flight);
scalesModel.add(scaleModel);
}
List<CostBean> costs = flightBean.getCosts();
List<Cost> costModel = new ArrayList<>();
for (CostBean cost: costs) {
LocalDateTime costDeparture = LocalDateTime.parse(cost.getDepartureDate());
LocalDateTime costArrival = LocalDateTime.parse(cost.getArrivalDate());
if (costDeparture.isAfter(costArrival) ||
costDeparture.isEqual(costArrival))
throw new IllegalArgumentException("Departure date invalid!");
if (cost.getAmount() == 0)
throw new IllegalArgumentException("Cost can't be zero!");
Cost oneCost = new Cost();
oneCost.setAmount(cost.getAmount());
oneCost.setDepartureDate(costDeparture);
oneCost.setArrivalDate(costArrival);
oneCost.setFlight(flight);
costModel.add(oneCost);
}
flight.setAirline(airline.get());
flight.setAircraft(aircraft.get());
flight.setDepartureDate(departureDate);
flight.setArrivalDate(arrivalDate);
flight.setScales(scalesModel);
flight.setCosts(costModel);
flight.setAirportOrigin(flight.getScales().get(0).getAirportOrigin());
flight.setAirportDestination(flight.getScales().get(flight.getScales().size() - 1).getAirportDestination());
return FlightBean.miniClone(flightRepository.save(flight));
}
public FlightBean update(FlightBean flightBean, Integer id) {
Optional<Flight> flight = flightRepository.findById(id);
if (!flight.isPresent())
throw new NotFoundException("Flight not found!");
Flight flightEdit = flight.get();
LocalDateTime departureDate = LocalDateTime.parse(flightBean.getDepartureDate());
LocalDateTime arrivalDate = LocalDateTime.parse(flightBean.getArrivalDate());
List<Cost> costsNew = flightBean.getCosts().stream().map(costBean -> {
Cost cost = new Cost();
cost.setFlight(flightEdit);
cost.setAmount(costBean.getAmount());
cost.setDepartureDate(LocalDateTime.parse(costBean.getDepartureDate()));
cost.setArrivalDate(LocalDateTime.parse(costBean.getArrivalDate()));
return cost;
}).collect(Collectors.toList());
flightEdit.getCosts().addAll(costsNew);
flightEdit.setDepartureDate(departureDate);
flightEdit.setArrivalDate(arrivalDate);
return FlightBean.miniClone(flightRepository.save(flightEdit));
}
public void delete(Integer id) {
Optional<Flight> flight = flightRepository.findById(id);
if (!flight.isPresent())
throw new NotFoundException("Flight not found!");
flight.get().setDeletedAt(LocalDate.now());
flightRepository.save(flight.get());
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.*;
import com.bytesw.bytebot.model.agency.AgencyAgent;
import com.bytesw.bytebot.model.agency.Flight;
import com.bytesw.bytebot.model.agency.Passenger;
import com.bytesw.bytebot.model.agency.User;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import com.bytesw.bytebot.repository.agency.AgencyUserRepository;
import com.bytesw.bytebot.repository.agency.PassengerRepository;
import com.bytesw.bytebot.service.CustomPaginationService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import com.bytesw.xdf.exception.NotFoundException;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class PassengerService extends CustomPaginationService<Passenger> {
private final PassengerRepository passengerRepository;
private final AgencyUserRepository userRepository;
public PassengerService(PassengerRepository passengerRepository, AgencyUserRepository userRepository) {
this.passengerRepository = passengerRepository;
this.userRepository = userRepository;
}
public CustomPaginationBean<PassengerBean> getByPagination(CustomPaginationBean<PassengerBean> pagination) {
Pageable pageable = CustomPaginationBean.buildPageable(pagination);
Specification<Passenger> specification = (Specification<Passenger>) (root, query, criteriaBuilder)
-> criteriaBuilder.isNull(root.get("deletedAt"));
Page<Passenger> page = passengerRepository.findAll(specification, pageable);
Page<PassengerBean> passengerBeans = convertPage(page);
return CustomPaginationBean.fromPage(passengerBeans);
}
public Page<PassengerBean> convertPage(Page<Passenger> originalPage) {
List<PassengerBean> passengerBeans = originalPage.getContent().stream()
.map(PassengerBean::miniClone)
.collect(Collectors.toList());
return new PageImpl<>(passengerBeans, originalPage.getPageable(), originalPage.getTotalElements());
}
public PassengerBean getById(Integer id) {
Optional<Passenger> passenger = passengerRepository.findByIdAndDeletedAtIsNull(id);
if (!passenger.isPresent())
throw new RuntimeException("Passenger not found!");
return PassengerBean.miniClone(passenger.get());
}
public List<PassengerMapBean> getAll() {
Iterable<Passenger> passengers = passengerRepository.findAllByDeletedAtIsNull();
List<PassengerMapBean> passengerBeans = new ArrayList<>();
for (Passenger passenger: passengers) {
passengerBeans.add(PassengerMapBean.miniClone(passenger));
}
return passengerBeans;
}
public PassengerBean getByUserId(Integer userId) {
Optional<Passenger> passenger = passengerRepository.findByUser_Id(userId);
if (!passenger.isPresent())
throw new RuntimeException("Passenger not found!");
return PassengerBean.miniClone(passenger.get());
}
public PassengerBean create(SignUpBean up) {
Passenger passenger = new Passenger();
User user = new User();
user.setEmail(up.getEmail());
user.setPassword(up.getPassword());
user.setRole(RoleEnum.PASSENGER);
passenger.setName(up.getName());
passenger.setLastname(up.getLastname());
passenger.setCity(up.getCity());
passenger.setPhone(up.getPhone());
passenger.setAddress(up.getAddress());
passenger.setCity(up.getCity());
passenger.setCountry(up.getCountry());
passenger.setUser(user);
return PassengerBean.miniClone(passengerRepository.save(passenger));
}
public PassengerBean update(UpdatePasswordBean passwordBean, Integer id) {
Optional<Passenger> passenger = passengerRepository.findByIdAndDeletedAtIsNull(id);
if (!passenger.isPresent())
throw new RuntimeException("Agent not found!");
Passenger passengerBd = passenger.get();
passengerBd.getUser().setPassword(passwordBean.getPassword());
return PassengerBean.miniClone(passengerRepository.save(passengerBd));
}
public PassengerBean delete(Integer id) {
Optional<Passenger> passenger = this.passengerRepository.findByIdAndDeletedAtIsNull(id);
if (!passenger.isPresent())
throw new NotFoundException(String.format("Passenger with id %d not found!", id));
Passenger passengerDelete = passenger.get();
passengerDelete.setDeletedAt(LocalDate.now());
return PassengerBean.miniClone(this.passengerRepository.save(passengerDelete));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.FlightSearchBean;
import com.bytesw.bytebot.bean.agency.ReservationBean;
import com.bytesw.bytebot.bean.agency.SupervisorBean;
import com.bytesw.bytebot.bean.agency.UpdateReservationStatus;
import com.bytesw.bytebot.model.agency.*;
import com.bytesw.bytebot.model.agency.enums.PaymentStatusEnum;
import com.bytesw.bytebot.model.agency.enums.ReservationStatusEnum;
import com.bytesw.bytebot.model.agency.enums.TicketTypeEnum;
import com.bytesw.bytebot.model.agency.enums.TravelClassEnum;
import com.bytesw.bytebot.repository.agency.AgencyAgentRepository;
import com.bytesw.bytebot.repository.agency.FlightRepository;
import com.bytesw.bytebot.repository.agency.PassengerRepository;
import com.bytesw.bytebot.repository.agency.ReservationRepository;
import com.bytesw.bytebot.service.CustomPaginationService;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import com.bytesw.xdf.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class ReservationService {
@Autowired
private ReservationRepository reservationRepository;
@Autowired
private FlightRepository flightRepository;
@Autowired
private PassengerRepository passengerRepository;
@Autowired
private AgencyAgentRepository agentRepository;
public CustomPaginationBean<ReservationBean> getByPaginationAgent(CustomPaginationBean<ReservationBean> pagination) {
Pageable pageable = CustomPaginationBean.buildPageable(pagination);
Specification<Reservation> specification = (Specification<Reservation>) (root, query, criteriaBuilder)
-> criteriaBuilder.isNull(root.get("deletedAt"));
Page<Reservation> page = reservationRepository.findAll(specification, pageable);
Page<ReservationBean> supervisorBeans = convertPage(page);
return CustomPaginationBean.fromPage(supervisorBeans);
}
public Page<ReservationBean> convertPage(Page<Reservation> originalPage) {
List<ReservationBean> reservationBean = originalPage.getContent().stream()
.map(ReservationBean::miniClone)
.collect(Collectors.toList());
return new PageImpl<>(reservationBean, originalPage.getPageable(), originalPage.getTotalElements());
}
public ReservationBean create(ReservationBean reservationBean) {
Reservation reservation = new Reservation();
Optional<Passenger> passengerOptional = passengerRepository.findByIdAndDeletedAtIsNull(reservationBean.getPassengerId());
if (!passengerOptional.isPresent())
throw new NotFoundException("Passenger not found!!");
Optional<AgencyAgent> agentOptional = agentRepository.findByIdAndDeletedAtIsNull(reservationBean.getAgentId());
if (!agentOptional.isPresent())
throw new NotFoundException("Agent not found!!");
Optional<Flight> flightOptional = flightRepository.findById(reservationBean.getFlightId());
if (!flightOptional.isPresent())
throw new NotFoundException("Flight not found!!");
reservation.setPassenger(passengerOptional.get());
reservation.setAgencyAgent(agentOptional.get());
reservation.setStatus(ReservationStatusEnum.RESERVED);
reservation.setDepartureDate(LocalDateTime.parse(reservationBean.getDepartureDate()));
reservation.setTicketType(TicketTypeEnum.fromString(reservationBean.getTicketType()));
reservation.setTravelClass(TravelClassEnum.fromString(reservationBean.getTravelClass()));
reservation.setFlight(flightOptional.get());
reservation.setCreatedDate(LocalDate.now());
Payment payment = new Payment();
payment.setStatus(PaymentStatusEnum.WAITING);
payment.setDate(LocalDate.now());
payment.setAmount(FlightSearchBean.getAmount(flightOptional.get().getCosts(), LocalDateTime.parse(reservationBean.getDepartureDate())));
reservation.setPayment(payment);
return ReservationBean.miniClone(reservationRepository.save(reservation));
}
public ReservationBean getById(Integer id) {
Optional<Reservation> reservation = reservationRepository.findByIdAndDeletedAtIsNull(id);
if (!reservation.isPresent())
throw new NotFoundException("Reservation not found!");
return ReservationBean.miniClone(reservation.get());
}
public ReservationBean updateStatusReservation(UpdateReservationStatus status, Integer id) {
Optional<Reservation> reservation = reservationRepository.findByIdAndDeletedAtIsNull(id);
if (!reservation.isPresent())
throw new NotFoundException("Reservation not found!!");
ReservationStatusEnum statusEnum = ReservationStatusEnum.fromString(status.getStatus());
reservation.get().setStatus(statusEnum);
if (statusEnum == ReservationStatusEnum.PAID) {
reservation.get().getPayment().setStatus(PaymentStatusEnum.PAID);
reservation.get().getPayment().setDate(LocalDate.now());
} else if (statusEnum == ReservationStatusEnum.CANCELED) {
reservation.get().getPayment().setStatus(PaymentStatusEnum.CANCELED);
reservation.get().getPayment().setDate(LocalDate.now());
} else {
throw new NotFoundException("Status not found!");
}
return ReservationBean.miniClone(reservationRepository.save(reservation.get()));
}
public ReservationBean delete(Integer id) {
Optional<Reservation> reservationOptional = reservationRepository.findByIdAndDeletedAtIsNull(id);
if (!reservationOptional.isPresent())
throw new NotFoundException("Reservation not found!");
reservationOptional.get().setDeletedAt(LocalDate.now());
return ReservationBean.miniClone(reservationRepository.save(reservationOptional.get()));
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.AgentBean;
import com.bytesw.bytebot.bean.agency.SignUpBean;
import com.bytesw.bytebot.bean.agency.SupervisorBean;
import com.bytesw.bytebot.bean.agency.UpdatePasswordBean;
import com.bytesw.bytebot.model.agency.Passenger;
import com.bytesw.bytebot.model.agency.Supervisor;
import com.bytesw.bytebot.model.agency.User;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import com.bytesw.bytebot.repository.agency.AgencyUserRepository;
import com.bytesw.bytebot.repository.agency.SupervisorRepository;
import com.bytesw.bytebot.utils.CustomPaginationBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class SupervisorService {
private final SupervisorRepository supervisorRepository;
private final AgencyUserRepository userRepository;
public SupervisorService(SupervisorRepository supervisorRepository, AgencyUserRepository userRepository) {
this.supervisorRepository = supervisorRepository;
this.userRepository = userRepository;
}
public List<SupervisorBean> getAll() {
List<Supervisor> supervisors = supervisorRepository.findAllByDeletedAtIsNull();
List<SupervisorBean> supervisorBeans = new ArrayList<>();
for (Supervisor supervisor: supervisors) {
supervisorBeans.add(SupervisorBean.miniClone(supervisor));
}
return supervisorBeans;
}
public CustomPaginationBean<SupervisorBean> getByPagination(CustomPaginationBean<SupervisorBean> pagination) {
Pageable pageable = CustomPaginationBean.buildPageable(pagination);
Specification<Supervisor> specification = (Specification<Supervisor>) (root, query, criteriaBuilder)
-> criteriaBuilder.isNull(root.get("deletedAt"));
Page<Supervisor> page = supervisorRepository.findAll(specification, pageable);
Page<SupervisorBean> supervisorBeans = convertPage(page);
return CustomPaginationBean.fromPage(supervisorBeans);
}
public Page<SupervisorBean> convertPage(Page<Supervisor> originalPage) {
List<SupervisorBean> supervisorBeans = originalPage.getContent().stream()
.map(SupervisorBean::miniClone)
.collect(Collectors.toList());
return new PageImpl<>(supervisorBeans, originalPage.getPageable(), originalPage.getTotalElements());
}
public SupervisorBean getByUserId(Integer userId) {
Optional<Supervisor> supervisor = supervisorRepository.findByUser_Id(userId);
if (!supervisor.isPresent())
throw new RuntimeException("Supervisor not found!");
return SupervisorBean.miniClone(supervisor.get());
}
public SupervisorBean getById(Integer id) {
Optional<Supervisor> supervisor = supervisorRepository.findById(id);
if (!supervisor.isPresent())
throw new RuntimeException("Supervisor not found!");
return SupervisorBean.miniClone(supervisor.get());
}
public SupervisorBean create(SignUpBean up) {
Supervisor supervisor = new Supervisor();
User user = new User();
user.setEmail(up.getEmail());
user.setPassword(up.getPassword());
user.setRole(RoleEnum.SUPERVISOR);
supervisor.setName(up.getName());
supervisor.setLastname(up.getLastname());
supervisor.setDetails(up.getDetails());
supervisor.setUser(user);
return SupervisorBean.miniClone(supervisorRepository.save(supervisor));
}
public SupervisorBean update(UpdatePasswordBean passwordBean, Integer id) {
Optional<Supervisor> supervisorOp = supervisorRepository.findById(id);
if (!supervisorOp.isPresent())
throw new RuntimeException("Supervisor not found!");
Supervisor supervisor = supervisorOp.get();
supervisor.getUser().setPassword(passwordBean.getPassword());
return SupervisorBean.miniClone(supervisorRepository.save(supervisor));
}
public SupervisorBean delete(Integer id) {
Optional<Supervisor> supervisors = supervisorRepository.findByIdAndDeletedAtIsNull(id);
if (!supervisors.isPresent())
throw new RuntimeException("Supervisor not found!");
Supervisor supervisor = supervisors.get();
supervisor.setDeletedAt(LocalDate.now());
userRepository.save(supervisor.getUser());
return SupervisorBean.miniClone(supervisor);
}
}
package com.bytesw.bytebot.service.agency;
import com.bytesw.bytebot.bean.agency.*;
import com.bytesw.bytebot.model.agency.Passenger;
import com.bytesw.bytebot.model.agency.User;
import com.bytesw.bytebot.model.agency.enums.RoleEnum;
import com.bytesw.bytebot.repository.agency.AgencyUserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional;
@Service
@Transactional
public class UserService {
private final AgencyUserRepository agencyUserRepository;
private final AgencyAgentService agencyAgentService;
private final PassengerService passengerService;
private final SupervisorService supervisorService;
public UserService(AgencyUserRepository agencyUserRepository, AgencyAgentService agencyAgentService, PassengerService passengerService, SupervisorService supervisorService) {
this.agencyUserRepository = agencyUserRepository;
this.agencyAgentService = agencyAgentService;
this.passengerService = passengerService;
this.supervisorService = supervisorService;
}
public ResponseEntity<?> signIn(SignInBean in) {
Optional<User> user =
agencyUserRepository.findByEmailAndPassword(in.getEmail(), in.getPassword());
if (!user.isPresent())
throw new RuntimeException("Email y/o password incorrect!");
RoleEnum role = user.get().getRole();
switch (role) {
case PASSENGER:
PassengerBean passengerBean = passengerService.getByUserId(user.get().getId());
return ResponseEntity.status(HttpStatus.OK).body(passengerBean);
case AGENT:
AgentBean agentBean = agencyAgentService.getByUserId(user.get().getId());
return ResponseEntity.status(HttpStatus.OK).body(agentBean);
case SUPERVISOR:
SupervisorBean supervisorBean = supervisorService.getByUserId(user.get().getId());
return ResponseEntity.status(HttpStatus.OK).body(supervisorBean);
}
throw new RuntimeException("An error occurred white save user");
}
public ResponseEntity<?> signUp(SignUpBean up) {
RoleEnum role = RoleEnum.fromString(up.getRole().toUpperCase());
switch (role) {
case AGENT:
AgentBean agentBean = agencyAgentService.create(up);
return ResponseEntity.status(HttpStatus.CREATED).body(agentBean);
case PASSENGER:
PassengerBean passengerBean = passengerService.create(up);
return ResponseEntity.status(HttpStatus.CREATED).body(passengerBean);
case SUPERVISOR:
SupervisorBean supervisorBean = supervisorService.create(up);
return ResponseEntity.status(HttpStatus.CREATED).body(supervisorBean);
}
throw new RuntimeException("Error occurred white try to save user");
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.jdbc.ActionJDBCRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.xdf.sql.beans.Pagination;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@Service
public class CustomerInteractionDashboardService extends DashboardService {
@Autowired
private MessageJDBCRepository messageJDBCRepository;
@Autowired
private ActionJDBCRepository actionJDBCRepository;
@Override
protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Integer rangeMinutes,Map<String, Object> info) {
List<RangeBean> rangeList = calculateRangeList(startDate, endDate);
info.put("sessionFlow", generateInteractionByCustomerData(startDate, endDate));
info.put("summaryGoals", generateSummaryByGoals(startDate, endDate));
info.put("intentAvgByCustomer", generateAverageIntentsByCustomer(rangeList));
info.put("summaryIntents", generateSummaryMessageByIntent(rangeList,startDate,endDate));
}
private List<ActionSummaryByGoalBean> generateSummaryByGoals(OffsetDateTime startDate, OffsetDateTime endDate) {
List<ActionSummaryByGoalBean> actionByGoalList;
actionByGoalList = actionJDBCRepository.getSummaryByGoals(startDate, endDate);
if (actionByGoalList == null) {
actionByGoalList = new ArrayList<>();
}
return actionByGoalList;
}
private Map<String, List<Object>> generateSummaryMessageByIntent(List<RangeBean> rangeList,OffsetDateTime startDate, OffsetDateTime endDate) {
List<MessageByIntentBean> total_list = messageJDBCRepository.countMessageByIntent(startDate,endDate);
Map<String, List<Object>> data = new HashMap<>();
rangeList.stream().forEach(x -> {
List<String> identifiers = new ArrayList<>();
List<MessageByIntentBean> list = messageJDBCRepository.countMessageByIntent(x.getStartDate(), x.getEndDate());
list.stream().forEach(intentSummary -> {
identifiers.add((intentSummary.getIdentifier()));
if (!data.containsKey(intentSummary.getIdentifier())){
data.put(intentSummary.getIdentifier(), new ArrayList<>());
}
data.get(intentSummary.getIdentifier()).add(new Object[]{getDayOnStart(x.getStartDate()).toInstant().toEpochMilli()/1000, intentSummary.getCount()});
});
total_list.stream().forEach(intentSummary -> {
if(!identifiers.contains(intentSummary.getIdentifier())){
if(!data.containsKey(intentSummary.getIdentifier())){
data.put(intentSummary.getIdentifier(),new ArrayList<>());
}
data.get(intentSummary.getIdentifier()).add(new Object[]{getDayOnStart(x.getStartDate()).toInstant().toEpochMilli()/1000, 0});
}
});
});
return data;
}
private List<Object[]> generateAverageIntentsByCustomer(List<RangeBean> rangeList) {
List<Object[]> averageList = new ArrayList<>();
rangeList.stream().forEach(x -> {
LocalDateTime times = x.getStartDate().toLocalDateTime().plusHours(12);
Long timestamp = Timestamp.valueOf(times).getTime();
Double avg = messageJDBCRepository.avgIntentsByCustomerAndRange(x.getStartDate(), x.getEndDate());
if(avg!=null){
averageList.add(new Object[]{timestamp,avg});
}
});
return averageList;
}
private double round(Double value) {
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(2, RoundingMode.HALF_UP);
return bd.doubleValue();
}
private Map<String, Map<String, Object>> generateInteractionByCustomerData(OffsetDateTime startDate, OffsetDateTime endDate) {
Map<String, Map<String, Object>> data = new HashMap<>();
data.put("intent", new HashMap<>());
List<SummaryMessageByIntentBean> intentTopList = messageJDBCRepository.getSummaryByIntent(startDate, endDate);
int totalIntents = messageJDBCRepository.countByIntentAndRange(startDate, endDate);
if (intentTopList == null) {
new ArrayList<>();
}
BigInteger result = intentTopList.stream()
.map(SummaryMessageByIntentBean::getCount)
.reduce(BigInteger.ZERO, BigInteger::add);
SummaryMessageByIntentBean others = new SummaryMessageByIntentBean();
others.setCount(new BigInteger(String.valueOf(totalIntents)).subtract(result));
others.setId(0L);
others.setIdentifier("others");
if(others.getCount().intValue()>0){
intentTopList.add(others);
}
data.get("intent").put("total", totalIntents);
data.get("intent").put("topList", intentTopList);
List<SummaryMessageBySentenceBean> sentenceTopList = messageJDBCRepository.getSummaryBySentence(startDate, endDate);
int totalSentences = messageJDBCRepository.countBySentencesAndRange(startDate, endDate);
if (sentenceTopList == null) {
sentenceTopList = new ArrayList<>();
}
data.put("sentence", new HashMap<>());
BigInteger resultSentence = sentenceTopList.stream()
.map(SummaryMessageBySentenceBean::getCount)
.reduce(BigInteger.ZERO, BigInteger::add);
SummaryMessageBySentenceBean othersSentence = new SummaryMessageBySentenceBean();
othersSentence.setCount(new BigInteger(String.valueOf(totalSentences)).subtract(resultSentence));
othersSentence.setId(0L);
othersSentence.setIdentifier("others");
if(othersSentence.getCount().intValue()>0){
sentenceTopList.add(othersSentence);
}
data.get("sentence").put("topList", sentenceTopList);
data.get("sentence").put("total", totalSentences);
return data;
}
public void getSummaryByIntentAndSentencePagination(Pagination<SummaryMessageBySentenceBean> pagination) {
int total = messageJDBCRepository.countSummaryByIntentAndSentence(pagination);
int totalPages = total / pagination.getItemsPerPage();
if (total % pagination.getItemsPerPage() != 0) {
totalPages++;
}
pagination.setTotalItems(total);
pagination.setTotalPages(totalPages);
List<SummaryMessageBySentenceBean> list = messageJDBCRepository.getSummaryByIntentAndSentence(pagination);
list.stream().forEach(x -> {
int customers = messageJDBCRepository.countCustomersBySentence(x.getSentence());
x.setCustomerCount(BigInteger.valueOf(customers));
});
pagination.setData(list);
}
public void getSummaryBySentencePagination(Pagination<SummaryMessageBySentenceBean> pagination) {
int total = messageJDBCRepository.countSummaryBySentence(pagination);
int totalPages = total / pagination.getItemsPerPage();
if (total % pagination.getItemsPerPage() != 0) {
totalPages++;
}
pagination.setTotalItems(total);
pagination.setTotalPages(totalPages);
List<SummaryMessageBySentenceBean> list = messageJDBCRepository.getMessageBySentencePage(pagination);
pagination.setData(list);
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.RangeBean;
import lombok.extern.log4j.Log4j2;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
public abstract class DashboardService {
abstract void completeData(OffsetDateTime startDate, OffsetDateTime endDate,
Integer rangeMinutes, Map<String, Object> info);
public Map<String, Object> generateInfo(Map<String, Object> params) {
Map<String, Object> info = new HashMap<>();
log.info(params);
if (params == null) {
return info;
}
OffsetDateTime startDate = convertToOffsetDatetime((String) params.get("startDate"));
OffsetDateTime endDate = convertToOffsetDatetime((String) params.get("endDate"));
Integer rangeMinutes = (Integer)params.get("rangeMinutes");
if (startDate == null || endDate == null) {
return info;
}
this.completeData(startDate, endDate, rangeMinutes, info);
return info;
}
protected OffsetDateTime convertToOffsetDatetime(String date) {
if (date.length() == 24) {
date = date.substring(0, date.length() - 1);
}
OffsetDateTime dateOffset = null;
try {
LocalDateTime dateParsed = LocalDateTime.parse(date);
dateOffset = OffsetDateTime.ofInstant(dateParsed.toInstant(ZoneOffset.UTC), ZoneId.systemDefault());
} catch (Exception e) {
log.warn(e);
}
return dateOffset;
}
protected OffsetDateTime getNextHour(OffsetDateTime date) {
OffsetDateTime nextDate = date.plusHours(1);
nextDate = nextDate.withMinute(0);
nextDate = nextDate.withSecond(0);
nextDate = nextDate.withNano(0);
return nextDate;
}
protected OffsetDateTime getNextDay(OffsetDateTime date) {
OffsetDateTime newDate = date.plusDays(1);
newDate = newDate.withSecond(0);
newDate = newDate.withMinute(0);
newDate = newDate.withHour(0);
newDate = newDate.withNano(0);
return newDate;
}
protected OffsetDateTime getDayOnStart(OffsetDateTime date) {
OffsetDateTime nextDate = date.withHour(12);
nextDate = nextDate.withMinute(0);
nextDate = nextDate.withSecond(0);
nextDate = nextDate.withNano(0);
return nextDate;
}
protected List<RangeBean> calculateMinutesRangeList(OffsetDateTime startDate, OffsetDateTime endDate, Integer range){
List<RangeBean> rangeList = new ArrayList<>();
OffsetDateTime nextRange = startDate.plusMinutes(range);
OffsetDateTime startNextRange = startDate;
while(nextRange.isBefore(endDate)){
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextRange);
rangeBean.setEndDate(nextRange);
rangeList.add(rangeBean);
startNextRange = nextRange;
nextRange = nextRange.plusMinutes(range);
}
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextRange);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
return rangeList;
}
protected List<RangeBean> calculateRangeList(OffsetDateTime startDate, OffsetDateTime endDate) {
OffsetDateTime nextDate = getNextDay(startDate);
OffsetDateTime startNextDate = startDate;
List<RangeBean> rangeList = new ArrayList<>();
while (nextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(nextDate);
rangeList.add(rangeBean);
startNextDate = nextDate;
nextDate = getNextDay(nextDate);
}
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
return rangeList;
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.AverageBean;
import com.bytesw.bytebot.bean.RangeBean;
import com.bytesw.bytebot.bean.SummaryBean;
import com.bytesw.bytebot.bean.SessionByClientBean;
import com.bytesw.bytebot.jdbc.BotSessionJDCBRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.bytebot.jdbc.ResponseJDBCRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bytesw.bytebot.model.enums.MetricMessageTypeEnum;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.*;
import java.util.*;
@Log4j2
@Service
public class OperativeDashboardService extends DashboardService {
@Autowired
private BotSessionJDCBRepository botSessionJDCBRepository;
@Autowired
private MessageJDBCRepository messageJDBCRepository;
@Autowired
private ResponseJDBCRepository responseJDBCRepository;
@Override
protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Integer rangeMinutes, Map<String, Object> info) {
if (startDate.isAfter(endDate)) {
throw new NotFoundException("Invalid data range");
}
List<RangeBean> rangeList = calculateRangeList(startDate, endDate);
List<RangeBean> rangeMinutsList = calculateMinutesRangeList(startDate, endDate, rangeMinutes);
List<Object[]> messageByActivity = generateData(rangeList);
//Cantidad de sesiones
List<Object[]> sessions = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.SESSION.getName());
int totalSessions = botSessionJDCBRepository.countSessionInRange(startDate, endDate);
// Mensajes recibidos
List<Object[]> recivedMessages = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.RECEIVED.getName());
int totalrecivedMessages = messageJDBCRepository.countSessionInRange(startDate, endDate);
// Mensajes enviados
List<Object[]> responseMessages = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.SENT.getName());
int totalresponseMessages = responseJDBCRepository.countSessionInRange(startDate, endDate);
//Promedio primera respuesta en mili
Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate);
Double avgFirstResponse;
if (avgFRObject instanceof Long) {
avgFirstResponse = new Double((Long) avgFRObject);
} else {
avgFirstResponse = (Double) avgFRObject;
}
Double avgSessionsByCustomerRaw = botSessionJDCBRepository.getAvgSessionByCustomerInRange(startDate, endDate);
// Tomar solo parte entera
if (avgSessionsByCustomerRaw == null){
avgSessionsByCustomerRaw = 0.0;
}
int avgSessionsByCustomer = avgSessionsByCustomerRaw.intValue();
Timestamp timestamp = botSessionJDCBRepository.getLastDateInRage(startDate, endDate);
if (timestamp == null) {
throw new NotFoundException("No se encontró una sesión en el rango de fechas indicado");
}
//Calculando el tiempo de inactividad de la sesion
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate);
// Adjuntando tiempo de inactividad
SummaryBean sessionInactivity = new SummaryBean();
BigInteger value = new BigInteger(String.valueOf(difference.getSeconds()));
sessionInactivity.setValue(value);
// Adjutando las sesiones totales
Map<String,Object> totalSession = new HashMap<>();
totalSession.put("value",totalSessions);
totalSession.put("history",sessions);
// Adjuntamos los mensajes recibidos
Map<String, Object> recivedMessage = new HashMap<>();
recivedMessage.put("value", totalrecivedMessages);
recivedMessage.put("history", recivedMessages);
// Adjuntamos los mensajes enviados
Map<String, Object> responseMessage = new HashMap<>();
responseMessage.put("value", totalresponseMessages);
responseMessage.put("history", responseMessages);
Map<String, Object> summary = new HashMap<>();
summary.put("sessionInactivity", sessionInactivity);
summary.put("totalSessions", totalSession);
summary.put("totalSentMessages", responseMessage);
summary.put("totalReceivedMessages", recivedMessage);
AverageBean averageBean = new AverageBean();
if (avgFirstResponse == null) {
averageBean.setFirstResponseAverage(new BigDecimal(0));
} else {
averageBean.setFirstResponseAverage(new BigDecimal(avgFirstResponse));
}
averageBean.setSessionAverage(new BigDecimal(avgSessionsByCustomer));
info.put("summary", summary);
info.put("averages", averageBean);
info.put("customerMessageDetail", messageByActivity);
}
private List<Object[]> generateDataVariablePeriod(List<RangeBean> rangeList, String metric) {
List<Object[]> data = new ArrayList<>();
Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>();
int cont = 0;
for (RangeBean range : rangeList) {
int cant = 0;
if (metric.equals(MetricMessageTypeEnum.RECEIVED.getName())) {
cant = messageJDBCRepository.countMessageInRangeHour(range.getStartDate(), range.getEndDate());
} else if (metric.equals(MetricMessageTypeEnum.SENT.getName())) {
cant = responseJDBCRepository.countSessionInRange(range.getStartDate(), range.getEndDate());
}else if (metric.equals(MetricMessageTypeEnum.SESSION.getName())){
cant = botSessionJDCBRepository.countSessionInRange(range.getStartDate(), range.getEndDate());
}
LocalDateTime times = range.getStartDate().toLocalDateTime();
Long timestamp = Timestamp.valueOf(times).getTime();
if (!accumulated.containsKey(timestamp)) {
accumulated.put(timestamp, new HashMap<>());
}
accumulated.get(timestamp).put(cont, cant);
cont++;
}
accumulated.keySet().stream().forEach(x -> {
accumulated.get(x).keySet().stream().forEach(y -> {
data.add(new Object[]{x, accumulated.get(x).get(y)});
});
});
return data;
}
private List<Object[]> generateData(List<RangeBean> rangeList) {
List<Object[]> data = new ArrayList<>();
Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>();
for (RangeBean range : rangeList) {
List<RangeBean> hourRanges = getRangeHours(range.getStartDate(), range.getEndDate());
for (RangeBean hourRange : hourRanges) {
int cant = messageJDBCRepository.countMessageInRangeHour(hourRange.getStartDate(), hourRange.getEndDate());
int rangeHour = getRangeHour(hourRange.getStartDate().getHour());
Long timestamp = getTimestamp(hourRange.getStartDate());
if (!accumulated.containsKey(timestamp)) {
accumulated.put(timestamp, new HashMap<>());
}
if (!accumulated.get(timestamp).containsKey(rangeHour)) {
accumulated.get(timestamp).put(rangeHour, 0);
}
accumulated.get(timestamp).put(rangeHour, accumulated.get(timestamp).get(rangeHour) + cant);
}
}
accumulated.keySet().stream().forEach(x -> {
accumulated.get(x).keySet().stream().forEach(y -> {
data.add(new Object[]{x, y, accumulated.get(x).get(y)});
});
});
return data;
}
private int getRangeHour(int hour) {
switch (hour) {
case 3:
case 4:
case 5:
return 1;
case 6:
case 7:
case 8:
return 2;
case 9:
case 10:
case 11:
return 3;
case 12:
case 13:
case 14:
return 4;
case 15:
case 16:
case 17:
return 5;
case 18:
case 19:
case 20:
return 6;
case 21:
case 22:
case 23:
return 7;
default:
return 0;
}
}
private long getTimestamp(OffsetDateTime date) {
OffsetDateTime dateTime;
dateTime = date.withHour(0);
dateTime = dateTime.withMinute(0);
dateTime = dateTime.withSecond(0);
dateTime = dateTime.withNano(0);
return dateTime.toInstant().toEpochMilli();
}
private List<RangeBean> getRangeHours(OffsetDateTime startDate, OffsetDateTime endDate) {
OffsetDateTime nextDate = getNextHour(startDate);
OffsetDateTime startNextDate = startDate;
List<RangeBean> rangeList = new ArrayList<>();
while (nextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(nextDate);
rangeList.add(rangeBean);
startNextDate = nextDate;
nextDate = getNextHour(nextDate);
}
if (startNextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
}
return rangeList;
}
}
package com.bytesw.bytebot.service.provider;
import com.bytesw.xdf.exception.NotFoundException;
import com.twilio.exception.AuthenticationException;
import lombok.extern.log4j.Log4j2;
import java.util.HashMap;
import java.util.Map;
@Log4j2
public abstract class ProviderService {
abstract void completeData(Map<String, Object> info, String SmsId, int Agent_id) throws Exception;
public Map<String, Object> generateInfo(String sid, Map<String, Object> params) throws AuthenticationException {
Map<String, Object> info = new HashMap<>();
if (params == null) {
return info;
}
try {
int agen_id = (Integer) params.get("agent_id");
this.completeData(info, sid, agen_id);
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch (java.lang.ClassCastException e) {
log.info("Body Input inválido");
throw new ClassCastException("Input inválido");
} catch (AuthenticationException e) {
throw new AuthenticationException(e.getMessage());
} catch (InternalError e) {
throw new InternalError(e.getMessage());
} catch (Exception e) {
throw new InternalError(e.getMessage());
}
return info;
}
}
package com.bytesw.bytebot.service.provider;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.ChannelEnum;
import com.bytesw.bytebot.model.enums.ProviderErrorEnum;
import com.bytesw.bytebot.service.AgentService;
import com.bytesw.xdf.exception.NotFoundException;
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.exception.AuthenticationException;
import com.twilio.rest.api.v2010.account.message.Media;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Log4j2
@Service
public class TwilioService extends ProviderService {
@Autowired
private AgentService agentService;
public List<DeploymentChannelParamValueBean> getAllParamsWithRefresh() {
return getAllParams();
}
public List<DeploymentChannelParamValueBean> getAllParams() {
List<DeploymentChannelParamValueBean> agents = new ArrayList<>();
agents = agentService.GetKeysFromAgents(AgentStatusEnum.DEPLOYED);
return agents;
}
@Override
protected void completeData(Map<String, Object> info, String SmsId, int agent_id) throws Exception {
long start_time = System.nanoTime();
List<DeploymentChannelParamValueBean> agents = getAllParamsWithRefresh();
long end_time = System.nanoTime();
long duration = (end_time - start_time) / 1000000;
log.debug("DURACION: " + duration);
String sid = "";
String token = "";
int MAX_LIMIT = 999;
List<String> data = new ArrayList<String>();
log.debug(agents);
try {
boolean exist_agent = false;
for (DeploymentChannelParamValueBean agent : agents) {
if (agent.getAgen_id() == agent_id && agent.getChannel().equals(ChannelEnum.WHATSAPP.getName())) {
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_ID.getName())) {
sid = agent.getValue();
}
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_TOKEN.getName())) {
token = agent.getValue();
}
exist_agent = true;
}
}
if (!exist_agent) {
log.info("No existe un agente con el ID especificado");
throw new Exception("No se encontró un agente con canales deployados con dicho ID");
}
String[] images_droped = new String[MAX_LIMIT];
Twilio.init(sid, token);
ResourceSet<Media> media = Media.reader(SmsId).limit(MAX_LIMIT).read();
int cont = 0;
for (Media record : media) {
Media.deleter(SmsId, record.getSid()).delete();
images_droped[cont] = record.getSid();
cont++;
}
if (cont == 0) {
log.info("No hay imágenes para el mensaje indicado");
throw new NotFoundException("No se encontraron imágenes para el mensaje " + SmsId);
} else {
for (String image : Arrays.copyOfRange(images_droped, 0, cont)) {
data.add(image);
}
}
info.put("status", "success");
info.put("data", data);
} catch (com.twilio.exception.ApiException e) {
if (e.getMessage().equals(ProviderErrorEnum.AUTHENTICATE.getName())) {
log.error("Credenciales inválidas para borrar imagen");
throw new AuthenticationException("Credenciales inválidas");
} else if (e.getMessage().contains(ProviderErrorEnum.CONEXION.getName())) {
log.error("Fallo temporal en la conexión con el Proveedor");
throw new InternalError("Fallo en la conexión con Twilio API");
} else {
log.info("El mensaje no existe para : " + SmsId + "\n" + e.getMessage());
throw new NotFoundException("No se encontraron imágenes para el mensaje " + SmsId);
}
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
package com.bytesw.bytebot.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
public class CustomMapper {
/*public static <T, S> S mapTo(Class<S> destinationClass, T sourceObject) {
try {
Constructor<S> constructor = destinationClass.getDeclaredConstructor();
S destinationObject = constructor.newInstance();
Field[] sourceFields = sourceObject.getClass().getDeclaredFields();
for (Field sourceField : sourceFields) {
sourceField.setAccessible(true);
Field destinationField;
try {
destinationField = destinationClass.getDeclaredField(sourceField.getName());
} catch (NoSuchFieldException e) {
//System.out.println("Campo no encontrado en la clase de destino: " + sourceField.getName());
continue; // Ignora el campo y pasa al siguiente
}
destinationField.setAccessible(true);
Object sourceFieldValue = sourceField.get(sourceObject);
if (sourceFieldValue != null && !sourceField.getType().isPrimitive() && !sourceField.getType().getName().startsWith("java")) {
// Si el campo es un objeto y no es un tipo primitivo ni un tipo de Java (como Integer, String, etc.)
Object nestedDestinationObject = mapTo(destinationField.getType(), sourceFieldValue);
destinationField.set(destinationObject, nestedDestinationObject);
} else {
destinationField.set(destinationObject, sourceFieldValue);
}
}
return destinationObject;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error during mapping", e);
}
}*/
/*public static <T, S> List<S> mapListTo(Class<S> destinationClass, List<T> sourceList) {
return sourceList.stream()
.map(item -> mapTo(destinationClass, item))
.collect(Collectors.toList());
}*/
}
package com.bytesw.bytebot.utils;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
public class CustomPaginationBean<T> {
@Expose
private int currentPage;
@Expose
private List<T> data;
@Expose
private int itemsPerPage;
@Expose
private List<SortFieldBean> sortFields;
@Expose
private int totalItems;
@Expose
private int totalPages;
public static <T> Pageable buildPageable(CustomPaginationBean<T> originPagination) {
int currentPage = originPagination.getCurrentPage();
int itemsPerPage = originPagination.getItemsPerPage();
List<SortFieldBean> sortFields = originPagination.getSortFields();
Sort sort = null;
if (sortFields != null && !sortFields.isEmpty()) {
sort = Sort.by(sortFields.stream()
.map(sf -> sf.getDirection().equals("desc") ? Sort.Order.desc(sf.getField()) : Sort.Order.asc(sf.getField()))
.toArray(Sort.Order[]::new));
return PageRequest.of(currentPage, itemsPerPage, sort);
}
return PageRequest.of(currentPage, itemsPerPage);
}
public static <T> CustomPaginationBean<T> fromPage(Page<T> page) {
CustomPaginationBean<T> customPagination = new CustomPaginationBean<>();
customPagination.setCurrentPage(page.getNumber());
customPagination.setItemsPerPage(page.getSize());
customPagination.setTotalItems((int) page.getTotalElements());
customPagination.setTotalPages(page.getTotalPages());
customPagination.setData(page.getContent());
if (page.getPageable().getSort() == null) {
customPagination.setSortFields(new ArrayList<>());
}
else {
List<SortFieldBean> sorts = page.getPageable().getSort().stream().map(sort -> {
SortFieldBean sortBean = new SortFieldBean();
sortBean.setDirection(sort.getDirection().name());
sortBean.setField(sort.getProperty());
return sortBean;
}).collect(Collectors.toList());
customPagination.setSortFields(sorts);
}
return customPagination;
}
}
package com.bytesw.bytebot.utils;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SortFieldBean {
private String direction;
private String field;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Utilities {
public static String convertDateToString(Date date, String format){
DateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:applicationContext-aop.xml" />
<import resource="classpath:applicationContext-datasource.xml" />
<import resource="classpath:applicationContext-scheduler.xml" />
</beans>
spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration
server:
servlet.context-path: ${APPLICATION_PATH:/AVB}
port: ${APPLICATION_PORT:9077}
web:
#static-content-location: file:/home/mgutierrez/Documentos/Bytesw/bytebot-workspace/dist/bytebot-html/
static-content-location: file:/home/hcordova/Descargas/bytebot-workspace/dist/bytebot-html/
security:
require-ssl: false
hystrix.shareSecurityContext: true
# oracle
endpoints:
shutdown:
enabled: true
management:
endpoints:
shutdown.enabled: true
web.exposure.include: "*"
application:
byte-bot:
batch:
chunk: 10
cron: 0 0/1 * * * *
show-side-bar: false
test: ENC(OEchnTXpIZnCVdPNthgCZBfQjMt1AUS1)
name: AVB-HDI
license:
applicationId: test
clientId: test
hosts: 38F9D38DD09
type: web # web o service
security:
enabled: true
encryption-key: ENC(0WRfEFi8lYjlJj2bj37z4TRu4zmPnmXl4zM4Jpdh1H8=)*
web:
server: docker # weblogic, docker
ignore:
path: /v2/api-docs, /configuration/**, /swagger-resources/**, /swagger-ui.html, /webjars/**, /api-docs/**, /resources/**, /css/**, /js/**, /fonts/**, /img/**, /modules/**, /system/**, /views/**, /font-awesome/**, /translations/**, /bower_components/**, /cache.manifest, /favicon.ico, /service/file, /providers/**
goodbyeURL: /goodbye
api.info:
title: 'pilotoXDF Service'
description: 'API para el desarrollo de software'
version: '1.0.0'
terms-of-service-url: 'https://es.wikipedia.org/wiki/byteXDF4Java'
license: 'Open source licensing'
license-url: 'https://help.github.com/articles/open-source-licensing/'
services:
multi-tenant-conf:
exclude-service: /
authorization-service.url: http://localhost:17580
security: none #oauth2sso none, basic, oauth2sso
security.method: true
security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot
messaging:
queue-support: activemq
multi-tenant: false
clustering: true
database: true
send-email: false
jt400: false
rabbitMQ: true
webservices: false
statistics.type: log # database or log
messaging:
queue-test: action_queue.fifo
topic-test: topic-test
AVB-integration:
ftp:
host: localhost
username: ftp
password: ftp
directory: uploadBYTEBOT/IMG/
# email.info:
# smtp:
# host: smtp.gmail.com
# port: 587
# username: mortiz@bytesw-bfm.com
# encrypted.password: ENC(OEchnTXpIZnCVdPNthgCZBfQjMt1AUS1)
# from.email: mortiz@bytesw-bfm.com
# jt400.info:
# username: usuario24
# password: poiuyt5
# host: 192.168.27.30
# queue-name: V4STCPGM.LIB/COLGENESIS.DTAQ
rabbitMQ.info:
host: localhost
port: 8161
queue-name: task_queue
timezone:
zone: TimeZone
default: America/Mexico_City
bucket:
deployment: DeployMode
parameter: KnowledgeBaseBucket
tenant: T186A1
region: us-east-1
fileBucket: KB_Files
modelBucket: KB_Model
version: "1.0"
knowledge:
url: "http://127.0.0.1:3000/byteknowledgebaseApi"
scheduler:
cron: 0 0/1 * * * *
spring:
main:
allow-bean-definition-overriding: true
mbeans.exclude: dataSource
application:
name: AVB-HDI
datasource:
database-type: postgres
schemaName: bytebot
url: jdbc:postgresql://192.168.100.4:5432/bytebot?useSSL=false&currentSchema=avb_hdi
# schemaName: avb
# url: jdbc:postgresql://192.168.100.4:5432/bytebot?useSSL=false&currentSchema=avb_hdi
driverClassName: 'org.postgresql.Driver'
username: postgres
password: postgres
minimum-idle: 10
maximum-pool-size: 10
validationQuery: SELECT 1
testWhileIdle: true
hikari.registerMbeans: true
security:
basepath: http://localhost:9077/AVB
provider: byte # oracle, amazon
oauth2-client:
clientId: xdf-client
clientSecret: xdf-secret
accessTokenUri: http://192.168.0.119:18080/oauth/token
userAuthorizationUri: http://192.168.0.119:18080/oauth/authorize
oauth2-resource:
userInfoUri: http://192.168.0.119:18080/oauth/userinfo
logoutUri: http://192.168.0.119:18080/oauth/userlogout
tenants:
-
id: T186A1
servername: prueba_avb
datasource:
database-type: postgres
schemaName: avb
url: jdbc:postgresql://192.168.100.4:5432/avb?useSSL=false
driverClassName: 'org.postgresql.Driver'
username: postgres
password:
minimum-idle: 10
maximum-pool-size: 10
validationQuery: SELECT 1
testWhileIdle: true
hikari.registerMbeans: true
security:
basepath: http://localhost:9077/AVB
provider: byte # oracle, amazon
oauth2-client:
clientId: xdf-client
clientSecret: xdf-secret
accessTokenUri: http://192.168.100.4:18080/oauth/token
userAuthorizationUri: http://192.168.100.4:18080/oauth/authorize
oauth2-resource:
userInfoUri: http://192.168.100.4:18080/oauth/userinfo
logoutUri: http://192.168.100.4:18080/oauth/userlogout
jpa:
show-sql: true
open-in-view: true
properties.hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect #org.hibernate.dialect.MySQL5Dialect
format_sql: false
hbm2ddl.auto: update #none
jdbc:
lob:
non_contextual_creation: true
#session.store-type: jdbc
activemq.broker-url: tcp://localhost:61616
batch:
tenants:
-
id: T186A1
datasource:
jdbc-driver: 'org.postgresql.Driver'
username: postgres
password:
jdbc-url: jdbc:postgresql://192.168.21.74:5432/avb?useSSL=false&currentSchema=avb
query: 'select * from events WHERE id > %d order by id asc'
logging.level.root: INFO
logging.pattern.console: '%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n'
logging.level.com.zaxxer.hikari: ERROR
logging.level.springfox.documentation: ERROR
logging.level.org.kie.api.internal: ERROR
logging.level.org.springframework: ERROR
logging.level.org.apache.catalina.core: ERROR
logging.level.org.apache: ERROR
logging.level.org.quartz: ERROR
logging.level.com.bytesw-bfm.xdf.example.security: ERROR
logging.level.net.javacrumbs.shedlock: ERROR
logging.level.com.github.alturkovic.lock: ERROR
logging.level.com.ulisesbocchio.jasyptspringboot: ERROR
#logging.level.org.hibernate.SQL: TRACE
#logging.level.org.hibernate.type: TRACE
#logging.level.net.sf.hibernate.type: TRACE
jasypt.encryptor.password: 179CD78D24F9BC63D6E677272D1A7
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
">
<aop:aspectj-autoproxy proxy-target-class="true" />
<aop:config>
<aop:pointcut id="allServiceMethodsPointcut" expression="execution(* com.bytesw.xdf.example.controller.*.*(..)) || execution(* com.bytesw.xdf.controller.*.*(..))" />
<!--<aop:pointcut id="authResourcesMethodsPointcut" expression="execution(* org.springframework.security.oauth2.client.OAuth2RestTemplate.*(..))" />-->
<aop:advisor pointcut-ref="allServiceMethodsPointcut" advice-ref="statisticsInterceptor" />
<!--<aop:advisor pointcut-ref="authResourcesMethodsPointcut" advice-ref="authResourcerInterceptor" />-->
</aop:config>
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<jpa:repositories base-package="com.bytesw" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="2" />
<property name="maxPoolSize" value="5" />
<property name="queueCapacity" value="5" />
<property name="waitForTasksToCompleteOnShutdown" value="true" />
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
</property>
</bean>
<!--<bean name="testServiceJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="name" value="SCH00001: Test Service"/>
<property name="group" value="Security"/>
<property name="targetObject" ref="testService"/>
<property name="targetMethod" value="saludar"/>
</bean>
<bean id="testServiceTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="testServiceJob"/>
<property name="cronExpression" value="0/1 * * * * ?"/>
</bean>-->
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ActionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal
FROM AVB_ACTION_SESSION BAS
JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID;
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.AgentMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getCredentialsFromAgentandChannel" resultType="DeploymentChannelParamValue" flushCache="true">
SELECT chpv_id as id,
chpa_label as channelParamName,
chpv_value as value,
AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.MessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<!-- @TODO Pendiente agregar la fecha -->
<select id="getSummaryByIntentAndSentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY ${columnSort} ${directionSort} LIMIT ${initLimit},${itemsForPage}
</select>
<select id="countSummaryByIntentAndSentence" resultType="int" flushCache="true">
select count(*) FROM (SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY count DESC) as AVB_SUMMARY
</select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4
</select>
<select id="getSummaryBySentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY ${columnSort} ${directionSort}, identifier DESC LIMIT ${initLimit},${itemsForPage}
</select>
<select id="countSummaryBySentence" resultType="int" flushCache="true">
SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select>
<select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT
COUNT(M.MESSA_ID)
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
left join avb_blacklist_params abkp
on abkp.inten_id=I.inten_id
left join avb_blacklist abk
on abk.blis_id=abkp.blis_id
WHERE INTEN_ID IS NOT NULL
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT
COUNT(MESSA_ID)
FROM AVB_MESSAGE WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="avgIntentsByCustomerAndRange" resultType="Double" flushCache="true">
SELECT AVG (COUNT_MESSA) FROM
(
SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID
FROM AVB_MESSAGE M
LEFT JOIN AVB_SESSION S ON M.SESSION_ID = S.SESSION_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY S.USER_ID
) AVB_INTENT_CUSTOMER
</select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT
COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY I.INTEN_IDENT
</select>
<select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID)
FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID)
FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.SessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT
FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate}
ORDER BY SESSION_LEDAT DESC LIMIT 1
</select>
<select id="countSessionsInRange" resultType="int" flushCache="true">
select count(session_id) from avb_session
WHERE SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
</select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM
(
select count(USER_ID) as SESSION_CANT
from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID
) AVB_SESSION_COUNT
</select>
<select id="avgFirstResponseTime" resultType="Long" flushCache="true">
SELECT AVG(RESP_TIME)
FROM (
select TIMESTAMPDIFF(MICROSECOND, SESSION_DATE, SESSION_FRDAT)/1000 AS RESP_TIME
from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT NULL
AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ActionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal
FROM AVB_ACTION_SESSION BAS
JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID;
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.AgentMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getCredentialsFromAgentandChannel" resultType="DeploymentChannelParamValue" flushCache="true">
SELECT chpv_id as id,
chpa_label as channelParamName,
chpv_value as value,
AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.MessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<!-- @TODO Pendiente agregar la fecha -->
<select id="getSummaryByIntentAndSentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit}
</select>
<select id="countSummaryByIntentAndSentence" resultType="int" flushCache="true">
select count(*) FROM (SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY count DESC) as AVB_SUMMARY
</select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4
</select>
<select id="getSummaryBySentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit}
</select>
<select id="countSummaryBySentence" resultType="int" flushCache="true">
SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select>
<select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT
COUNT(M.MESSA_ID)
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
left join avb_blacklist_params abkp
on abkp.inten_id=I.inten_id
left join avb_blacklist abk
on abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT
COUNT(MESSA_ID)
FROM AVB_MESSAGE WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="avgIntentsByCustomerAndRange" resultType="Double" flushCache="true">
SELECT AVG (COUNT_MESSA) FROM
(
SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID
FROM AVB_MESSAGE M
LEFT JOIN AVB_SESSION S ON M.SESSION_ID = S.SESSION_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY S.USER_ID
) AVB_INTENT_CUSTOMER
</select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT
COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY I.INTEN_IDENT
</select>
<select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID)
FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID)
FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.SessionMapper">
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT
FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate}
ORDER BY SESSION_LEDAT DESC LIMIT 1
</select>
<select id="countSessionsInRange" resultType="int" flushCache="true">
select count(session_id) from avb_session
WHERE SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
</select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM
(
select count(USER_ID) as SESSION_CANT
from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID
) AVB_SESSION_COUNT
</select>
<select id="avgFirstResponseTime" resultType="Double" flushCache="true">
SELECT AVG(RESP_TIME)
FROM (
SELECT DATE_PART('milliseconds', SESSION_FRDAT - SESSION_DATE) AS RESP_TIME
from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT null
AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAgentChannel" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel}
</select>
<select id="getAgentChannelByAgentId" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel} and AG.agen_id = #{agentId}
</select>
<select id="getControl" resultType="DeleteControl" flushCache="true">
SELECT dsmc_id as id,
agent_id as agentId,
dsmc_date as dateDelete,
evnt_id as eventId
FROM avb_delete_sens_msg_control
WHERE agent_id=#{agenId}
</select>
<select id="getIntentByAgent" resultType="String" flushCache="true">
SELECT
inten_ident as intent
FROM avb_intent
WHERE intent_is_sensible = #{sensible} AND agen_id = #{agenId}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLMessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT
MESSA_CORRE
FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT
RESPO_CORR
FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLSessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastSessionByUser" resultType="Session" flushCache="true">
SELECT
SESSION_ID as id,
SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate,
chan_id as channelId,
USER_ID as userId
FROM AVB_SESSION
WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC
LIMIT 1
</select>
<update id="updateLastEventDate" flushCache="true">
UPDATE
AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID}
</update>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAgentChannel" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel}
</select>
<select id="getAgentChannelByAgentId" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel} and AG.agen_id = #{agentId}
</select>
<select id="getControl" resultType="DeleteControl" flushCache="true">
SELECT dsmc_id as id,
agent_id as agentId,
dsmc_date as dateDelete,
evnt_id as eventId
FROM avb_delete_sens_msg_control
WHERE agent_id=#{agenId}
</select>
<select id="getIntentByAgent" resultType="String" flushCache="true">
SELECT
inten_ident as intent
FROM avb_intent
WHERE intent_is_sensible = #{sensible} AND agen_id = #{agenId}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLMessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT
MESSA_CORRE
FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT
RESPO_CORR
FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLSessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastSessionByUser" resultType="Session" flushCache="true">
SELECT
SESSION_ID as id,
SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate,
chan_id as channelId,
USER_ID as userId
FROM AVB_SESSION
WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC
LIMIT 1
</select>
<update id="updateLastEventDate" flushCache="true">
UPDATE
AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID}
</update>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.xdf.dao.jdbc.AuditMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAuditData" resultType="hashmap" flushCache="true">
SELECT ${columns},
SECURITY_AUDIT.REV_USER as username,
SECURITY_AUDIT.REV_MODIF as date,
${tableName}.REVTYPE as revisionType
FROM ${tableName}
LEFT JOIN SECURITY_AUDIT
ON ${tableName}.REV = SECURITY_AUDIT.REV_ID
WHERE ${pkName} = #{pkValue} ORDER BY SECURITY_AUDIT.REV_MODIF DESC
LIMIT ${page},${pageSize}
</select>
<select id="countAuditData" resultType="int" flushCache="true">
SELECT count(${pkName})
FROM ${tableName}
WHERE ${pkName} = #{pkValue}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.xdf.dao.jdbc.AuditMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAuditData" resultType="hashmap" flushCache="true">
SELECT ${columns},
SECURITY_AUDIT.REV_USER as username,
SECURITY_AUDIT.REV_MODIF as date,
${tableName}.REVTYPE as revisionType
FROM ${tableName}
LEFT JOIN SECURITY_AUDIT
ON ${tableName}.REV = SECURITY_AUDIT.REV_ID
WHERE ${pkName} = #{pkValue} ORDER BY SECURITY_AUDIT.REV_MODIF DESC
LIMIT ${page},${pageSize}
</select>
<select id="countAuditData" resultType="int" flushCache="true">
SELECT count(${pkName})
FROM ${tableName}
WHERE ${pkName} = #{pkValue}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n</pattern>
</encoder>
</appender>
<root level="ALL">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.apache" level="off" />
<logger name="org.springframework" level="info" />
<logger name="javax.management" level="info" />
<logger name="com.bytesw.xdf.example" level="off" />
</configuration>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="mybatis.properties" />
<typeAliases>
<typeAlias type="com.bytesw.bytebot.bean.SummaryMessageByIntentBean" alias="SummaryMessageByIntent"/>
<typeAlias type="com.bytesw.bytebot.bean.SummaryMessageBySentenceBean" alias="SummaryMessageBySentence"/>
<typeAlias type="com.bytesw.bytebot.bean.ActionSummaryByGoalBean" alias="ActionSummaryByGoal"/>
<typeAlias type="com.bytesw.bytebot.bean.MessageByIntentBean" alias="MessageByIntent"/>
<typeAlias type="com.bytesw.bytebot.bean.DeploymentChannelParamValueBean" alias="DeploymentChannelParamValue"/>
<typeAlias type="com.bytesw.bytebot.bean.SessionByClientBean" alias="SessionByClient"/>
<typeAlias type="com.bytesw.bytebot.etl.beans.SessionBean" alias="Session"/>
<typeAlias type="com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean" alias="ChannelByAgent"/>
<typeAlias type="com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean" alias="DeleteControl"/>
</typeAliases>
<mappers>
<mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/SessionMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/MessageMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/ResponseMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/ActionMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/AgentMapper.xml"/>
<mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/SessionMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/MessageMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/ResponseMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/DataSensibleMapper.xml"/>
</mappers>
</configuration>
database-type-xdf=postgres
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Session + JDBC Demo</title>
</head>
<body>
<div>
<form th:action="@{/messages}" method="post">
<textarea name="msg" cols="40" rows="4"></textarea>
<input type="submit" value="Save"/>
</form>
<p><a href="/">refresh</a></p>
</div>
<div>
<h2>Messages</h2>
<ul th:each="m : ${messages}">
<li th:text="${m}">msg</li>
</ul>
</div>
<H3>Mensaje a cola</H3>
<div>
<form th:action="@{/sendToQueue}" method="post">
ID: <input name="message" />
<input type="submit" value="Send"/>
</form>
</div>
<H3>Mensaje a topico</H3>
<div>
<form th:action="@{/sendToTopic}" method="post">
ID: <input name="message" />
<input type="submit" value="Send"/>
</form>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>OAuth Server Index</title>
</head>
<body>
<div class="container">
<h1 class="page-header">OAuth Server Administration Dashboard </h1>
<div class="row">
<div class="col-md-12" >
<span sec:authorize="isAuthenticated()" style="display: inline-block;">
<a href="/logout">Sign Out</a>
</span>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Byte - Login</title>
<!-- Vendor CSS -->
<!-- <link href="css/animate.min.css" rel="stylesheet" />-->
<!-- <link href="css/material-design-iconic-font.min.css" rel="stylesheet" />-->
<!-- CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script>
function loginButton() {
window.location.href='./';
}
</script>
<style>
body {
color: #676a6c;
background-color: #f3f3f4;
}
.centered {
position: absolute;
left: 50%;
top: 40%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
h3 {
display: inherit;
font-weight: 600;
}
.text-center {
text-align: center;
}
</style>
</head>
<body>
<div class="row centered" >
<div class="col-lg-12">
<div class="ibox">
<div class="row">
<div class="text-center">
<i class="zmdi zmdi-sign-in" style="font-size: 80px"></i>
<h3 class="text-navy"> Su sesión ha finalizado</h3>
<p>Para iniciar sesión nuevamente presione aquí: <a href="#" onclick="loginButton()">Ingresar</a></p>
</div>
</div>
<div class="row text-center">
<div style="
display: inline-flex;
">
<img class="logo-byte" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAFP0lEQVRIx92WX4hdVxWHv33+3Js7k0zGeidNTLRR6YNaDTGFigq+mIZKzUOpTz4IimKtTw1aS6kahUKpPqixIlEqKFgaa4xYRGNESEtFGtN/dsyEJp3pTDOTzMzN3HvnnrPPXmttH+7JNGkqvuXBBYez4bDXt9b+rbX2cTFGroUl14TyfwnKAJ58dhYABxgQxADWi9mOstJQin29FDlVVPpgEfT3RdCdPuj3IvHB+VXP2V7BUhCCRVLnhr6cI200mD3xDwa/vm8IumSxhjnnsBg/GdS2ebXdlehJH+zbZdB9XnS+Ev2aWDy8VHpWKiGrnf/PjC43BzdD/EEV9FQZ7DYvurkIcqAMdqhSu9OLUoptXQ3y81LsZwlMAIcT+EWKW9PCEUnTFJekV4MSR1uNfZXYS0XQr3jRh9TsKTWOlqJ3lEG7pdhSKfrAIOg7K4tfGIjhLe7VyA0C+5O6XZLGOtQ5pCovA0VwDjSysxT9axn0YCn2DS96JMZ4PE0cWZreJZXca0ZXgUKtNRD9TV/0zhURzovuqGIkzXNcqwXeU734HLK89AYoEom4O6qgTxSVTHmxj4jq5wuvC81mvvltYyOElT4bk6wbXcJyWdGTftELg8/4GHetBN3QT5NnaI3gigFxahJmZ6DXhdbIGyCNkWhxxIvNB42PlUG+OaiE8bEN3/eqPHHsKZ6fPE1rbIx2+zo6Sx02bd/OxLZ30e90T6RZg6QsiWdOE6dfhYsdaDZgZPTKYhCN7xa12UrtQz7oBS+ajLRaE5OvvvbwoT8eY356FvIM5s7xSoxgypn5BdqbztL3FSHNiL0V4tIiZBmMjcGbRtswI42fLcW+W1T6xSLI81nW+Nv5TvfYjx77HSx19nJ9+/04lxLjIvA4SdKRsmR+agrSdOg0z2F0fd0nV8/PDMCrnazE8KK3B40/JWoyqMKmfF3zQti44VvAX4jxInALcDtmL5Dn95PnW4EvAYvAB4AceBloAAqsAinwwwTABz3hRW/zYue8aNIvK9Isv350pAWm88BFYKEeHH8HJoGjwEHgJeC3wDKwpV7fCuwBbgQOQz3rKtWDXvSMF73Li2IuWej0+//q9vot8nyiBq3UkX8K+BUwUgMPAXPAaeB14CzggQvAuUuMDKAS61TBTlYi7ULs4xvXNc5Mv34+2vx8YHz8SZzbQoztetOB+tj3184u2RRQ1usjwNuBAHwO+E4GsFqFfUHjqNe46sX+sNTt7R1tT3DDRz8mM6cm98deF5rN4YAyAZdAo/nnN+n9dP0A/KR+rwM+sZZREbRpMT7kxW4Kqp++WPr3uSSd/OCHd21tbtk6N/3vl6mWFolZDqNjEA3Ozw3BiYOsAUnyVtVW1ZoOQaWYM4u7vei9pej9A7GbBkEfLVaLWxqtkbvbO29+ZLnToSgFshwqgSSHojfMbnUFRIffroRZrW3dR2avaeRPpdg9hdh9heg/B2qPr6rRKQc/XozxuCTZi6SWURVCZTDxjmFGaQrLCzB7Giobwt7i2kgA+l5Y9fJsKfJKoXa01Lhcqt3aVWVBDV8Fp77ag+oMxgwx3k2oIHjwBVy3GbbdWDev/feGnekVOCBN3AOV0R2ofrkrum0u6D2idgLRF1A9juoYYmB2ALVZiEcA0B6MjsN7d8DKIlyYHUJxV4IijstieLhUay+InCtVM9R2YQZiX0XtUVRTVJexOL22IxqoQd6E9ePQWQAVqC+9taNL6uJJ6hiiY3FgNBB7BNE9dXX9khjfQ4y7sbgdeG7NyyVNVIZArtbIXasfyP8ArlhZjGSh5u0AAAAldEVYdGRhdGU6Y3JlYXRlADIwMjAtMDMtMDVUMTI6NTA6MzUtMDU6MDBkp/5ZAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIwLTAzLTA1VDEyOjUwOjM1LTA1OjAwFfpG5QAAAABJRU5ErkJggg==" style="
height: 20px;
width: 20px;
"> <p class="m-t"> <small class="ng-binding" style="
line-height: 24px;
">&nbsp;Latin American Byte © 2020</small> </p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="/favicon.ico" title="Favicon">
<title>Spring Security SSO Client 2</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="col-sm-12">
<h1>Spring Security SSO and logout</h1>
<a href="#" onclick="logout()"><font
class="lightTextLarge">Log Out</font></a>
</div>
</div>
</body>
<script type="text/javascript">
function setTimeZoneInCookie() {
console.log("creando cookie");
var _myDate = new Date();
var _offset = _myDate.getTimezoneOffset();
document.cookie = "TIMEZONE_COOKIE=" + _offset; //Cookie name with value
}
setTimeZoneInCookie();
function logout() {
window.location.href='logout';
}
</script>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="/favicon.ico" title="Favicon">
<title>Spring Security SSO Client 2</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="col-sm-12">
<h1>Spring Security SSO and logout</h1>
<form name="logout_form" id="logout_form" method="post" action="/logout1">
<input type="hidden" name="scope" value="read">
<input type="submit" value="Logout"/>
</form>
<a href="#" onclick="login()"><font
class="lightTextLarge">Log Out</font></a>
<a href="#" onclick="logout()"><font
class="lightTextLarge">Log Out</font></a>
</div>
</div>
</body>
<script type="text/javascript">
function setTimeZoneInCookie() {
console.log("creando cookie");
var _myDate = new Date();
var _offset = _myDate.getTimezoneOffset();
document.cookie = "TIMEZONE_COOKIE=" + _offset; //Cookie name with value
}
setTimeZoneInCookie();
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
console.log(document.cookie);
function login() {
window.location.href='mylogin';
}
function logout() {
var url = 'https://idcs-204e4341c8eb4484b0edba0934b4d507.identity.oraclecloud.com/oauth2/v1/userlogout?post_logout_redirect_uri=http://localhost:8080/logout&id_token_hint='+readCookie('XSRF-TOKEN');
window.location.href = url;
}
</script>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Session + JDBC Demo</title>
</head>
<body>
<h3>Good bye</h3>
</body>
</html>
\ No newline at end of file
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.service.AgentService;
import com.bytesw.bytebot.service.FileManagementService;
import com.bytesw.xdf.config.security.annotation.DummyPermissionEvaluator;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Hernán Uriarte Melchor
* @date 14/09/2020.
* <p>
* <p>
* Copyright (c) 2018 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebMvcTest(controllers = AgentController.class)
@ActiveProfiles(value = "test")
@AutoConfigureMockMvc(secure = false)
public class AgencyAgentControllerTest {
public static String baseService = "/service/agent";
@TestConfiguration
static class UserServiceTestContextConfiguration {
@Bean
DummyPermissionEvaluator dummyPermissionEvaluator() {
return new DummyPermissionEvaluator();
}
}
@Autowired
private MockMvc mvc;
@MockBean
private AgentService agentService;
@MockBean
private FileManagementService fileManagementService;
@Before
public void setUp() {
}
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void uploadFile_whenFileXLS_isOK() throws Exception {
MockMultipartFile xlsFile = new MockMultipartFile(
"file",
"my-xls-file.xls",
"application/vnd.ms-excel",
"my-xls-file".getBytes());
Mockito.when(fileManagementService.validateAndSaveFile(anyString(), eq(xlsFile) ))
.thenReturn(new FileValidationResponse());
mvc.perform(MockMvcRequestBuilders.multipart(baseService + "/file-upload")
.file(xlsFile))
.andExpect(status().isOk());
}
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void uploadFile_whenFileXLSNotAppropriate_throwException() throws Exception {
MockMultipartFile xlsFile = new MockMultipartFile("file", "my-xls-file.xls", "application/vnd.ms-excel",
"my-xls-file".getBytes());
Mockito.when(fileManagementService.validateAndSaveFile(anyString(), eq(xlsFile) ))
.thenThrow(IOException.class);
mvc.perform(MockMvcRequestBuilders.multipart(baseService + "/file-upload")
.file(xlsFile))
.andExpect(status().isInternalServerError());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.bean.ChannelBean;
import com.bytesw.bytebot.bean.CountryBean;
import com.bytesw.bytebot.bean.DeploymentChannelBean;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.bean.FrequentQuestionBean;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import com.bytesw.bytebot.model.Country;
import com.bytesw.bytebot.model.DeploymentChannel;
import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import com.bytesw.bytebot.model.FrequentQuestion;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import com.bytesw.bytebot.model.enums.StatusEnum;
import com.bytesw.bytebot.repository.AgentRepository;
import com.bytesw.bytebot.repository.ChannelParamRepository;
import com.bytesw.bytebot.repository.ChannelRepository;
import com.bytesw.bytebot.repository.CountryRepository;
import com.bytesw.bytebot.repository.DeploymentChannelParamValueRepository;
import com.bytesw.bytebot.repository.DeploymentChannelRepository;
import com.bytesw.bytebot.repository.FrequentQuestionRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.sql.beans.Pagination;
import com.bytesw.xdf.sql.beans.SortField;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.apache.camel.ProducerTemplate;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Hernán Uriarte Melchor
* @version 14/09/18.
* <p>
* <p>
* Copyright (c) 2018 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@RunWith(SpringRunner.class)
public class AgencyAgentServiceTest {
@TestConfiguration
static class AgentServiceTestContextConfiguration {
@MockBean
private AgentRepository agentRepository;
@MockBean
private CountryRepository countryRepository;
@MockBean
private DeploymentChannelRepository deploymentChannelRepository;
@MockBean
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@MockBean
private ChannelRepository channelRepository;
@MockBean
private ChannelParamRepository channelParamRepository;
@MockBean
private FrequentQuestionRepository frequentQuestionRepository;
@MockBean
private QuestionFileRepository questionFileRepository;
@MockBean
private ProducerTemplate producerTemplate;
@Bean
public AgentService agentService() {
return new AgentService();
}
}
@Autowired
private AgentService agentService;
@Autowired
private ChannelRepository channelRepository;
@Autowired
private CountryRepository countryRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private FrequentQuestionRepository frequentQuestionRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private ProducerTemplate producerTemplate;
@Autowired
private DeploymentChannelRepository deploymentChannelRepository;
@Autowired
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@Autowired
private ChannelParamRepository channelParamRepository;
@Before
public void setUp() {
}
@Test
public void searchByPagination_whenThereAreNotSortField_isOK(){
Pagination<AgentBean> pagination = new Pagination<>();
pagination.setItemsPerPage(20);
pagination.setCurrentPage(1);
List<Agent> listOfAgents = new ArrayList<>();
Country countryPeru = new Country();
countryPeru.setId(1L);
countryPeru.setName("PERU");
Agent agentA = new Agent();
agentA.setId(1L);
agentA.setName("BYTEBOT");
agentA.setVersion("1.0.0");
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentA.setTimezone("GMT-5");
agentA.setAvatar("bytebot.png");
agentA.setCountry(countryPeru);
Agent agentB = new Agent();
agentB.setId(1L);
agentB.setName("BFMBOT");
agentB.setVersion("2.0.0");
agentB.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentB.setTimezone("GMT-5");
agentB.setAvatar("bfmbot.png");
agentB.setCountry(countryPeru);
listOfAgents.add(agentA);
listOfAgents.add(agentB);
Page<Agent> page = new PageImpl<>(listOfAgents);
Mockito.when(agentRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(page);
agentService.searchByPagination(pagination);
}
@Test
public void searchByPagination_whenThereAreResults_isOK(){
Pagination<AgentBean> pagination = new Pagination<>();
pagination.setItemsPerPage(20);
pagination.setCurrentPage(1);
SortField[] orderFields = new SortField[1];
SortField sortFieldA = new SortField();
sortFieldA.setDirection("asc");
sortFieldA.setField("id");
orderFields[0] = sortFieldA;
pagination.setSortFields(orderFields);
List<Agent> listOfAgents = new ArrayList<>();
Country countryPeru = new Country();
countryPeru.setId(1L);
countryPeru.setName("PERU");
Agent agentA = new Agent();
agentA.setId(1L);
agentA.setName("BYTEBOT");
agentA.setVersion("1.0.0");
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentA.setTimezone("GMT-5");
agentA.setAvatar("bytebot.png");
agentA.setCountry(countryPeru);
Agent agentB = new Agent();
agentB.setId(1L);
agentB.setName("BFMBOT");
agentB.setVersion("2.0.0");
agentB.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentB.setTimezone("GMT-5");
agentB.setAvatar("bfmbot.png");
agentB.setCountry(countryPeru);
listOfAgents.add(agentA);
listOfAgents.add(agentB);
Page<Agent> page = new PageImpl<>(listOfAgents);
Mockito.when(agentRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(page);
agentService.searchByPagination(pagination);
}
@Test
public void save_whenAgentExists_OK() {
Long idAgente = 1L;
Long idCountry = 1L;
Long idFrequentQuestion = 1L;
Agent agentBD = new Agent();
agentBD.setId(idAgente);
agentBD.setName("BOT-1");
agentBD.setDescription("BOT BASICO DE PREGUNTAS");
agentBD.setVersion("0.0.1");
agentBD.setLanguage(LanguageEnum.SPANISH);
agentBD.setTimezone("GMT-5");
agentBD.setType(AgentTypeEnum.FREQUENT_QUESTION);
agentBD.setStatus(AgentStatusEnum.CREATED);
agentBD.setAvatar("avatar-png");
Country countryA = new Country();
countryA.setId(idCountry);
countryA.setName("Perú");
agentBD.setCountry(countryA);
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idFrequentQuestion);
frequentQuestionA.setDescription("Preguntas de entrenamiento");
frequentQuestionA.setUser("lortiz");
frequentQuestionA.setFilename("preguntas-base-old.xls");
frequentQuestionA.setUploadDate(LocalDateTime.now());
frequentQuestionA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestions.add(frequentQuestionA);
agentBD.setFrequentQuestions(frequentQuestions);
List<DeploymentChannel> deploymentChannels = new ArrayList<>();
DeploymentChannel deploymentChannelA = new DeploymentChannel();
deploymentChannelA.setId(1L);
deploymentChannelA.setName("FACEBOOK");
deploymentChannelA.setStatus(StatusEnum.ACTIVE);
Channel channelA = new Channel();
channelA.setId(1L);
channelA.setName("FACEBOOK");
deploymentChannelA.setChannel(channelA);
List<DeploymentChannelParamValue> parameters = new ArrayList<>();
ChannelParam channelParamA = new ChannelParam();
channelParamA.setId(1L);
channelParamA.setName("token");
DeploymentChannelParamValue parameterA = new DeploymentChannelParamValue();
parameterA.setId(1L);
parameterA.setValue("facebook-abc");
parameterA.setParameter(channelParamA);
DeploymentChannelParamValue parameterB = new DeploymentChannelParamValue();
parameterB.setId(2L);
parameterB.setValue("https://facebook....");
parameters.add(parameterA);
parameters.add(parameterB);
deploymentChannelA.setParameters(parameters);
DeploymentChannel deploymentChannelB = new DeploymentChannel();
deploymentChannelB.setId(2L);
deploymentChannelB.setName("WHATSAPP");
deploymentChannelB.setStatus(StatusEnum.INACTIVE);
deploymentChannelB.setParameters(new ArrayList<>());
deploymentChannels.add(deploymentChannelA);
deploymentChannels.add(deploymentChannelB);
agentBD.setDeploymentChannels(deploymentChannels);
// Agent Data Bean
AgentBean agentBeanA = new AgentBean();
agentBeanA.setId(idAgente);
agentBeanA.setName("BOT-AGENT");
agentBeanA.setDescription("BOT AVANZADO DE PREGUNTAS");
agentBeanA.setVersion("2.0.0");
agentBeanA.setLanguage(LanguageEnum.SPANISH.getName());
agentBeanA.setTimezone("GMT-5");
agentBeanA.setType(AgentTypeEnum.FREQUENT_QUESTION.getName());
agentBeanA.setStatus(AgentStatusEnum.CREATED.getName());
agentBeanA.setAvatar("avatar-BOT.png");
agentBeanA.setCountryId(countryA.getId());
agentBeanA.setCountryName(countryA.getName());
agentBeanA.setFrequentQuestions(new ArrayList<>());
FrequentQuestionBean frequentQuestionBeanA = new FrequentQuestionBean();
frequentQuestionBeanA.setId(idFrequentQuestion);
frequentQuestionBeanA.setUuid("");
frequentQuestionBeanA.setDescription("Database Principal");
frequentQuestionBeanA.setUser("lortiz");
frequentQuestionBeanA.setFilename("preguntas-advanced.xls");
frequentQuestionBeanA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
agentBeanA.getFrequentQuestions().add(frequentQuestionBeanA);
FrequentQuestionBean frequentQuestionBeanB = new FrequentQuestionBean();
//frequentQuestionBeanB.setId(12L);
frequentQuestionBeanB.setUuid("");
frequentQuestionBeanB.setDescription("Database Secundaria");
frequentQuestionBeanB.setUser("lortiz");
frequentQuestionBeanB.setFilename("preguntas-advanced-TIGO.xls");
frequentQuestionBeanB.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
agentBeanA.getFrequentQuestions().add(frequentQuestionBeanB);
agentBeanA.setDeploymentChannels(new ArrayList<>());
DeploymentChannelBean deploymentChannelBeanA = new DeploymentChannelBean();
deploymentChannelBeanA.setId(1L);
deploymentChannelBeanA.setName("FACEBOOK");
deploymentChannelBeanA.setStatus(StatusEnum.ACTIVE.getName());
deploymentChannelBeanA.setChannelId(channelA.getId());
deploymentChannelBeanA.setChannelName(channelA.getName());
deploymentChannelBeanA.setParameters(new ArrayList<>());
DeploymentChannelParamValueBean deploymentChannelParamValueBeanA = new DeploymentChannelParamValueBean();
deploymentChannelParamValueBeanA.setId(1L);
deploymentChannelParamValueBeanA.setValue("facebook-botbyte");
deploymentChannelParamValueBeanA.setChannelParamName(channelParamA.getName());
deploymentChannelBeanA.getParameters().add(deploymentChannelParamValueBeanA);
agentBeanA.getDeploymentChannels().add(deploymentChannelBeanA);
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(agentBD));
Mockito.when(countryRepository.findById(idCountry))
.thenReturn(Optional.ofNullable(countryA));
Mockito.when(frequentQuestionRepository.findById(idFrequentQuestion))
.thenReturn(Optional.ofNullable(frequentQuestionA));
Mockito.when(agentRepository.save(any(Agent.class)))
.thenReturn(agentBD);
Mockito.when(deploymentChannelRepository.findById(1L))
.thenReturn(Optional.ofNullable(deploymentChannelA));
Mockito.when(channelRepository.findById(1L))
.thenReturn(Optional.ofNullable(channelA));
Mockito.when(deploymentChannelParamValueRepository.findById(1L))
.thenReturn(Optional.ofNullable(parameterA));
Mockito.when(channelParamRepository.findByNameAndChannelId(channelParamA.getName(), channelA.getId()))
.thenReturn(Optional.ofNullable(channelParamA));
agentService.save(agentBeanA);
}
@Test
public void getAgent_whenAgentNotExists_OK() {
Long idAgente = 1L;
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(null));
AgentBean agentBean = agentService.getAgent(idAgente);
assertThat(agentBean).isNull();
}
@Test
public void getAgent_whenAgentExists_OK() {
Long idAgente = 1L;
Long idCountry = 1L;
Long idFrequentQuestion = 1L;
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setName("BOT-1");
agentA.setDescription("BOT BASICO DE PREGUNTAS");
agentA.setVersion("0.0.1");
agentA.setLanguage(LanguageEnum.SPANISH);
agentA.setTimezone("GMT-5");
agentA.setType(AgentTypeEnum.FREQUENT_QUESTION);
agentA.setStatus(AgentStatusEnum.CREATED);
agentA.setAvatar("avatar-png");
Country countryA = new Country();
countryA.setId(idCountry);
countryA.setName("Perú");
agentA.setCountry(countryA);
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idFrequentQuestion);
frequentQuestionA.setDescription("Preguntas de entrenamiento");
frequentQuestionA.setUser("lortiz");
frequentQuestionA.setFilename("preguntas-base-old.xls");
frequentQuestionA.setUploadDate(LocalDateTime.now());
frequentQuestionA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestions.add(frequentQuestionA);
agentA.setFrequentQuestions(frequentQuestions);
List<DeploymentChannel> deploymentChannels = new ArrayList<>();
DeploymentChannel deploymentChannelA = new DeploymentChannel();
deploymentChannelA.setId(1L);
deploymentChannelA.setName("FACEBOOK");
deploymentChannelA.setStatus(StatusEnum.ACTIVE);
Channel channelA = new Channel();
channelA.setId(1L);
channelA.setName("FACEBOOK");
deploymentChannelA.setChannel(channelA);
List<DeploymentChannelParamValue> parameters = new ArrayList<>();
ChannelParam channelParamA = new ChannelParam();
channelParamA.setName("token");
DeploymentChannelParamValue parameterA = new DeploymentChannelParamValue();
parameterA.setId(1L);
parameterA.setValue("facebook-abc");
parameterA.setParameter(channelParamA);
DeploymentChannelParamValue parameterB = new DeploymentChannelParamValue();
parameterB.setId(2L);
parameterB.setValue("https://facebook....");
parameters.add(parameterA);
parameters.add(parameterB);
deploymentChannelA.setParameters(parameters);
DeploymentChannel deploymentChannelB = new DeploymentChannel();
deploymentChannelB.setId(2L);
deploymentChannelB.setName("WHATSAPP");
deploymentChannelB.setStatus(StatusEnum.INACTIVE);
deploymentChannelB.setParameters(new ArrayList<>());
deploymentChannels.add(deploymentChannelA);
deploymentChannels.add(deploymentChannelB);
agentA.setDeploymentChannels(deploymentChannels);
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
AgentBean agentBean = agentService.getAgent(idAgente);
assertThat(agentBean.getId()).isEqualTo(idAgente);
}
@Test
public void delete_whenAgentExists_OK() {
Long idAgente = 1L;
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
Mockito.when(agentRepository.save(any(Agent.class))).thenReturn(agentA);
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void delete_whenAgentNotExists_OK() {
Long idAgente = null;
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void delete_whenAgentNotExistsById_OK() {
Long idAgente = 1L;
Agent agentA = null;
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void getCountries_whenCountries_areOK() {
List<Country> countries = new ArrayList<>();
Country countryA = new Country();
Country countryB = new Country();
countries.add(countryA);
countries.add(countryB);
Mockito.when(countryRepository.findAll()).thenReturn(countries);
List<CountryBean> countriesBeanList = agentService.getCountries();
assertThat(countriesBeanList.size()).isEqualTo(2);
}
@Test
public void getChannels_whenChannels_areOK() {
List<Channel> channels = new ArrayList<>();
Channel channelA = new Channel();
Channel channelB = new Channel();
channels.add(channelA);
channels.add(channelB);
Mockito.when(channelRepository.findAll()).thenReturn(channels);
List<ChannelBean> channelsBeanList = agentService.getChannels();
assertThat(channelsBeanList.size()).isEqualTo(2);
}
@Test
public void synchronizeFiles_whenQuestionFileIsNotPresent_OK() {
Long idAgente = 1L;
String user = "lortiz";
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idAgente);
frequentQuestionA.setUuid(uuid);
frequentQuestions.add(frequentQuestionA);
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
Mockito.when(frequentQuestionRepository.findAllByAgentIdAndStatus(idAgente, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED))
.thenReturn(frequentQuestions);
Mockito.when(questionFileRepository.findByUuid(uuid))
.thenReturn(Optional.ofNullable(null));
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(agentA));
agentService.synchronizeFiles(idAgente, user);
//@HU como validar un void method
}
@Test
public void synchronizeFiles_whenQuestionFileIsPresentButNotAgent_OK() {
Long idAgente = 1L;
String user = "lortiz";
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idAgente);
frequentQuestionA.setUuid(uuid);
frequentQuestions.add(frequentQuestionA);
QuestionFile questionFileA = new QuestionFile();
questionFileA.setName("preguntas-basicas-old");
Mockito.when(frequentQuestionRepository.findAllByAgentIdAndStatus(idAgente, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED))
.thenReturn(frequentQuestions);
Mockito.when(questionFileRepository.findByUuid(uuid))
.thenReturn(Optional.ofNullable(questionFileA));
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(null));
agentService.synchronizeFiles(idAgente, user);
//@HU como validar un void method
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Hernán Uriarte Melchor
* @version 14/09/18.
* <p>
* <p>
* Copyright (c) 2018 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@RunWith(SpringRunner.class)
public class FileManagementServiceTest {
@TestConfiguration
static class UserServiceTestContextConfiguration {
@MockBean
private QuestionFileRepository questionFileRepository;
@Bean
public FileManagementService fileManagementService() {
return new FileManagementService();
}
}
@Autowired
private FileManagementService fileManagementService;
@Autowired
private QuestionFileRepository questionFileRepository;
@Before
public void setUp() {
}
@Test
public void validateAndSaveFile_whenFileHasInvalidExtension_SimpleError() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-columna-doble-columna.xls");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileHeadersRepetead = new MockMultipartFile(
"preguntas-ejemplo-sin-columna-doble-columna.xml",
"preguntas-ejemplo-sin-columna-doble-columna.xml",
MediaType.APPLICATION_XML_VALUE,
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileHeadersRepetead);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.INCOMPATIBLE_EXTENSION);
}
@Test
public void validateAndSaveFile_whenFileHasHeaderRepetead_ErrorWithDetails() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-columna-doble-columna.xls");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileHeadersRepetead = new MockMultipartFile(
"preguntas-ejemplo-sin-columna-doble-columna.xls",
"preguntas-ejemplo-sin-columna-doble-columna.xls",
"application/vnd.ms-excel",
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileHeadersRepetead);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.HEADER_ERROR);
}
@Test
public void validateAndSaveFile_whenFileHasBadContent_ErrorWithDetails() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileBadContent = new MockMultipartFile(
"preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx",
"preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx",
"application/vnd.ms-excel",
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileBadContent);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.CONTENT_ERROR);
}
@Test
public void validateAndSaveFile_whenFileIsCorrect_thenIsSaved() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-base.xlsx");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFile = new MockMultipartFile(
"preguntas-ejemplo-base.xlsx",
"preguntas-ejemplo-base.xlsx",
"application/vnd.ms-excel",
inputData);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(xlsFile.getOriginalFilename());
questionFileBD.setSize(xlsFile.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(xlsFile.getBytes());
Mockito.when(questionFileRepository.save(any(QuestionFile.class)))
.thenReturn(questionFileBD);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFile);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.OK);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--<import resource="classpath:applicationContext-aop.xml" />-->
<import resource="classpath:applicationContext-scheduler.xml" />
<!-- MyBatis stuff -->
<!--
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis-config.xml" />
</bean>
-->
</beans>
spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
server:
servlet.context-path: /tenant-server
port: 9443
ssl:
key-store-type: JKS
key-store: 'classpath:keystore.jks'
key-store-password: changeit
key-alias: tomcat
security:
require-ssl: true
basic:
enabled: false
application:
services:
security: none
api.info:
title: 'byteXDF4Java Service'
description: 'API para el desarrollo de software'
version: '1.0.0'
terms-of-service-url: 'https://es.wikipedia.org/wiki/byteXDF4Java'
license: 'Open source licensing'
license-url: 'https://help.github.com/articles/open-source-licensing/'
spring:
application:
name: tenant-server
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
username: sa
password: sa
minimum-idle: 10
maximum-pool-size: 10
validationQuery: SELECT 1
testWhileIdle: true
hikari.registerMbeans: true
jpa:
properties.hibernate.dialect: org.hibernate.dialect.H2Dialect
show-sql: true
logging.level.root: info
logging.pattern.console: '%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n'
logging.level.com.bytesw: debug
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="2" />
<property name="maxPoolSize" value="5" />
<property name="queueCapacity" value="5" />
<property name="waitForTasksToCompleteOnShutdown" value="true" />
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
</property>
</bean>
</beans>
\ No newline at end of file
CREATE TABLE SEQUENCE_TABLE
(SEQ_NAME VARCHAR(50) NOT NULL,
SEQ_COUNT INTEGER DEFAULT 0,
PRIMARY KEY (SEQ_NAME));
INSERT SEQUENCE_TABLE (SEQ_NAME, SEQ_COUNT) VALUES ('USER_SEQ', 0);
\ No newline at end of file
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