Commit 1d0b7890 authored by virginiagonzalezd's avatar virginiagonzalezd

Added DISNET services

parent f635c72b
text-extraction @ 3d282d5c
Subproject commit 3d282d5ce4c0b056fd63e6bcde2750a468272c8b
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### Local env ###
tmp/
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
</persistence>
@echo off
call .\mvnw clean package -DskipTests
move target\*0.0.1-SNAPSHOT.jar target\app.jar
scp target\app.jar virginia@138.4.130.139:/var/local/docker/disnet/dockerfile/text-extraction
echo Reiniciando contenedor...
ssh virginia@138.4.130.139 "cd /var/local/docker/disnet/dockerfile/text-extraction && docker compose restart disnet-text-extraction"
echo Ya esta!
\ 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
#
# http://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 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 Migwn, 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)`"
# TODO classpath?
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
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
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
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 http://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 Maven2 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 key stroke 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 enable echoing my 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
%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 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.upm.ctb.medal</groupId>
<artifactId>text-extraction</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>text-extraction</name>
<description>Extract disease related information from the public sources of Wikipedia, Mayo Clinic and PubMed</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<jjwt.version>0.7.0</jjwt.version>
<jsoup.version>1.10.2</jsoup.version>
<jdom2.version>2.0.6</jdom2.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Apache Commons -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>com.github.mpkorstanje</groupId>
<artifactId>simmetrics-core</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.github.bohnman</groupId>
<artifactId>squiggly-filter-jackson</artifactId>
<version>1.3.8</version>
</dependency>
<dependency>
<groupId>edu.wcmc.reciter</groupId>
<artifactId>reciter-pubmed-model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.3.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/jena -->
<dependency>
<groupId>com.hp.hpl.jena</groupId>
<artifactId>jena</artifactId>
<version>2.6.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hp.hpl.jena/arq -->
<dependency>
<groupId>com.hp.hpl.jena</groupId>
<artifactId>arq</artifactId>
<version>2.8.3</version>
</dependency>
<!--AUTORIZACIÓN-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<!-- Begin Netflix Feign dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- End Netflix Feign dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
<!-- jsoup HTML parser library @ http://jsoup.org/ -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>${jdom2.version}</version>
</dependency>
<!-- leer XML dentro de jar -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
<!--ENVÌO DE CORREOS-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.ibm.icu/icu4j -->
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>77.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.19.3</version> <!-- or compatible -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<version>1.19.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--NECESARIA PARA FEIGN-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>reciter-snapshots</id>
<url>https://github.com/wcmc-its/ReCiter-Maven-Repository/raw/master/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package es.upm.ctb.medal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(scanBasePackages = "es.upm.ctb.medal")
@EnableAutoConfiguration
@EnableScheduling
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix
public class GetDiseasesListRestApplication {
public static void main(String[] args) {
SpringApplication.run(GetDiseasesListRestApplication.class, args);
}
}
package es.upm.ctb.medal.common.enums;
import org.apache.commons.lang.StringUtils;
public enum ApiErrorEnum {
INVALID_PARAMETERS("400", "A required parameter for this API operation is invalid or has not been provided"),
UNAUTHORIZED("401", "The access token credential are missing or invalid for the given request"),
RESOURCE_NOT_FOUND("404", "Could not find resource"),
RESOURCES_NOT_FOUND("404", "Could not find resources"),
INVALID_SNAPSHOT("405", "The snapshot is incorrect"),
INTERNAL_SERVER_ERROR("500", "An unknown Api exception was thrown");
private String key;
private String description;
private ApiErrorEnum(String key, String description) {
this.key = key;
this.description = description;
}
public static ApiErrorEnum getEnum(String key) {
if (StringUtils.isNotBlank(key)) {
for (ApiErrorEnum status : ApiErrorEnum.values()) {
if (key.equals(status.getKey()))
return status;
}
}
return null;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package es.upm.ctb.medal.common.enums;
import org.apache.commons.lang.StringUtils;
/**
* Created by gerardo on 29/3/17.
* @project ExtractionInformationWikipedia
* @version ${<VERSION>}
* @author Gerardo Lagunes G.
* @className ErrorEnum
* @see
*/
public enum ErrorEnum {
INVALID_PARAMETERS("400", "HTML_A required parameter for this API operation is invalid or has not been provided"),
UNAUTHORIZED("401", "The username and password credentials are missing or invalid for the given request."),
RESOURCE_NOT_FOUND("404", "Could not find resource."),
INTERNAL_SERVER_ERROR("500", "An unknown Api exception was thrown");
private String clave;
private String descripcion;
private ErrorEnum(String clave, String descripcion) {
this.clave = clave;
this.descripcion = descripcion;
}
public static ErrorEnum getEnum(String clave) {
if (StringUtils.isNotBlank(clave)) {
for (ErrorEnum estatus : ErrorEnum.values()) {
if (clave.equals(estatus.getClave()))
return estatus;
}
}
return null;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
}
package es.upm.ctb.medal.common.enums;
import org.apache.commons.lang.StringUtils;
/**
* Created by gerardo on 6/4/17.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project ExtractionInformationWikipedia
* @className StatusHttpEnum
* @see
*/
public enum SourceEnum {
DBPEDIA("SO02", "dbpedia"),
DBPEDIALIVE("SO04", "dbpedialive");
private String key;
private String description;
private SourceEnum(String key, String description) {
this.key = key;
this.description = description;
}
public static SourceEnum getEnumByKey(String clave) {
if (StringUtils.isNotBlank(clave)) {
for (SourceEnum source : SourceEnum.values()) {
if (clave.equals(source.getKey()))
return source;
}
}
return null;
}
public static SourceEnum getEnumByDescription(String description) {
if (StringUtils.isNotBlank(description)) {
for (SourceEnum source : SourceEnum.values()) {
if (description.equalsIgnoreCase(source.getDescription()))
return source;
}
}
return null;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package es.upm.ctb.medal.common.enums;
import org.apache.commons.lang.StringUtils;
/**
* Created by gerardo on 6/4/17.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project ExtractionInformationWikipedia
* @className StatusHttpEnum
* @see
*/
public enum StatusHttpEnum {
OK("200 OK", "OK"),
MULTIPLE_CHICES("300", "Multiple Choices"),
MOVED_PERMANENTLY("301", "Moved Permanently"),
USE_PROXY("305", "Use Proxy"),
BAD_REQUEST("400", "Bad Request"),
FORBIDDEN("403", "Forbidden"),
NOT_FOUND("404", "Not Found"),
INTERNAL_SERVER_ERROR("500", "Internal Server Error"),
BAD_GATEWAY("502", "Bad Gateway"),
SERV_UNAVAILABLE("503", "Service Unavailable");
private String key;
private String description;
private StatusHttpEnum(String key, String description) {
this.key = key;
this.description = description;
}
public static StatusHttpEnum getEnum(String clave) {
if (StringUtils.isNotBlank(clave)) {
for (StatusHttpEnum estatus : StatusHttpEnum.values()) {
if (clave.equals(estatus.getKey()))
return estatus;
}
}
return null;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package es.upm.ctb.medal.common.util;
import es.upm.ctb.medal.common.constants.Constants;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.component.JwtTokenUtil;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.service.TokenAuthorization;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by gerardo on 10/05/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project ExtractionInformationDiseasesWikipedia
* @className Validations
* @see
*/
@Service
public class Common {
@Autowired
private TokenAuthorization tokenAuthorization;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private Common common;
/**
* @param token
* @param start
* @param end
* @throws Exception
*/
public void saveQueryRuntime(String token, String start, String end) throws Exception {
try {
//Aunque exista problema al insertar el runtime no hay problema con la ejecución de la consulta
String queryId = jwtTokenUtil.getQueryIdJWTDecode(token);
if (!common.isEmpty(queryId)) {
HttpStatus response = tokenAuthorization.updateQueryRuntime(queryId, start, end);
//System.out.println(response);
}
}catch (Exception e){}
}
public boolean isEmpty(String string) {
if (string == null) {
return true;
}
else {
if (string.trim().equalsIgnoreCase("")) {
return true;
}
else {
return false;
}
}
}
public boolean isInvalidCode(String code){
for (String i_code: Constants.INVALID_CODES){
if (code.trim().equals(i_code)) return true;
}
return false;
}
public String cutString(String str) {
return str = str.substring(0, str.length()-2);
}
/**
* @param cutStart
* @param cutFinal
* @param str
* @return
*/
public String cutStringPerformance(int cutStart, int cutFinal, String str) {
return str = str.substring(cutStart, str.length() - cutFinal);
}
public String cutString(int cutStart, int cutFinal, String str) {
return str = str.substring(cutStart, cutFinal);
}
public String replaceUnicodeToSpecialCharacters(String data){
Pattern p = Pattern.compile("\\\\u(\\p{XDigit}{4})");
Matcher m = p.matcher(data);
StringBuffer buf = new StringBuffer(data.length());
while (m.find()) {
String ch = String.valueOf((char) Integer.parseInt(m.group(1), 16));
m.appendReplacement(buf, Matcher.quoteReplacement(ch));
}
return m.appendTail(buf).toString();
}
public String getUnicode(char character){
return "\\u" + Integer.toHexString(character | 0x10000).substring(1);
}
public String replaceSpecialCharactersToUnicode(String text){
return StringEscapeUtils.escapeJava(text);
}
public void removeRepetedElementsList(List<String> elementsList){
Set<String> linkedHashSet = new LinkedHashSet<String>();
linkedHashSet.addAll(elementsList);
elementsList.clear();
elementsList.addAll(linkedHashSet);
}
public boolean itsFound(String originalStr, String findStr){
// System.out.println("RECIBE itsFound: ORI:" + originalStr + " | FIND: " + findStr);
return originalStr.trim().indexOf(findStr.trim()) != -1;// Retorna true si ha encontrado la subcadena en la cadena
}
}
package es.upm.ctb.medal.common.util;
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
/**
* Created by gerardo on 04/05/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project ExtractionInformationDiseasesWikipedia
* @className CurrentDate
* @see
*/
@Service
public class TimeProvider {
private static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public Date getNow(){
return new Date(new java.util.Date().getTime());
}
public String getTime(){
return String.format(new java.util.Date().toString(), dtf);
}
public String getNowFormatyyyyMMdd(){
return new SimpleDateFormat("yyyy-MM-dd").format(new Date(new java.util.Date().getTime()));
}
public DateFormat getSdf() {
return this.sdf = new SimpleDateFormat("yyyy-MM-dd");
}
public String getTimestampFormat() {
java.util.Date date = new java.util.Date();
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(date);
}
public java.util.Date stringToDate(String date) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
}
public java.sql.Date convertSQLDateToUtilDate(java.util.Date date){
return new java.sql.Date(date.getTime());
}
public Date getSqlDate(){
return new Date(new java.util.Date().getTime());
}
public long getTimestampNumber(){
return new Timestamp( System.currentTimeMillis() ).getTime();
}
}
package es.upm.ctb.medal.common.util;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;
/**
* Created by gerardo on 09/05/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project ExtractionInformationDiseasesWikipedia
* @className UniqueId
* @see
*/
@Service
public class UniqueId {
public String generate(int length){
return RandomStringUtils.randomAlphanumeric( length ).toLowerCase();
}
public String generateDisease(int disease){
String dis = String.format("%06d", disease);
return "DIS" + dis;
}
public String generateSource(int source){
String sou = (source < 10)?String.format("%02d", source):source+"";
return "SO" + sou;
}
public String generateDocument(String sourceId, int document){
String doc = (document < 10)?String.format("%02d", document):document+"";
return sourceId + ".DOC" + doc;
}
public String generateCode(String code, int resourceId){
//String cod = (code < 10)?String.format("%02d", code):code+"";
//return documentId + ".C" + cod;
return "C" + code + "/" + resourceId;
}
public String generateSection(int section){
String sec = (section < 10)?String.format("%02d", section):section+"";
return "SEC" + sec;
}
public String generateText(String documentId, String sectionId, int text){
String txt = (text < 10)?String.format("%02d", text):text+"";
return documentId + "." + sectionId + ".T" + txt;
}
public String generateUrl(String id, int url){
String u = (url < 10)?String.format("%02d", url):url+"";
return id + ".URL" + u;
}
public String generateUrl_alternative(String id, int url){
String u = (url < 10)?String.format("%02d", url):url+"";
return id + ".URL" + u + generate(4);
}
public String generateConfiguration(String id, int url){
String u = (url < 10)?String.format("%02d", url):url+"";
return id + ".U" + u;
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.configuration.FeignAuthConfiguration;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.UpdateQueryRuntimeRequest;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.fallback.AuthClientFallback;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.ValidationResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
/**
* Created by gerardo on 17/08/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project eidw
* @className TvpClient
* @see
*/
@FeignClient(name = "${my.service.authorization.name}",
url = "${my.service.authorization.url}",
fallback = AuthClientFallback.class,
configuration = FeignAuthConfiguration.class)
public interface AuthClient {
@RequestMapping(value = "${my.service.authorization.path}", method = RequestMethod.POST)
ValidationResponse validationServiceByToken(@RequestBody String tokenService);
@RequestMapping(value = "${my.service.authorization.validation.update_query_runtime.path}", method = RequestMethod.POST)
HttpStatus updateQueryRunTime(@RequestBody @Valid UpdateQueryRuntimeRequest request);
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.configuration;
import feign.Logger;
import feign.Request;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
/**
* Created by gerardo on 26/09/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project tvp_rest
* @className FeignAuthConfiguration
* @see
*/
public class FeignAuthConfiguration {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
public static final int SECONDS = 172800000;
@Bean
public Request.Options options() {
return new Request.Options(SECONDS, SECONDS);
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.fallback;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.AuthClient;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.UpdateQueryRuntimeRequest;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.ValidationResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* Created by gerardo on 17/08/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project eidw
* @className TvpClientFallback
* @see
*/
@Component
public class AuthClientFallback implements AuthClient {
@Override
public ValidationResponse validationServiceByToken(String tokenService) {
return new ValidationResponse();
}
@Override
public HttpStatus updateQueryRunTime(UpdateQueryRuntimeRequest request) {
return HttpStatus.NOT_FOUND;
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model;
import es.upm.ctb.medal.common.constants.Constants;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Created by gerardo on 27/11/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project validation_service_rest
* @className UpdateQueryRuntimeRequest
* @see
*/
public class UpdateQueryRuntimeRequest {
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@Size(min = 30, message = Constants.ERR_EMPTY_PARAMETER)
private String queryId;
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
private String startDatetime;
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
private String endDatetime;
public String getQueryId() {
return queryId;
}
public void setQueryId(String queryId) {
this.queryId = queryId;
}
public String getStartDatetime() {
return startDatetime;
}
public void setStartDatetime(String startDatetime) {
this.startDatetime = startDatetime;
}
public String getEndDatetime() {
return endDatetime;
}
public void setEndDatetime(String endDatetime) {
this.endDatetime = endDatetime;
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model;
import es.upm.ctb.medal.common.constants.Constants;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/**
* Created by gerardo on 25/09/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project disnet_web_app
* @className ValidationRequest
* @see
*/
public class ValidationRequest {
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@NotEmpty(message = Constants.ERR_EMPTY_PARAMETER)
private String token;
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@NotEmpty(message = Constants.ERR_EMPTY_PARAMETER)
private String apiCode;
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@NotEmpty(message = Constants.ERR_EMPTY_PARAMETER)
private String request;
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@NotEmpty(message = Constants.ERR_EMPTY_PARAMETER)
private String url;
private boolean enabled;
private String message;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getApiCode() {
return apiCode;
}
public void setApiCode(String apiCode) {
this.apiCode = apiCode;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model;
/**
* Created by gerardo on 26/09/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project disnet_web_app
* @className ValidationResponse
* @see
*/
public class ValidationResponse {
private boolean authorized;
private String message;
private String token;//Se enviará información extra entre los claims
public boolean isAuthorized() {
return authorized;
}
public void setAuthorized(boolean authorized) {
this.authorized = authorized;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Override
public String toString() {
return "ValidationResponse{" +
"authorized=" + authorized +
", message='" + message + '\'' +
", token='" + token + '\'' +
'}';
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.service;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.UpdateQueryRuntimeRequest;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.ValidationResponse;
import org.springframework.http.HttpStatus;
/**
* Created by gerardo on 08/08/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project eidw
* @className AuthResourceService
* @see
*/
public interface AuthResourceService {
ValidationResponse validationServiceByToken(String token) throws SecurityException;
HttpStatus updateQueryRunTime(UpdateQueryRuntimeRequest request);
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.service.impl;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.service.AuthResourceService;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.client.AuthClient;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.UpdateQueryRuntimeRequest;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.ValidationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
/**
* Created by gerardo on 17/08/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project eidw
* @className TvpResourceServiceImpl
* @see
*/
@Service
public class AuthResourceServiceImpl implements AuthResourceService {
@Autowired
private AuthClient authClient;
@Override
public ValidationResponse validationServiceByToken(String token) throws SecurityException{
ValidationResponse validationResponse = authClient.validationServiceByToken(token);
if (!validationResponse.isAuthorized()){
throw new SecurityException("The given token is not authorized");
}
return validationResponse;
}
@Override
public HttpStatus updateQueryRunTime(UpdateQueryRuntimeRequest request) {
return authClient.updateQueryRunTime(request);
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.component;
import es.upm.ctb.medal.common.util.TimeProvider;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtTokenUtil implements Serializable {
private static final long serialVersionUID = -3301605591108950415L;
static final String CLAIM_KEY_USERNAME = "sub";
static final String CLAIM_KEY_AUDIENCE = "aud";
static final String CLAIM_KEY_CREATED = "iat";
static final String AUDIENCE_UNKNOWN = "unknown";
static final String AUDIENCE_WEB = "web";
static final String AUDIENCE_MOBILE = "mobile";
static final String AUDIENCE_TABLET = "tablet";
@Autowired
private TimeProvider timeProvider;
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
@Value("${jwt.claims.name.token}")
private String claim_name_token;
@Value("${jwt.claims.name.api_code}")
private String claim_name_apiCode;
@Value("${jwt.claims.name.request}")
private String claim_name_request;
@Value("${jwt.claims.name.url}")
private String claim_name_url;
@Value("${jwt.claims.name.method}")
private String claim_name_method;
@Value("${jwt.claims.name.transaction_id}")
private String claim_name_transactionId;
//Obtiene el código del servicio. Nota: Debe coincidir con el de la base de datos
@Value("${my.service.code}")
private String apiCode;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public String getAudienceFromToken(String token) {
return getClaimFromToken(token, Claims::getAudience);
}
public String getApiCode() {
return apiCode;
}
public void setApiCode(String apiCode) {
this.apiCode = apiCode;
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(timeProvider.getNow());
}
private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
return (lastPasswordReset != null && created.before(lastPasswordReset));
}
private String generateAudience(/*Device device*/) {
String audience = AUDIENCE_UNKNOWN;
/*if (device.isNormal()) {
audience = AUDIENCE_WEB;
} else if (device.isTablet()) {
audience = AUDIENCE_TABLET;
} else if (device.isMobile()) {
audience = AUDIENCE_MOBILE;
}*/
return audience;
}
private Boolean ignoreTokenExpiration(String token) {
String audience = getAudienceFromToken(token);
return (AUDIENCE_TABLET.equals(audience) || AUDIENCE_MOBILE.equals(audience));
}
public String generateToken(String userToken, String request, String method, String url/*, Device device*/) {
Map<String, Object> claims = new HashMap<>();
claims.put(claim_name_token, userToken);
claims.put(claim_name_apiCode, apiCode);
claims.put(claim_name_request, request);
claims.put(claim_name_url, url);
claims.put(claim_name_method, method);
return doGenerateToken(claims/*, generateAudience(device)*/);
}
private String doGenerateToken(Map<String, Object> claims/*,String audience*/) {
final Date createdDate = timeProvider.getNow();
final Date expirationDate = calculateExpirationDate(createdDate);
System.out.println("doGenerateToken " + createdDate);
return Jwts.builder()
.setClaims(claims)
.setSubject(apiCode)
//.setAudience(audience)
.setIssuedAt(createdDate)
//.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/**
* @param token
* @return
*/
public String getQueryIdJWTDecode(String token){
try {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token).getBody();
//System.out.println("CLAIMS: " + claims.toString());
return claims.get(claim_name_transactionId).toString();
}catch (Exception e){
return "";
}
}
public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
final Date created = getIssuedAtDateFromToken(token);
return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
&& (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public String refreshToken(String token) {
final Date createdDate = timeProvider.getNow();
final Date expirationDate = calculateExpirationDate(createdDate);
final Claims claims = getAllClaimsFromToken(token);
claims.setIssuedAt(createdDate);
claims.setExpiration(expirationDate);
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/*
public Boolean validateToken(String token, UserDetails userDetails) {
JwtUser user = (JwtUser) userDetails;
final String username = getUsernameFromToken(token);
final Date created = getIssuedAtDateFromToken(token);
//final Date expiration = getExpirationDateFromToken(token);
return (
username.equals(user.getUsername())
&& !isTokenExpired(token)
//&& !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())
);
}
*/
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + expiration * 1000);
}
}
package es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.service;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.UpdateQueryRuntimeRequest;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.service.AuthResourceService;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.model.ValidationResponse;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.component.JwtTokenUtil;
import es.upm.ctb.medal.get_diseases_list.model.response.ResponseFather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
//import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Service;
/**
* Created by gerardo on 26/09/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project tvp_rest
* @className TokenAuthorization
* @see
*/
@Service
public class TokenAuthorization {
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private AuthResourceService authResourceService;
@Value("${my.service.authorization.url}")
private String authorization_url;
@Value("${my.service.authorization.path}")
private String authorization_path;
public ResponseFather validateService(String userToken, String request, String method, String url/*, Device device*/) throws SecurityException {
ResponseFather response = new ResponseFather();
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(userToken+" | "+ request+" | "+ url +" | "+ device);
String token = jwtTokenUtil.generateToken( userToken, request, method, url/*, device */);
System.out.println( "Call Authorization API... (" + authorization_url + authorization_path + ")");
ValidationResponse validationResponse = authResourceService.validationServiceByToken( token );
response.setAuthorized( validationResponse.isAuthorized() );
response.setAuthorizationMessage( validationResponse.getMessage() );
response.setToken( userToken );
response.setInfoToken( validationResponse.getToken() );
return response;
}
public HttpStatus updateQueryRuntime(String queryId, String startDatetime, String endDatetime){
UpdateQueryRuntimeRequest request = new UpdateQueryRuntimeRequest();
System.out.println( "Call Authorization API for update query runtime... " +" "+queryId +" "+ startDatetime +" "+ endDatetime );
request.setQueryId(queryId);
request.setStartDatetime(startDatetime);
request.setEndDatetime(endDatetime);
return authResourceService.updateQueryRunTime(request);
}
}
package es.upm.ctb.medal.get_diseases_list.controller;
import com.google.gson.Gson;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.service.TokenAuthorization;
import es.upm.ctb.medal.common.util.Common;
import es.upm.ctb.medal.common.util.TimeProvider;
import es.upm.ctb.medal.get_diseases_list.service.jpa.AlbumService;
import es.upm.ctb.medal.get_diseases_list.model.request.RequestFather;
import es.upm.ctb.medal.get_diseases_list.model.request.getAlbum.RequestAlbum;
import es.upm.ctb.medal.get_diseases_list.model.response.Album;
import es.upm.ctb.medal.get_diseases_list.model.response.ApiResponseError;
import es.upm.ctb.medal.get_diseases_list.model.response.ResponseFather;
import es.upm.ctb.medal.get_diseases_list.model.response.getLastAlbum.ResponseLA;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
//import org.springframework.mobile.device.Device;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(value = "${get_diseases_list.service.rest.request.mapping.general.url}")
public class AlbumController {
@Autowired
private AlbumService albumService;
@Autowired
private TokenAuthorization tokenAuthorization;
@Autowired
private TimeProvider timeProvider;
@Autowired
private Common common;
private static final Logger logger = LoggerFactory.getLogger(AlbumController.class);
@RequestMapping(path = {"/last"}, //wikipedia extraction
method = RequestMethod.GET)
public ResponseLA getLastAlbumByGET(@RequestParam(value = "token", required = false) String token,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
//System.out.println(httpRequest.getMethod());
ResponseFather responseFather = tokenAuthorization.validateService(token, httpRequest.getQueryString(), httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
ResponseLA response = new ResponseLA();
List<ApiResponseError> errorsFound = new ArrayList<>();
Album album = new Album();
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
//<editor-fold desc="PROCESO DE RESPUESTA">
authorized(responseFather, response, album, false, null, "", errorsFound);
//</editor-fold>
return response;
//return "Successful extraction and insertion in a DB!";
}
/**
* dsvp-rest.getLastAlbum()
*/
@RequestMapping(path = {"/last"}, //wikipedia extraction
method = RequestMethod.POST)
public ResponseLA getLastAlbumByPOST(@RequestBody @Valid RequestFather request,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
//System.out.println("path: "+httpRequest.getRequestURI());
//System.out.println(httpRequest.getMethod() + " " + RequestMethod.POST.toString());
Gson gson = new Gson();
String requestJSON = gson.toJson(request);
ResponseFather responseFather = tokenAuthorization.validateService(request.getToken(), requestJSON, httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
ResponseLA response = new ResponseLA();
List<ApiResponseError> errorsFound = new ArrayList<>();
Album album = new Album();
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
//<editor-fold desc="PROCESO DE RESPUESTA">
authorized(responseFather, response, album, false, null, "", errorsFound);
//</editor-fold>
return response;
//return "Successful extraction and insertion in a DB!";
}
/**
* @param responseFather
* @param response
* @param errorsFound
*/
public void authorized(ResponseFather responseFather, ResponseLA response, Album album, boolean one, Date snapshot, String source, List<ApiResponseError> errorsFound) throws Exception {
if (responseFather.isAuthorized()) {//Validar findLinksByIdAndSourceNameNative
String start = timeProvider.getTimestampFormat();
if (one) {
try {
album = albumService.findByVersionAndSourceNative(snapshot, source);
} catch (Exception e) {
response.setResponseCode(HttpStatus.PRECONDITION_FAILED.toString());
response.setResponseMessage(HttpStatus.PRECONDITION_FAILED.getReasonPhrase()+": "+e.getMessage());
return;
}
} else {
album = albumService.findByLastVersionNative();
}
String end = timeProvider.getTimestampFormat();
if (album != null) {
response.setResponseCode(HttpStatus.OK.toString());
response.setResponseMessage(HttpStatus.OK.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
} else {
response.setResponseCode(HttpStatus.NOT_FOUND.toString());
response.setResponseMessage(HttpStatus.NOT_FOUND.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
}
} else {
response.setResponseCode(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.toString());
response.setResponseMessage(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.getReasonPhrase());
}
response.setAlbum(album);
response.setErrorsFound(errorsFound);
}
/**
* dsvp-rest.getSpecificAlbum
*/
@RequestMapping(path = {"/one"}, //wikipedia extraction
method = RequestMethod.POST)
public ResponseLA getAlbumByPOST(@RequestBody @Valid RequestAlbum request,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
//System.out.println("path: "+httpRequest.getRequestURI());
//System.out.println(httpRequest.getMethod() + " " + RequestMethod.POST.toString());
Gson gson = new Gson();
String requestJSON = gson.toJson(request);
ResponseFather responseFather;
ResponseLA response = new ResponseLA();
List<ApiResponseError> errorsFound = new ArrayList<>();
Album album = new Album();
try {
responseFather = tokenAuthorization.validateService(request.getToken(), requestJSON, httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
}
catch (SecurityException e) {
logger.error(e.toString());
response.setAuthorizationMessage(e.toString());
response.setResponseCode(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.toString());
response.setResponseMessage(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.getReasonPhrase());
return response;
}
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
//"PROCESO DE RESPUESTA"
authorized(responseFather, response, album, true, timeProvider.stringToDate(request.getSnapshot()), request.getSource(), errorsFound);
return response;
//return "Successful extraction and insertion in a DB!";
}
@RequestMapping(path = {"/one"}, //wikipedia extraction
method = RequestMethod.GET,
params = {"source", "snapshot", "token"})
public ResponseLA getAlbumByGET(@RequestParam(value = "source") @Valid @NotBlank @NotEmpty @NotNull String source,
@RequestParam(value = "snapshot") @Valid @NotBlank @NotEmpty @NotNull String snapshot,
@RequestParam(value = "token") @Valid @NotBlank @NotEmpty @NotNull String token,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
//System.out.println("path: "+httpRequest.getRequestURI());
//System.out.println(httpRequest.getMethod() + " " + RequestMethod.POST.toString());
ResponseFather responseFather = tokenAuthorization.validateService(token, httpRequest.getQueryString(), httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
ResponseLA response = new ResponseLA();
List<ApiResponseError> errorsFound = new ArrayList<>();
Album album = new Album();
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
//"PROCESO DE RESPUESTA"
authorized(responseFather, response, album, true, timeProvider.stringToDate(snapshot), source, errorsFound);
//</editor-fold>
return response;
//return "Successful extraction and insertion in a DB!";
}
}
package es.upm.ctb.medal.get_diseases_list.controller;
import es.upm.ctb.medal.common.util.TimeProvider;
import es.upm.ctb.medal.common.constants.Constants;
import es.upm.ctb.medal.get_diseases_list.model.jpa.Album;
import es.upm.ctb.medal.get_diseases_list.service.jpa.AlbumService;
import es.upm.ctb.medal.get_diseases_list.service.GetDiseasesFromDBPedia;
import es.upm.ctb.medal.get_diseases_list.service.Populate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by gerardo on 30/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className ExtractionController
* @see
*/
@RestController("getDiseasesListExtractionController")
@RequestMapping(value = "${get_diseases_list.service.rest.request.mapping.general.url}") // /api/disease_album
public class ExtractionController {
private static final Logger logger = LoggerFactory.getLogger(ExtractionController.class);
@Autowired
private GetDiseasesFromDBPedia getDiseasesFromDBPedia;
@Autowired
private Populate populateService;
@Autowired
private AlbumService albumService;
@Autowired
private TimeProvider timeProvider;
@GetMapping("${get_diseases_list.service.rest.request.mapping.get.populate}")
public ResponseEntity<String> populate() {
try {
logger.info("Start population process");
Album album = populateService.populate();
if (album == null) {
return ResponseEntity.internalServerError()
.body("Error during population process. The album is null.");
}
logger.info("Update new album with diseases from the Safe List");
populateService.populateAlbumWithDiseaseSafeListAndLastDiseaseAlbum(Constants.WIKIPEDIA_SOURCE, album);
logger.info("Update disease Safe List");
populateService.updateDiseaseSafeList(Constants.WIKIPEDIA_SOURCE, album);
logger.info("End of population process");
return ResponseEntity.ok("Successful extraction and insertion in the DB!");
}
catch (Exception e) {
logger.error("Error during population process: {}", e.getMessage(), e);
return ResponseEntity.internalServerError()
.body("An error occurred during the population process: " + e.getMessage());
}
}
@RequestMapping(path = { "/insert-json" }, //wikipedia extraction
method = RequestMethod.GET)
public String insertJson(String snapshot) {
System.out.println(snapshot);
try {
populateService.insertByJson(snapshot);
}
catch (Exception e){
logger.error("Insertion failed",e);
return "Insertion failed";
}
return "Successful extraction and insertion in a DB!";
}
}
package es.upm.ctb.medal.get_diseases_list.controller;
import com.google.gson.Gson;
import es.upm.ctb.medal.get_diseases_list.client_modules.authorization.token.service.TokenAuthorization;
import es.upm.ctb.medal.common.util.Common;
import es.upm.ctb.medal.common.util.TimeProvider;
import es.upm.ctb.medal.get_diseases_list.service.jpa.helper.AlbumHelper;
import es.upm.ctb.medal.get_diseases_list.model.request.getDiseaseLinkList.RequestGDLL;
import es.upm.ctb.medal.get_diseases_list.model.response.ApiResponseError;
import es.upm.ctb.medal.get_diseases_list.model.response.Disease;
import es.upm.ctb.medal.get_diseases_list.model.response.ResponseFather;
import es.upm.ctb.medal.get_diseases_list.model.response.getDiseaseLinkList.ResponseGDLL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
//import org.springframework.mobile.device.Device;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(value = "${get_diseases_list.service.rest.request.mapping.general.url}")
public class QueryController {
@Autowired
private AlbumHelper albumHelper;
@Autowired
private TimeProvider timeProvider;
@Autowired
private TokenAuthorization tokenAuthorization;
@Autowired
private Common common;
private static final Logger logger = LoggerFactory.getLogger(QueryController.class);
@RequestMapping(path = {"/get"}, //wikipedia extraction
method = RequestMethod.GET)
public ResponseGDLL getDiseaseLinkListGET(@RequestParam(value = "source") String source,
@RequestParam(value = "album") String albumId,
@RequestParam(value = "snapshot") String snapshot,
@RequestParam(value = "token", required = false) String token,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
Date dataVersion = timeProvider.getSdf().parse(snapshot);
ResponseFather responseFather = tokenAuthorization.validateService(token, httpRequest.getQueryString(), httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
ResponseGDLL response = new ResponseGDLL();
List<ApiResponseError> errorsFound = new ArrayList<>();
List<Disease> diseases = new ArrayList<>();
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
response.setDiseases(diseases);
if (responseFather.isAuthorized()) {//Validar findLinksByIdAndSourceNameNative
try {
String start = timeProvider.getTimestampFormat();
diseases = albumHelper.findLinksByIdAndSourceNameNativeAndReplaceSpecialCharacters(errorsFound, albumId, dataVersion, source);
String end = timeProvider.getTimestampFormat();
if (diseases.size() > 0) {
response.setDiseases(diseases);
response.setUseDiseaseSafeList(true);//Siempre será true desde el 2018-04-02
response.setResponseCode(HttpStatus.OK.toString());
response.setResponseMessage(HttpStatus.OK.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
} else {
response.setResponseCode(HttpStatus.NOT_FOUND.toString());
response.setResponseMessage(HttpStatus.NOT_FOUND.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
}
} catch (Exception e) {
response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.toString());
response.setResponseMessage(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
} else {
response.setResponseCode(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.toString());
response.setResponseMessage(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.getReasonPhrase());
}
response.setDiseaseCount(diseases.size());
response.setErrorsFound(errorsFound);
return response;
//return "Successful extraction and insertion in a DB!";
}
@RequestMapping(path = {"/get"}, //wikipedia extraction
method = RequestMethod.POST)
public ResponseGDLL getDiseaseLinkListPOST(@RequestBody @Valid RequestGDLL requestGDLL,
HttpServletRequest httpRequest/*,
Device device*/) throws Exception {
Gson gson = new Gson();
String requestJSON = gson.toJson(requestGDLL);
Date dataVersion = timeProvider.getSdf().parse(requestGDLL.getSnapshot());//httpRequest.getQueryString() = request
System.out.println("dataVersion");
System.out.println(dataVersion);
ResponseFather responseFather;
ResponseGDLL response = new ResponseGDLL();
List<ApiResponseError> errorsFound = new ArrayList<>();
List<Disease> diseases = new ArrayList<>();
try {
responseFather = tokenAuthorization.validateService(requestGDLL.getToken(), requestJSON, httpRequest.getMethod(), httpRequest.getRequestURL().toString()/*, device*/);
} catch (SecurityException e) {
logger.error(e.toString());
response.setAuthorizationMessage(e.toString());
response.setResponseCode(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.toString());
response.setResponseMessage(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.getReasonPhrase());
return response;
}
System.out.println("responseFather");
System.out.println(responseFather);
response.setAuthorized(responseFather.isAuthorized());
response.setAuthorizationMessage(responseFather.getAuthorizationMessage());
response.setToken(responseFather.getToken());
// response.setDiseases(diseases);
try {
String start = timeProvider.getTimestampFormat();
diseases = albumHelper.findLinksByIdAndSourceNameNativeAndReplaceSpecialCharacters(errorsFound, requestGDLL.getAlbum(), dataVersion, requestGDLL.getSource());
String end = timeProvider.getTimestampFormat();
if (diseases.size() > 0) {
response.setDiseases(diseases);
response.setUseDiseaseSafeList(true);//Siempre será true desde el 2018-04-02
response.setResponseCode(HttpStatus.OK.toString());
response.setResponseMessage(HttpStatus.OK.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
} else {
response.setResponseCode(HttpStatus.NOT_FOUND.toString());
response.setResponseMessage(HttpStatus.NOT_FOUND.getReasonPhrase());
common.saveQueryRuntime(responseFather.getInfoToken(), start, end);
}
} catch (Exception e) {
response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.toString());
response.setResponseMessage(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
response.setDiseaseCount(diseases.size());
response.setErrorsFound(errorsFound);
return response;
//return "Successful extraction and insertion in a DB!";
}
}
package es.upm.ctb.medal.get_diseases_list.model.extraction;
import java.util.LinkedList;
import java.util.Objects;
public class Code {
public LinkedList<String> keys;
public Code(LinkedList<String> keys) {
this.keys = new LinkedList<>(keys);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Code)) {
return false;
}
Code other = (Code) obj;
System.out.println("Comparing " + this + " with " + other);
// Special case: if both are empty, they are NOT equal
if (this.keys.isEmpty() && other.keys.isEmpty()) {
return this != other; // only same instance is equal
}
// Otherwise, compare content with order
return this.keys.equals(other.keys);
}
@Override
public int hashCode() {
if (keys.isEmpty()) {
// Special: generate a unique hash for each empty list instance
return System.identityHashCode(this);
}
// Regular list hash code with order
return Objects.hash(keys);
}
@Override
public String toString() {
return keys.toString();
}
}
\ No newline at end of file
package es.upm.ctb.medal.get_diseases_list.model.extraction;
public class Disease {
private String name;
private String URI;
private String wikipediaPage;
private String ICD9Code;
private String ICD10Code;
private String diseasesDBCode;
private String meshCode;
private String medlinePlusCode;
private String OMIMCode;
private String eMedicineCode;
private String freebaseURL;
private String sourceId;
public Disease(String uri) {
this.URI = uri;
}
public Disease(String uri, String sourceId) {
this.URI = uri;
this.sourceId = sourceId;
}
public void setEMedicineCode(String e) {
this.eMedicineCode = e;
}
public void setOMIMCode(String o) {
this.OMIMCode = o;
}
public void setMedlinePlusCode(String m) {
this.medlinePlusCode = m;
}
public void setMeSHCode(String m) {
this.meshCode = m;
}
public void setDiseasesDBCode(String d) {
this.diseasesDBCode = d;
}
public void setICD10Code(String i) {
this.ICD10Code = i;
}
public void setICD9Code(String i) {
this.ICD9Code = i;
}
public void setWikipediaPage(String wp) {
this.wikipediaPage = wp;
}
public String toString() {
String ret = "";
ret += "\tURI: " + this.URI + "\n";
ret += "\tName: " + this.name + "\n";
ret += "\tWikipedia Page: " + this.wikipediaPage + "\n";
ret += "\tICD9 Code: " + this.ICD9Code + "\n";
ret += "\tICD10 Code: " + this.ICD10Code + "\n";
ret += "\tDiseases DB Code: " + this.diseasesDBCode + "\n";
ret += "\tMeSH ID: " + this.meshCode + "\n";
ret += "\tMedlinePlus Code: " + this.medlinePlusCode + "\n";
ret += "\tOMIM Code: " + this.OMIMCode + "\n";
ret += "\teMedicine Code: " + this.eMedicineCode + "\n";
ret += "\tFreebase URL: " + this.freebaseURL + "\n";
return ret;
}
public String getURI() {
return this.URI;
}
public String getName() {
return name;
}
public String getWikipediaPage() {
return wikipediaPage;
}
public String getICD9Code() {
return ICD9Code;
}
public String getICD10Code() {
return ICD10Code;
}
public String getDiseasesDBCode() {
return diseasesDBCode;
}
public String getMeshCode() {
return meshCode;
}
public String getMedlinePlusCode() {
return medlinePlusCode;
}
public String getOMIMCode() {
return OMIMCode;
}
public String geteMedicineCode() {
return eMedicineCode;
}
public String getFreebaseURL() {
return freebaseURL;
}
public void setName(String n) {
this.name = n;
}
public void setFreebaseURL(String fbu) {
this.freebaseURL = fbu;
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getDiseaseConcept() {
if (this.freebaseURL != null) {
String conc = this.freebaseURL.replaceAll("http://rdf.freebase.com/ns/", "");
System.out.println(conc);
return conc;
}
return null;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.sql.Date;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className AlbumDisease
* @see
*/
@Entity
@Table(name = "album_disease", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "AlbumDisease.findAll", query = "SELECT a FROM AlbumDisease a")
, @NamedQuery(name = "AlbumDisease.findById", query = "SELECT a FROM AlbumDisease a WHERE a.albumId = :albumId AND a.date = :date AND a.diseaseId = :diseaseId")
, @NamedQuery(name = "AlbumDisease.findByAlbumId", query = "SELECT a FROM AlbumDisease a WHERE a.albumId = :albumId")
, @NamedQuery(name = "AlbumDisease.findByDate", query = "SELECT a FROM AlbumDisease a WHERE a.date = :date")
, @NamedQuery(name = "AlbumDisease.findByDiseaseId", query = "SELECT a FROM AlbumDisease a WHERE a.diseaseId = :diseaseId")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "AlbumDisease.findByIdNative",
query = "SELECT a.album_id, a.date, a.disease_id " +
"FROM album_disease a WHERE a.album_id = :albumId AND a.date = :version AND a.disease_id = :diseaseId "
),
@NamedNativeQuery(
name = "AlbumDisease.findByAlbumIdNative",
query = "SELECT a.album_id, a.date, a.disease_id " +
"FROM album_disease a WHERE a.album_id = :albumId "
),
@NamedNativeQuery(
name = "AlbumDisease.findByVersionNative",
query = "SELECT a.album_id, a.date, a.disease_id " +
"FROM album_disease a WHERE a.date = :version "
),
@NamedNativeQuery(
name = "AlbumDisease.findByDiseaseIdNative",
query = "SELECT a.album_id, a.date, a.disease_id " +
"FROM album_disease a WHERE a.disease_id = :diseaseId "
),
@NamedNativeQuery(
name = "AlbumDisease.findLastAlbumVersionNative",
query = "SELECT MAX(a.date) " +
"FROM album_disease a "
),
@NamedNativeQuery(
name = "AlbumDisease.findAllNative",
query = "SELECT a.album_id, a.date, a.disease_id "
+ "FROM album_disease a "
)
,
@NamedNativeQuery(
name = "AlbumDisease.insertNative",
query = "INSERT INTO album_disease (album_id, date, disease_id) " +
"VALUES (:albumId, :version, :diseaseId)"
),
@NamedNativeQuery(
name = "AlbumDisease.insertIgnoreNative",
query = "INSERT IGNORE INTO album_disease (album_id, date, disease_id) " +
"VALUES (:albumId, :version, :diseaseId)"
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "AlbumDiseaseMapping",
entities = @EntityResult(
entityClass = AlbumDisease.class,
fields = {
@FieldResult(name = "albumId", column = "album_id"),
@FieldResult(name = "date", column = "date"),
@FieldResult(name = "diseaseId", column = "disease_id")
}
)
)
})
@IdClass(AlbumDiseasePK.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="AlbumDiseasePK")
public class AlbumDisease {
private String albumId;
private Date date;
private String diseaseId;
private Album album;
private Disease diseaseByDiseaseId;
@Id
@Column(name = "album_id", nullable = false, length = 15)
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
@Id
@Column(name = "date", nullable = false)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Id
@Column(name = "disease_id", nullable = false, length = 150)
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlbumDisease that = (AlbumDisease) o;
return Objects.equals(albumId, that.albumId) &&
Objects.equals(date, that.date) &&
Objects.equals(diseaseId, that.diseaseId);
}
@Override
public int hashCode() {
return Objects.hash(albumId, date, diseaseId);
}
@ManyToOne
@JoinColumns({@JoinColumn(name = "album_id", referencedColumnName = "album_id", nullable = false, insertable = false, updatable = false),
@JoinColumn(name = "date", referencedColumnName = "date", nullable = false, insertable = false, updatable = false)})
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
this.album = album;
}
@ManyToOne
@JoinColumn(name = "disease_id", referencedColumnName = "disease_id", nullable = false, insertable = false, updatable = false)
public Disease getDiseaseByDiseaseId() {
return diseaseByDiseaseId;
}
public void setDiseaseByDiseaseId(Disease diseaseByDiseaseId) {
this.diseaseByDiseaseId = diseaseByDiseaseId;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.sql.Date;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className AlbumDiseasePK
* @see
*/
public class AlbumDiseasePK implements Serializable {
private String albumId;
private Date date;
private String diseaseId;
@Column(name = "album_id", nullable = false, length = 15)
@Id
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
@Column(name = "date", nullable = false)
@Id
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Column(name = "disease_id", nullable = false, length = 150)
@Id
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlbumDiseasePK that = (AlbumDiseasePK) o;
return Objects.equals(albumId, that.albumId) &&
Objects.equals(date, that.date) &&
Objects.equals(diseaseId, that.diseaseId);
}
@Override
public int hashCode() {
return Objects.hash(albumId, date, diseaseId);
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.sql.Date;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className AlbumPK
* @see
*/
public class AlbumPK implements Serializable {
private String albumId;
private Date date;
@Column(name = "album_id", nullable = false, length = 15)
@Id
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
@Column(name = "date", nullable = false)
@Id
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlbumPK albumPK = (AlbumPK) o;
return Objects.equals(albumId, albumPK.albumId) &&
Objects.equals(date, albumPK.date);
}
@Override
public int hashCode() {
return Objects.hash(albumId, date);
}
@Override
public String toString() {
return "AlbumPK{" +
"albumId='" + albumId + '\'' +
", date=" + date +
'}';
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className Code
* @see
*/
@Entity
@Table(name = "code", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Code.findAll", query = "SELECT c FROM Code c")
, @NamedQuery(name = "Code.findById", query = "SELECT c FROM Code c WHERE c.codeId = :codeId AND c.resourceId = :resourceId")
, @NamedQuery(name = "Code.findByCodeId", query = "SELECT c FROM Code c WHERE c.codeId = :codeId")
, @NamedQuery(name = "Code.findByResourceId", query = "SELECT c FROM Code c WHERE c.resourceId = :resourceId")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "Code.findByIdNativeMapping",
query = "SELECT c.code_id, c.resource_id "
+ "FROM code c WHERE c.code_id = :codeId AND c.resource_id = :resourceId",
resultSetMapping="CodeMapping"
),
@NamedNativeQuery(
name = "Code.findByIdNativeResultClass",
query = "SELECT c.code_id, c.resource_id "
+ "FROM code c WHERE c.code_id = :codeId AND c.resource_id = :resourceId",
resultClass = Code.class
),
@NamedNativeQuery(
name = "Code.findByIdNative",
query = "SELECT c.code_id, c.resource_id "
+ "FROM code c WHERE c.code_id = :codeId AND c.resource_id = :resourceId"
),
@NamedNativeQuery(
name = "Code.insertNative",
query = "INSERT INTO code (code_id, resource_id) "
+ "VALUES (:codeId, :resourceId)"
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "CodeMapping",
entities = @EntityResult(
entityClass = Code.class,
fields = {
@FieldResult(name = "codeId", column = "code_id"),
@FieldResult(name = "resourceId", column = "resource_id")
}
)
)
})
@IdClass(CodePK.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="CodePK")
public class Code {
private String codeId;
private Integer resourceId;
private Resource resourceByResourceId;
private List<DiseaseCode> diseaseCodes;
@Id
@Column(name = "code_id", nullable = false, length = 150)
public String getCodeId() {
return codeId;
}
public void setCodeId(String codeId) {
this.codeId = codeId;
}
@Id
@Column(name = "resource_id", nullable = false)
public Integer getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Code code = (Code) o;
return Objects.equals(codeId, code.codeId) &&
Objects.equals(resourceId, code.resourceId);
}
@Override
public int hashCode() {
return Objects.hash(codeId, resourceId);
}
@ManyToOne
@JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false, insertable = false, updatable = false)
public Resource getResourceByResourceId() {
return resourceByResourceId;
}
public void setResourceByResourceId(Resource resourceByResourceId) {
this.resourceByResourceId = resourceByResourceId;
}
@OneToMany(mappedBy = "code")
public List<DiseaseCode> getDiseaseCodes() {
return diseaseCodes;
}
public void setDiseaseCodes(List<DiseaseCode> diseaseCodes) {
this.diseaseCodes = diseaseCodes;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className CodePK
* @see
*/
public class CodePK implements Serializable {
private String codeId;
private Integer resourceId;
@Column(name = "code_id", nullable = false, length = 150)
@Id
public String getCodeId() {
return codeId;
}
public void setCodeId(String codeId) {
this.codeId = codeId;
}
@Column(name = "resource_id", nullable = false)
@Id
public Integer getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CodePK codePK = (CodePK) o;
return Objects.equals(codeId, codePK.codeId) &&
Objects.equals(resourceId, codePK.resourceId);
}
@Override
public int hashCode() {
return Objects.hash(codeId, resourceId);
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className Disease
* @see
*/
@Entity
@Table(name = "disease", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Disease.findAll", query = "SELECT d FROM Disease d")
, @NamedQuery(name = "Disease.findById", query = "SELECT d FROM Disease d WHERE d.diseaseId = :diseaseId")
, @NamedQuery(name = "Disease.findByName", query = "SELECT d FROM Disease d WHERE d.name = :name")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "Disease.findByIdNative",
query = "SELECT d.disease_id, d.name "
+ "FROM disease d WHERE d.disease_id COLLATE utf8_bin = :diseaseId"
),
@NamedNativeQuery(
name = "Disease.findByNameNative",
query = "SELECT d.disease_id, d.name "
+ "FROM disease d WHERE d.name COLLATE utf8_bin = :name"
),
@NamedNativeQuery(
name = "Disease.findLastIdNative",
query = "SELECT d.disease_id " +
"FROM disease d " +
"ORDER BY CAST( SUBSTRING( d.disease_id , 4) AS UNSIGNED) DESC "
),
@NamedNativeQuery(
name = "Disease.insertNative",
query = "INSERT INTO disease (disease_id, name, source_id, partly_irrelevant, totally_irrelevant) "
+ "VALUES (:diseaseId, :name, :sourceId, :partly_irrelevant, :totally_irrelevant)"
),
@NamedNativeQuery(
name = "Disease.getAllDiseasesFromDiseaseSafeListAndLastDiseaseAlbumBySource",
query = "SELECT d.disease_id, d.name, u.url\n" +
"FROM safe_disease d\n" +
"JOIN safe_disease_url du ON d.disease_id = du.disease_id\n" +
"JOIN safe_url u ON du.url_id = u.url_id\n" +
"UNION\n" +
"SELECT DISTINCT d.disease_id, d.name, u.url \n" +
" FROM album a\n" +
" INNER JOIN album_disease ad ON ad.album_id = a.album_id AND ad.date = a.date\n" +
" INNER JOIN disease d ON d.disease_id = ad.disease_id\n" +
" INNER JOIN disease_url du ON du.disease_id = d.disease_id\n" +
" INNER JOIN source s ON s.source_id = du.source_id\n" +
" INNER JOIN url u ON u.url_id = du.url_id\n" +
" WHERE a.date = :current_version \n" +
" AND s.name = :source \n" +
"UNION\n" +
"SELECT DISTINCT d.disease_id, d.name, u.url \n" +
" FROM album a\n" +
" INNER JOIN album_disease ad ON ad.album_id = a.album_id AND ad.date = a.date\n" +
" INNER JOIN disease d ON d.disease_id = ad.disease_id\n" +
" INNER JOIN disease_url du ON du.disease_id = d.disease_id\n" +
" INNER JOIN source s ON s.source_id = du.source_id\n" +
" INNER JOIN url u ON u.url_id = du.url_id\n" +
" WHERE a.date = :penultimate_version \n" +
" AND s.name = :source "
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "DiseaseMapping",
entities = @EntityResult(
entityClass = Disease.class,
fields = {
@FieldResult(name = "diseaseId", column = "disease_id"),
@FieldResult(name = "name", column = "name"),
@FieldResult(name = "partlyIrrelevant", column = "partly_irrelevant"),
@FieldResult(name = "totallyIrrelevant", column = "totally_irrelevant"),
@FieldResult(name = "sourceId", column = "source_id")
}
)
)
})
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="diseaseId")
public class Disease {
private String diseaseId;
private String name;
private Boolean partlyIrrelevant;
private Boolean totallyIrrelevant;
private String sourceId;
private List<AlbumDisease> albumDiseasesByDiseaseId;
private List<DiseaseCode> diseaseCodesByDiseaseId;
private List<DiseaseUrl> diseaseUrlsByDiseaseId;
@Id
@Column(name = "disease_id", nullable = false, length = 150)
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Basic
@Column(name = "name", nullable = false, length = 150)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "partly_irrelevant", nullable = true)
public Boolean getPartlyIrrelevant() {
return partlyIrrelevant;
}
public void setPartlyIrrelevant(Boolean partlyIrrelevant) {
this.partlyIrrelevant = partlyIrrelevant;
}
@Basic
@Column(name = "totally_irrelevant", nullable = true)
public Boolean getTotallyIrrelevant() {
return totallyIrrelevant;
}
public void setTotallyIrrelevant(Boolean totallyIrrelevant) {
this.totallyIrrelevant = totallyIrrelevant;
}
@Basic
@Column(name = "source_id", nullable = false, length = 10)
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Disease disease = (Disease) o;
return Objects.equals(diseaseId, disease.diseaseId) &&
Objects.equals(name, disease.name)&&
Objects.equals(partlyIrrelevant, disease.partlyIrrelevant) &&
Objects.equals(totallyIrrelevant, disease.totallyIrrelevant);
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, name);
}
@OneToMany(mappedBy = "diseaseByDiseaseId")
public List<AlbumDisease> getAlbumDiseasesByDiseaseId() {
return albumDiseasesByDiseaseId;
}
public void setAlbumDiseasesByDiseaseId(List<AlbumDisease> albumDiseasesByDiseaseId) {
this.albumDiseasesByDiseaseId = albumDiseasesByDiseaseId;
}
@OneToMany(mappedBy = "diseaseByDiseaseId")
public List<DiseaseCode> getDiseaseCodesByDiseaseId() {
return diseaseCodesByDiseaseId;
}
public void setDiseaseCodesByDiseaseId(List<DiseaseCode> diseaseCodesByDiseaseId) {
this.diseaseCodesByDiseaseId = diseaseCodesByDiseaseId;
}
@OneToMany(mappedBy = "diseaseByDiseaseId")
public List<DiseaseUrl> getDiseaseUrlsByDiseaseId() {
return diseaseUrlsByDiseaseId;
}
public void setDiseaseUrlsByDiseaseId(List<DiseaseUrl> diseaseUrlsByDiseaseId) {
this.diseaseUrlsByDiseaseId = diseaseUrlsByDiseaseId;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className DiseaseCode
* @see
*/
@Entity
@Table(name = "disease_code", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "DiseaseCode.findAll", query = "SELECT d FROM DiseaseCode d")
, @NamedQuery(name = "DiseaseCode.findById", query = "SELECT d FROM DiseaseCode d WHERE d.diseaseId = :diseaseId AND d.codeId = :codeId AND d.resourceId = :codeId")
, @NamedQuery(name = "DiseaseCode.findByDiseaseId", query = "SELECT d FROM DiseaseCode d WHERE d.diseaseId = :diseaseId")
, @NamedQuery(name = "DiseaseCode.findByCodeId", query = "SELECT d FROM DiseaseCode d WHERE d.codeId = :codeId")
, @NamedQuery(name = "DiseaseCode.findByResourceId", query = "SELECT d FROM DiseaseCode d WHERE d.resourceId = :resourceId")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "DiseaseCode.findByIdNative",
query = "SELECT d.disease_id, d.code_id, d.resource_id "
+ "FROM disease_code d WHERE d.disease_id = :diseaseId AND d.code_id = :codeId AND d.resource_id = :resourceId "
),
@NamedNativeQuery(
name = "DiseaseCode.insertNative",
query = "INSERT INTO disease_code (disease_id, code_id, resource_id) "
+ "VALUES (:diseaseId, :codeId, :resourceId)"
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "DiseaseCodeMapping",
entities = @EntityResult(
entityClass = DiseaseCode.class,
fields = {
@FieldResult(name = "diseaseId", column = "disease_id"),
@FieldResult(name = "codeId", column = "code_id"),
@FieldResult(name = "resourceId", column = "resource_id")
}
)
)
})
@IdClass(DiseaseCodePK.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="DiseaseCodePK")
public class DiseaseCode {
private String diseaseId;
private String codeId;
private Integer resourceId;
private Disease diseaseByDiseaseId;
private Code code;
@Id
@Column(name = "disease_id", nullable = false, length = 150)
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Id
@Column(name = "code_id", nullable = false, length = 150)
public String getCodeId() {
return codeId;
}
public void setCodeId(String codeId) {
this.codeId = codeId;
}
@Id
@Column(name = "resource_id", nullable = false)
public Integer getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiseaseCode that = (DiseaseCode) o;
return Objects.equals(diseaseId, that.diseaseId) &&
Objects.equals(codeId, that.codeId) &&
Objects.equals(resourceId, that.resourceId);
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, codeId, resourceId);
}
@ManyToOne
@JoinColumn(name = "disease_id", referencedColumnName = "disease_id", nullable = false, insertable = false, updatable = false)
public Disease getDiseaseByDiseaseId() {
return diseaseByDiseaseId;
}
public void setDiseaseByDiseaseId(Disease diseaseByDiseaseId) {
this.diseaseByDiseaseId = diseaseByDiseaseId;
}
@ManyToOne
@JoinColumns({@JoinColumn(name = "code_id", referencedColumnName = "code_id", nullable = false, insertable = false, updatable = false),
@JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false, insertable = false, updatable = false)})
public Code getCode() {
return code;
}
public void setCode(Code code) {
this.code = code;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className DiseaseCodePK
* @see
*/
public class DiseaseCodePK implements Serializable {
private String diseaseId;
private String codeId;
private Integer resourceId;
@Column(name = "disease_id", nullable = false, length = 150)
@Id
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Column(name = "code_id", nullable = false, length = 150)
@Id
public String getCodeId() {
return codeId;
}
public void setCodeId(String codeId) {
this.codeId = codeId;
}
@Column(name = "resource_id", nullable = false)
@Id
public Integer getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiseaseCodePK that = (DiseaseCodePK) o;
return Objects.equals(diseaseId, that.diseaseId) &&
Objects.equals(codeId, that.codeId) &&
Objects.equals(resourceId, that.resourceId);
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, codeId, resourceId);
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className DiseaseUrl
* @see
*/
@Entity
@Table(name = "disease_url", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "DiseaseUrl.findAll", query = "SELECT d FROM DiseaseUrl d")
, @NamedQuery(name = "DiseaseUrl.findById", query = "SELECT d FROM DiseaseUrl d WHERE d.diseaseId = :diseaseId AND d.diseaseId = :diseaseId AND d.urlId = :urlId AND d.sourceId = :sourceId")
, @NamedQuery(name = "DiseaseUrl.findByDiseaseId", query = "SELECT d FROM DiseaseUrl d WHERE d.diseaseId = :diseaseId")
, @NamedQuery(name = "DiseaseUrl.findByUrlId", query = "SELECT d FROM DiseaseUrl d WHERE d.urlId = :urlId")
, @NamedQuery(name = "DiseaseUrl.findBySourceId", query = "SELECT d FROM DiseaseUrl d WHERE d.sourceId = :sourceId")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "DiseaseUrl.findByIdNative",
query = "SELECT d.disease_id, d.url_id, d.source_id "
+ "FROM disease_url d WHERE d.disease_id = :diseaseId AND d.url_id = :urlId AND d.source_id = :sourceId "
),
@NamedNativeQuery(
name = "DiseaseUrl.insertNative",
query = "INSERT INTO disease_url (disease_id, url_id, source_id) "
+ "VALUES (:diseaseId, :urlId, :sourceId)"
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "DiseaseUrlMapping",
entities = @EntityResult(
entityClass = DiseaseUrl.class,
fields = {
@FieldResult(name = "diseaseId", column = "disease_id"),
@FieldResult(name = "urlId", column = "url_id"),
@FieldResult(name = "sourceId", column = "source_id")
}
)
)
})
@IdClass(DiseaseUrlPK.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="DiseaseUrlPK")
public class DiseaseUrl {
private String diseaseId;
private String urlId;
private String sourceId;
private Disease diseaseByDiseaseId;
private Url urlByUrlId;
private Source sourceBySourceId;
@Id
@Column(name = "disease_id", nullable = false, length = 150)
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Id
@Column(name = "url_id", nullable = false, length = 15)
public String getUrlId() {
return urlId;
}
public void setUrlId(String urlId) {
this.urlId = urlId;
}
@Id
@Column(name = "source_id", nullable = false, length = 10)
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiseaseUrl that = (DiseaseUrl) o;
return Objects.equals(diseaseId, that.diseaseId) &&
Objects.equals(urlId, that.urlId) &&
Objects.equals(sourceId, that.sourceId);
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, urlId, sourceId);
}
@ManyToOne
@JoinColumn(name = "disease_id", referencedColumnName = "disease_id", nullable = false, insertable = false, updatable = false)
public Disease getDiseaseByDiseaseId() {
return diseaseByDiseaseId;
}
public void setDiseaseByDiseaseId(Disease diseaseByDiseaseId) {
this.diseaseByDiseaseId = diseaseByDiseaseId;
}
@ManyToOne
@JoinColumn(name = "url_id", referencedColumnName = "url_id", nullable = false, insertable = false, updatable = false)
public Url getUrlByUrlId() {
return urlByUrlId;
}
public void setUrlByUrlId(Url urlByUrlId) {
this.urlByUrlId = urlByUrlId;
}
@ManyToOne
@JoinColumn(name = "source_id", referencedColumnName = "source_id", nullable = false, insertable = false, updatable = false)
public Source getSourceBySourceId() {
return sourceBySourceId;
}
public void setSourceBySourceId(Source sourceBySourceId) {
this.sourceBySourceId = sourceBySourceId;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className DiseaseUrlPK
* @see
*/
public class DiseaseUrlPK implements Serializable {
private String diseaseId;
private String urlId;
private String sourceId;
@Column(name = "disease_id", nullable = false, length = 150)
@Id
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Column(name = "url_id", nullable = false, length = 20)
@Id
public String getUrlId() {
return urlId;
}
public void setUrlId(String urlId) {
this.urlId = urlId;
}
@Column(name = "source_id", nullable = false, length = 10)
@Id
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiseaseUrlPK that = (DiseaseUrlPK) o;
return Objects.equals(diseaseId, that.diseaseId) &&
Objects.equals(urlId, that.urlId) &&
Objects.equals(sourceId, that.sourceId);
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, urlId, sourceId);
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Objects;
/**
* Created by gerardo on 26/10/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className Resource
* @see
*/
@Entity
@Table(name = "resource", catalog = "addb", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Resource.findAll", query = "SELECT r FROM Resource r")
, @NamedQuery(name = "Resource.findById", query = "SELECT r FROM Resource r WHERE r.resourceId = :resourceId")
, @NamedQuery(name = "Resource.findByName", query = "SELECT r FROM Resource r WHERE r.name = :name")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "Resource.findByIdNative",
query = "SELECT r.resource_id, r.name "
+ "FROM resource r WHERE r.resource_id = :resourceId",
resultSetMapping="ResourceMapping"
),
@NamedNativeQuery(
name = "Resource.findByNameNative",
query = "SELECT r.resource_id, r.name "
+ "FROM resource r WHERE r.name COLLATE utf8_bin = :name",
resultClass = Resource.class
),
@NamedNativeQuery(
name = "Resource.findAllNative",
query = "SELECT r.resource_id, r.name "
+ "FROM resource r "
),
@NamedNativeQuery(
name = "Resource.findIdByNameNative",
query = "SELECT r.resource_id "
+ "FROM resource r WHERE r.name COLLATE utf8_bin = :name"
),
@NamedNativeQuery(
name = "Resource.insertNative",
query = "INSERT INTO resource (resource_id, name) "
+ "VALUES (:resourceId, :name)"
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "ResourceMapping",
entities = @EntityResult(
entityClass = Resource.class,
fields = {
@FieldResult(name = "resourceId", column = "resource_id"),
@FieldResult(name = "name", column = "name"),
}
)
)
})
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="resourceId")
public class Resource {
private Integer resourceId;
private String name;
private List<Code> codesByResourceId;
@Id
@Column(name = "resource_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
@Basic
@Column(name = "name", nullable = false, length = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Resource resource = (Resource) o;
return Objects.equals(resourceId, resource.resourceId) &&
Objects.equals(name, resource.name);
}
@Override
public int hashCode() {
return Objects.hash(resourceId, name);
}
@OneToMany(mappedBy = "resourceByResourceId")
public List<Code> getCodesByResourceId() {
return codesByResourceId;
}
public void setCodesByResourceId(List<Code> codesByResourceId) {
this.codesByResourceId = codesByResourceId;
}
}
package es.upm.ctb.medal.get_diseases_list.model.jpa;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Objects;
/**
* Created by gerardo on 29/01/2018.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className SafeDisease
* @see
*/
@Entity
@Table(name = "safe_disease", schema = "addb", catalog = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SafeDisease.findAll", query = "SELECT d FROM SafeDisease d")
, @NamedQuery(name = "SafeDisease.findById", query = "SELECT d FROM SafeDisease d WHERE d.diseaseId = :diseaseId")
, @NamedQuery(name = "SafeDisease.findByName", query = "SELECT d FROM SafeDisease d WHERE d.name = :name")
})
@NamedNativeQueries({
@NamedNativeQuery(
name = "SafeDisease.findByIdNative",
query = "SELECT d.disease_id, d.name "
+ "FROM safe_disease d WHERE d.disease_id COLLATE utf8_bin = :diseaseId"
),
@NamedNativeQuery(
name = "SafeDisease.findByNameNative",
query = "SELECT d.disease_id, d.name "
+ "FROM safe_disease d WHERE d.name COLLATE utf8_bin = :name"
),
@NamedNativeQuery(
name = "SafeDisease.findLastIdNative",
query = "SELECT d.disease_id " +
"FROM safe_disease d " +
"ORDER BY CAST( SUBSTRING( d.disease_id , 4) AS UNSIGNED) DESC "
),
@NamedNativeQuery(
name = "SafeDisease.insertNative",
query = "INSERT IGNORE INTO safe_disease (disease_id, name, source_id) "
+ "VALUES (:diseaseId, :name, :sourceId)"
),
//Obtiene todas las enfermedades de la safe list segun la fuente
@NamedNativeQuery(
name = "SafeDisease.findAllDiseasesBySource",
query = "-- consultar la \"disease safe list\"\n" +
"SELECT d.name 'diseaseName', u.url, d.disease_id " +
"FROM safe_disease d " +
"INNER JOIN safe_disease_url du ON du.disease_id = d.disease_id " +
"INNER JOIN source s ON s.source_id = du.source_id " +
"INNER JOIN safe_url u ON u.url_id = du.url_id " +
"WHERE s.name = :source "
)
})
@SqlResultSetMappings({
@SqlResultSetMapping(
name = "SafeDiseaseMapping",
entities = @EntityResult(
entityClass = SafeDisease.class,
fields = {
@FieldResult(name = "diseaseId", column = "disease_id"),
@FieldResult(name = "name", column = "name")
}
)
)
})
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="diseaseId")
public class SafeDisease {
private String diseaseId;
private String name;
private String sourceId;
private List<SafeDiseaseUrl> safeDiseaseUrlsByDiseaseId;
@Id
@Column(name = "disease_id", nullable = false, length = 150)
public String getDiseaseId() {
return diseaseId;
}
public void setDiseaseId(String diseaseId) {
this.diseaseId = diseaseId;
}
@Basic
@Column(name = "name", nullable = false, length = 150)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "source_id", nullable = false, length = 10)
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SafeDisease that = (SafeDisease) o;
return Objects.equals(diseaseId, that.diseaseId) &&
Objects.equals(name, that.name) ;
}
@Override
public int hashCode() {
return Objects.hash(diseaseId, name);
}
@OneToMany(mappedBy = "safeDiseaseByDiseaseId")
public List<SafeDiseaseUrl> getSafeDiseaseUrlsByDiseaseId() {
return safeDiseaseUrlsByDiseaseId;
}
public void setSafeDiseaseUrlsByDiseaseId(List<SafeDiseaseUrl> safeDiseaseUrlsByDiseaseId) {
this.safeDiseaseUrlsByDiseaseId = safeDiseaseUrlsByDiseaseId;
}
}
package es.upm.ctb.medal.get_diseases_list.model.request;
import es.upm.ctb.medal.common.constants.Constants;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Created by gerardo on 02/11/2017.
*
* @author Gerardo Lagunes G. ${EMAIL}
* @version ${<VERSION>}
* @project get_diseases_list_rest
* @className RequestFather
* @see
*/
public class RequestFather {
@Valid
@NotNull(message = Constants.ERR_NO_PARAMETER)
@Size(min = 1, message = Constants.ERR_EMPTY_PARAMETER)
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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