new public branch

parents
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
war {
enabled = true
archivesBaseName = 'ipmworks'
archiveClassifier = ''
}
sourceCompatibility = '11'
repositories{
mavenCentral()
maven{url "https://jaspersoft.jfrog.io/jaspersoft/third-party-ce-artifacts/"}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
implementation group: 'net.sf.jasperreports', name: 'jasperreports', version: '6.16.0'
implementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1'
implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
implementation group: 'org.glassfish.jaxb', name: 'jaxb-core', version: '2.3.0.1'
implementation group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'
implementation group: 'org.apache.poi', name: 'poi', version: '4.1.2'
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'ipmworks'
package ipm.ipmworks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class IpmworksBackendApplication {
public static void main(String[] args) {
SpringApplication.run(IpmworksBackendApplication.class, args);
System.out.println("Hello there");
}
}
package ipm.ipmworks;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(IpmworksBackendApplication.class);
}
}
package ipm.ipmworks.control;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import ipm.ipmworks.model.Resource;
import ipm.ipmworks.repository.ResourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
@RestController
@RequestMapping(value="/admin")
public class AdminResourceController {
@Autowired
ResourceRepository resourceRepository;
@Autowired
GridFsTemplate gridFsTemplate;
@RequestMapping(value="/getResourceForApproval", method= RequestMethod.GET)
public List<Resource> getResourceForApproval(){
return resourceRepository.findByApprovedIsFalse();
}
@GetMapping("/approve/{id}")
public void approveResource(@PathVariable("id") String idResource){
Optional<Resource> resource = resourceRepository.findById(idResource);
if (resource.isPresent()){
Resource r = resource.get();
r.setApproved(true);
resourceRepository.save(r);
}
}
@GetMapping("/delete/{id}")
public void deleteResource(@PathVariable("id") String idResource){
resourceRepository.deleteById(idResource);
Query query = new Query();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource));
gridFsTemplate.delete(query);
}
}
package ipm.ipmworks.control;
import ipm.ipmworks.model.*;
import ipm.ipmworks.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value="/codebooks")
public class CodebooksController {
@Autowired
RegionRepository cr;
@Autowired
ResourceTypeRepository rtr;
@Autowired
SectorRepository sr;
@Autowired
PestRepository pr;
@Autowired
CropRepository crR;
@Autowired
LanguageRepository lr;
@Autowired
ProjectRepository prR;
@RequestMapping(value="/saveResourceType", method= RequestMethod.POST)
public ResourceType saveResourceType(@RequestBody ResourceType rt){
ResourceType resType= rtr.save(rt);
return resType;
}
@RequestMapping(value="/getAllResourceTypes", method=RequestMethod.GET)
public List<ResourceType> getResourceTypes(){
return rtr.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
@RequestMapping(value="/saveSector", method= RequestMethod.POST)
public Sector saveSector(@RequestBody Sector s){
Sector sector= sr.save(s);
return sector;
}
@RequestMapping(value="/getAllSectors", method=RequestMethod.GET)
public List<Sector> getSecotrs(){
return sr.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
@RequestMapping(value="/getAllRegions", method=RequestMethod.GET)
public List<Region> getRegions(){return cr.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
@RequestMapping(value="/savePest", method= RequestMethod.POST)
public Pest savePest(@RequestBody Pest p){
Pest pest = pr.save(p);
return pest;
}
@RequestMapping(value="/getAllPests", method=RequestMethod.GET)
public List<Pest> getPests(){
return pr.findAll(Sort.by(Sort.Direction.ASC, "commonName"));
}
@RequestMapping(value="/saveCrop", method= RequestMethod.POST)
public Crop saveCrop(@RequestBody Crop c){
Crop crop = crR.save(c);
return crop;
}
@RequestMapping(value="/getAllCrops", method=RequestMethod.GET)
public List<Crop> getCrops(){
return crR.findAll(Sort.by(Sort.Direction.ASC, "commonName"));
}
@RequestMapping(value="/saveLanguage", method= RequestMethod.POST)
public Language saveLanguage(@RequestBody Language l){
Language lang = lr.save(l);
return lang;
}
@RequestMapping(value="/getAllLanguages", method=RequestMethod.GET)
public List<Language> getLanguages(){
return lr.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
@RequestMapping(value="/saveProject", method= RequestMethod.POST)
public Project saveProject(@RequestBody Project p){
Project proj = prR.save(p);
return proj;
}
@RequestMapping(value="/getAllProjects", method=RequestMethod.GET)
public List<Project> getProjects(){
return prR.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
}
package ipm.ipmworks.control;
import ipm.ipmworks.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("file")
public class FileController {
@Autowired
FileService fileService;
@GetMapping("/get/{id}")
public ResponseEntity<InputStreamResource> getFileById(@PathVariable("id") String fileId) throws IOException {
GridFsResource gridFSFile = fileService.getFileById(fileId);
if (gridFSFile == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
try {
return ResponseEntity.ok()
.contentLength(gridFSFile.contentLength())
.contentType(MediaType.valueOf(gridFSFile.getContentType()))
.body(new InputStreamResource(gridFSFile.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/help/list")
public List<Map> getListOfHelpFiles(){
return fileService.getFileDescription("help");
}
@PostMapping(value="/add")
public ResponseEntity<Boolean> addFile(@RequestPart(name="file", required = false) MultipartFile file,
@RequestPart(name="description", required = false) String description,
@RequestPart(value = "type", required = false) String type) {
try {
if (!fileService.uploadFile(file,description,type))
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(true, HttpStatus.OK);
}
catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value="/delete/{id}")
public ResponseEntity<Boolean> deleteFile(@PathVariable("id") String id) {
try {
if (!fileService.deleteFile(id))
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(true, HttpStatus.OK);
}
catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
package ipm.ipmworks.control;
import com.mongodb.BasicDBObject;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import ipm.ipmworks.model.*;
import ipm.ipmworks.repository.*;
import ipm.ipmworks.service.FileService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRSwapFile;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfReportConfiguration;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
import java.io.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value="/resource")
public class ResourceController {
@Autowired
ResourceRepository rr;
@Autowired
RegionRepository regionRepository;
@Autowired
MongoTemplate mongoTemplate;
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
FileService fileService;
@Autowired
@Qualifier("ipmDecisionRest")
RestTemplate ipmDecisionRest;
@Autowired
@Qualifier("organicKnowledgeRest")
RestTemplate organicKnowledgeRest;
@Autowired
ResourceTypeRepository resourceTypeRepository;
@Autowired
ProjectRepository projectRepository;
@Autowired
LanguageRepository languageRepository;
@Autowired
PestRepository pestRepository;
@Autowired
CropRepository cropRepository;
@Value("${organic_knowledge.search.bykeword}")
private String searchByKeyword;
@Value("${organic_knowledge.search.bytitle}")
private String searchByTitle;
@RequestMapping(value="/saveResource", method= RequestMethod.POST)
public Resource saveResource(@RequestBody Resource r){
Resource res = rr.save(r);
return res;
}
@RequestMapping(value="/getAllResources", method=RequestMethod.GET)
public Page<Resource> getResources(@RequestParam(required = false) final Integer pageNumber, @RequestParam(required = false) final Integer pageSize) {
int pSize = 10;
int pNum = 0;
if (pageSize != null) {
pSize = pageSize;
}
if (pageNumber != null) {
pNum = pageNumber;
}
Pageable pageable = PageRequest.of(pNum, pSize);
return rr.findByApprovedIsTrue(pageable);
}
private Resource createResourceFromOrganicKnowledge(LinkedHashMap map){
String title = (String) map.get("title");
if(title != null && !title.isEmpty()) {
Resource r = new Resource();
r.setExternal(true);
r.getLinks().add("https://orgprints.org/");
r.setCanEdit(false);
r.setProject("Organic Eprints");
if (title != null) {
r.setResourceName(title);
}
r.setIdResource("eprint_" + (Integer) map.get("eprintid") );
if ((String) map.get("type") != null) {
ResourceType temp = new ResourceType();
temp.setName((String) map.get("type"));
r.setResourceType(temp);
}
if ((String) map.get("institution") != null) {
r.setContactInstitution((String) map.get("institution"));
if ((String) map.get("department") != null) {
String inst = r.getContactInstitution() + ", " + (String) map.get("department");
r.setContactInstitution(inst);
}
}
if ((String) map.get("abstract") != null) {
r.setDescription((String) map.get("abstract"));
}
if ((List) map.get("doclang") != null) {
String lang = (String) ((List<?>) map.get("doclang")).get(0);
Language l = languageRepository.findByCode(lang);
r.setLanguage(l);
}
if ((List<String>) map.get("documents") != null) {
List<LinkedHashMap> documents = (List<LinkedHashMap>) map.get("documents");
for (LinkedHashMap doc : documents) {
r.getLinks().add((String) doc.get("uri"));
}
}
if ((String) map.get("uri") != null) {
r.setResourceOrigin((String) map.get("uri"));
}
if ((String) map.get("contact_email") != null) {
r.setContactEmail((String) map.get("contact_email"));
}
return r;
}else{
return null;
}
}
private Resource createResourceFromIPMDecisions(LinkedHashMap map){
Resource r = new Resource();
r.setExternal(true);
r.getLinks().add("https://platform.ipmdecisions.net/");
r.setCanEdit(false);
if((String) map.get("resourceName")!=null){
r.setResourceName((String) map.get("resourceName"));
}
if((String) map.get("resourceId")!=null){
r.setIdResource(((String) map.get("resourceId")).replaceFirst(";","_"));
}
if((String) map.get("idResource")!=null){
r.setIdResource(((String) map.get("idResource")).replaceFirst(";","_"));
}
if((String) map.get("project")!=null){
r.setProject((String) map.get("project"));
}
if((String) map.get("description")!=null){
r.setDescription((String)map.get("description"));
}
if((String) map.get("resourceOrigin")!=null){
r.setResourceOrigin((String)map.get("resourceOrigin"));
}
if((String) map.get("contactInstitution")!=null){
r.setContactInstitution((String)map.get("contactInstitution"));
}
if((String) map.get("contactEmail")!=null){
r.setContactEmail((String)map.get("contactEmail"));
}
if((String) map.get("contactPhone")!=null){
r.setContactPhone((String)map.get("contactPhone"));
}
if((String) map.get("citation")!=null){
r.setCitation((String)map.get("citation"));
}
if((String) map.get("contactAddress")!=null){
r.setContactAddress((String) map.get("contactAddress"));
}
if((String) map.get("resourceType")!=null){
ResourceType resourceType = resourceTypeRepository.findByName((String)map.get("resourceType"));
r.setResourceType(resourceType);
}
if((List<String>) map.get("regions")!=null){
List<String> regions =(List<String>) map.get("regions");
for(String reg:regions) {
Region region = regionRepository.findByCode(reg);
r.getRegions().add(region);
}
}
if((List<String>) map.get("languages")!=null){
List<String> languages =(List<String>) map.get("languages");
if (languages.size() > 1){
Language temp = new Language(String.join(", ",languages));
r.setLanguage(temp);
}else{
for(String lan:languages) {
Language l = languageRepository.findByName(lan);
r.setLanguage(l);
}
}
}
if((List<String>) map.get("pests")!=null){
List<String> pests =(List<String>) map.get("pests");
for(String pest:pests) {
List<Pest> pestList = pestRepository.findByEPPO(pest);
r.getPests().addAll(pestList);
}
}
if((List<String>) map.get("crops")!=null){
List<String> crops =(List<String>) map.get("crops");
for(String crop:crops) {
List<Crop> croplist = cropRepository.findByEPPO(crop);
r.getCrops().addAll(croplist);
}
}
return r;
}
@GetMapping(value = {"/get/{idResource}","/get/{idResource}/{lang}"})
public Resource getResource(@PathVariable("idResource") String idResource, @PathVariable(value = "lang", required = false) String lang){
Optional<Resource> resource = rr.findById(idResource);
if (resource.isEmpty()){
if (idResource.startsWith("eprint")){
String idRes = idResource.substring(7);
/* byte[] titleBytes = Base64.getDecoder().decode(idRes.getBytes());
String title = new String(titleBytes);
List<LinkedHashMap> map = organicKnowledgeRest.getForObject(searchByTitle+title+"|", List.class);*/
List<LinkedHashMap> map = organicKnowledgeRest.getForObject(searchByTitle+idRes, List.class);
return createResourceFromOrganicKnowledge(map.get(0));
}else{
//ovo je ipm decision
String idRes = idResource.replaceFirst("_",";");
HttpHeaders headers = new HttpHeaders();
if (lang != null){
headers.set("Accept-Language", lang);
}else{
headers.set("Accept-Language", "en");
}
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<LinkedHashMap> map = ipmDecisionRest.exchange("/search/"+idRes, HttpMethod.GET, entity,LinkedHashMap.class);
return createResourceFromIPMDecisions(map.getBody());
}
}else{
List <Map> files = getResourceFiles(idResource);
Resource r = resource.get();
r.setFiles(files);
return r;
}
}
@GetMapping("/imageExist/{type}/{idResource}")
public boolean hasImage(@PathVariable("idResource") String idResource, @PathVariable("type") String type){
Query query = new Query();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource).and("metadata.type").is(type));
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (gridFSFile == null){
return false;
}else{
return true;
}
}
@GetMapping("/file/{name}")
@ResponseBody
public ResponseEntity<InputStreamResource> getResourceFile(@PathVariable("name") String name) {
GridFsResource gridFSFile = gridFsTemplate.getResource(name);
if (gridFSFile == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
try {
return ResponseEntity.ok()
.contentLength(gridFSFile.contentLength())
.contentType(MediaType.valueOf(gridFSFile.getContentType()))
.body(new InputStreamResource(gridFSFile.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/image/raw/{idResource}/{type}")
@ResponseBody
public ResponseEntity<InputStreamResource> getImageRaw(@PathVariable("idResource") String idResource,@PathVariable("type") String type) {
try {
GridFsResource gridFSFile = fileService.getResourceImage(idResource,type);
if (gridFSFile != null) {
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(MediaType.IMAGE_JPEG_VALUE))
.contentType(MediaType.parseMediaType(MediaType.IMAGE_PNG_VALUE))
.contentType(MediaType.parseMediaType(MediaType.IMAGE_GIF_VALUE))
.body(new InputStreamResource(gridFSFile.getInputStream()));
}else{
return null;
}
}catch(IOException e){
e.printStackTrace();
return ResponseEntity.internalServerError().build();
}
}
@GetMapping("/image/{idResource}")
@ResponseBody
public ResponseEntity<InputStreamResource> getImage(@PathVariable("idResource") String idResource) {
Optional<Resource> res = rr.findById(idResource);
String imageName;
Resource resource=null;
if (res.isPresent()) {
resource = res.get();
if (resource.getProject()!=null && resource.getProject().equals("Smart Protect")){
imageName="smartprotect";
}else if (resource.getProject()!=null && resource.getProject().equals("Endure")){
imageName="endure";
}else if (resource.getSectors() != null && resource.getSectors().size() >2) {
imageName = "multi";
}else if (resource.getSectors() != null && resource.getSectors().size() ==1) {
imageName = resource.getSectors().get(0).getSectorIcon();
}else if (resource.getSectors() != null && resource.getSectors().size() ==2) {
imageName = resource.getSectors().get(0).getSectorIcon()+"_"+resource.getSectors().get(1).getSectorIcon();
}
else{
imageName = "multi";
}
}else if (idResource.startsWith("adas")) { //ovo je resurs iz IPM Decision
imageName="ipmdecision";
}else if (idResource.startsWith("eprint")){ //eprint baza
imageName="organiceprint";
}else{
imageName="ipmdecision";
}
try {
InputStream logo = fileService.getResourceImage(imageName, "logo").getInputStream();
if(logo !=null){
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(MediaType.IMAGE_JPEG_VALUE))
.contentType(MediaType.parseMediaType(MediaType.IMAGE_PNG_VALUE))
.body(new InputStreamResource(logo));
}else{
return ResponseEntity.internalServerError().build();
}
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.internalServerError().build();
}
}
/* @GetMapping("/image/{idResource}")
@ResponseBody
public ResponseEntity<InputStreamResource> getImage(@PathVariable("idResource") String idResource) {
Optional<Resource> res = rr.findById(idResource);
String regionImage = "images/regions/Default.png";
String sectorImage = "images/sectors/multi.jpg";
String languageImage = "images/languages/english.png";
Resource resource=null;
if (res.isPresent()) {
resource = res.get();
}else if (idResource.startsWith("adas")) { //ovo je resurs iz IPM Decision
String idRes = idResource.replaceFirst("_",";");
LinkedHashMap map = ipmDecisionRest.getForObject("/search/"+idRes, LinkedHashMap.class);
resource = createResourceFromIPMDecisions(map);
}else { //eprint baza
if (idResource.length() > 7){
String idRes = idResource.substring(7);
List<LinkedHashMap> map = organicKnowledgeRest.getForObject(searchByTitle + idRes , List.class);
if (map != null && !map.isEmpty()) {
resource = createResourceFromOrganicKnowledge(map.get(0));
}
}
}
List<Sector> sectors = resource.getSectors();
List<Region> regions = resource.getRegions();
Language language = resource.getLanguage();
String icon1 = null, icon2 = null, icon3 = null, icon4 = null, icon5 = null;
if (sectors != null && sectors.size()==1) {
sectorImage = "images/sectors/" + sectors.get(0).getSectorIcon();
}else if (sectors != null && sectors.size()>1){
sectorImage = "images/sectors/multi/" + sectors.get(0).getSectorIcon();
if(sectors.size()>=1){
icon1 = "images/icons/"+sectors.get(0).getSectorIcon();
}
if(sectors.size()>=2){
icon2 = "images/icons/"+sectors.get(1).getSectorIcon();
}
if(sectors.size()>=3){
icon3 = "images/icons/"+sectors.get(2).getSectorIcon();
}
if(sectors.size()>=4){
icon4 = "images/icons/"+sectors.get(3).getSectorIcon();
}
if(sectors.size()>=5){
icon5 = "images/icons/"+sectors.get(4).getSectorIcon();
}
}
if (language != null) {
languageImage = "images/languages/" + language.getName().toLowerCase()+".png";
}
if (regions != null && !regions.isEmpty()){
Region r = regionRepository.findByName(regions.get(0).getName());
if (r == null){
regionImage = "images/regions/Default.png";
}else{
regionImage = "images/regions/"+regions.get(0).getName().replaceFirst(" ","_")+".png";
}
}
try {
GridFsResource gridFSFileImage = fileService.getResourceImage(idResource,"image");
GridFsResource gridFSFileLogo = fileService.getResourceImage(idResource,"logo");
InputStream logo = null;
if (gridFSFileLogo != null){
logo = gridFSFileLogo.getInputStream();
}else{
if (resource.getProject().equals("Smart Protect")) {
logo = fileService.getResourceImage("smartprotect", "logo").getInputStream();
}else if (resource.getProject().equals("Organic Eprints")) {
logo = fileService.getResourceImage("organiceprint", "logo").getInputStream();
}else if (resource.getProject().equals("IPM Decisions")) {
logo = fileService.getResourceImage("6239f180051d511bc931ea30", "logo").getInputStream();
}
}
Image generatedImg = null;
if (gridFSFileImage != null) {
generatedImg = generateImage(sectorImage,gridFSFileImage.getInputStream(), regionImage, logo, languageImage,icon1,icon2,icon3,icon4,icon5);
} else {
generatedImg = generateImage(sectorImage, null, regionImage, logo, languageImage,icon1,icon2,icon3,icon4,icon5);
}
InputStream is = createInputStream(generatedImg);
if(is !=null){
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(MediaType.IMAGE_JPEG_VALUE))
.contentType(MediaType.parseMediaType(MediaType.IMAGE_PNG_VALUE))
.body(new InputStreamResource(is));
}else{
return ResponseEntity.internalServerError().build();
}
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.internalServerError().build();
}
}*/
private InputStream createInputStream(Image generatedImg){
try {
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
ImageOutputStream outputStream = ImageIO.createImageOutputStream(compressed);
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("JPG").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(0.6f);
jpgWriter.setOutput(outputStream);
jpgWriter.write(null, new IIOImage((RenderedImage) generatedImg, null, null), jpgWriteParam);
jpgWriter.dispose();
InputStream is = new ByteArrayInputStream(compressed.toByteArray());
is.close();
return is;
}catch (Exception e){
return null;
}
}
private BufferedImage generateImage(String sectorImagePath,InputStream centralImage,String regionImagePath,InputStream projectLogo, String languageImagePath, String icon1, String icon2, String icon3, String icon4, String icon5) throws IOException {
try {
InputStream inputStream = this.getClass().getResourceAsStream("/jasper/ipmworks_template.jasper");
File region = new ClassPathResource(regionImagePath).getFile();
File language = new ClassPathResource(languageImagePath).getFile();
File sector = new ClassPathResource(sectorImagePath).getFile();
Image userDefinedImg = null;
if(centralImage != null){
userDefinedImg = ImageIO.read(centralImage);
}
Image sectorImage = ImageIO.read(sector);
Image regionImage = ImageIO.read(region);
Image projectLogoImg = null;
Image icon1Img, icon2Img, icon3Img, icon4Img, icon5Img;
File icon1File,icon2File,icon3File,icon4File,icon5File;
Map templateMap = new HashMap<>();
if (icon1 != null){
icon1File = new ClassPathResource(icon1).getFile();
icon1Img = ImageIO.read(icon1File);
templateMap.put("icon1", icon1Img);
}
if (icon2 != null){
icon2File = new ClassPathResource(icon2).getFile();
icon2Img = ImageIO.read(icon2File);
templateMap.put("icon2", icon2Img);
}
if (icon3 != null){
icon3File = new ClassPathResource(icon3).getFile();
icon3Img = ImageIO.read(icon3File);
templateMap.put("icon3", icon3Img);
}
if (icon4 != null){
icon4File = new ClassPathResource(icon4).getFile();
icon4Img = ImageIO.read(icon4File);
templateMap.put("icon4", icon4Img);
}
if (icon5 != null){
icon5File = new ClassPathResource(icon5).getFile();
icon5Img = ImageIO.read(icon5File);
templateMap.put("icon5", icon5Img);
}
if (projectLogo != null){
projectLogoImg = ImageIO.read(projectLogo);
templateMap.put("projectLogo", projectLogoImg);
}
Image languageImage = ImageIO.read(language);
if(userDefinedImg != null){
templateMap.put("userDefinedImg", userDefinedImg);
}
templateMap.put("sector", sectorImage);
templateMap.put("region", regionImage);
templateMap.put("language", languageImage);
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, templateMap, new JREmptyDataSource());
inputStream.close();
DefaultJasperReportsContext ctx = DefaultJasperReportsContext.getInstance();
JasperPrintManager printManager = JasperPrintManager.getInstance(ctx);
BufferedImage rendered_image = null;
rendered_image = (BufferedImage) printManager.printPageToImage(jasperPrint, 0, 1f);
return rendered_image;
} catch (IOException | JRException ex) {
ex.printStackTrace();
return null;
}
}
private List<Map> getResourceFiles(String idResource) {
Query query = new Query();
List<Map> files = new ArrayList<>();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource).and("metadata.type").is("resource"));
GridFSFindIterable gridFSFiles = gridFsTemplate.find(query);
gridFSFiles.forEach((Consumer<? super GridFSFile>) gridFSFile -> {
Map m = new HashMap();
m.put("description",gridFSFile.getFilename());
m.put("fileIdentifier",gridFSFile.getObjectId().toHexString());
files.add(m);
});
return files;
}
@PostMapping(value="/add/{idResource}")
public ResponseEntity<Boolean> addFiles(@PathVariable("idResource") String idResource,@RequestPart(name="image", required = false) MultipartFile image,
@RequestPart(name="logo", required = false) MultipartFile logo,
@RequestPart(value = "files", required = false) MultipartFile[] files) {
try {
if (!uploadFile(idResource,image,logo,files))
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(true, HttpStatus.OK);
}
catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private boolean uploadFile(String idResource, MultipartFile image,MultipartFile logo,MultipartFile[] files) throws IOException {
if (rr.findById(idResource).isEmpty()){
return false;
}else {
if(image != null) {
BasicDBObject metaDataImage = new BasicDBObject();
metaDataImage.put("idResource", idResource);
Query query = new Query();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource).and("metadata.type").is("image"));
gridFsTemplate.delete(query);
metaDataImage.put("type", "image");
gridFsTemplate.store(image.getInputStream(), image.getOriginalFilename(), image.getContentType(), metaDataImage);
}
if(logo != null) {
BasicDBObject metaDataLogo = new BasicDBObject();
metaDataLogo.put("idResource", idResource);
Query query = new Query();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource).and("metadata.type").is("logo"));
gridFsTemplate.delete(query);
metaDataLogo.put("type", "logo");
gridFsTemplate.store(logo.getInputStream(), logo.getOriginalFilename(), logo.getContentType(), metaDataLogo);
}
if( files != null) {
for (MultipartFile mf : files) {
BasicDBObject metaDataResource = new BasicDBObject();
metaDataResource.put("idResource", idResource);
metaDataResource.put("type", "resource");
gridFsTemplate.store(mf.getInputStream(), mf.getOriginalFilename(), mf.getContentType(), metaDataResource);
}
}
return true;
}
}
private String createSearchCriteria(SearchModel searchModel){
List<String> criteria= new ArrayList<>();
List<Sector> sectors = searchModel.getSector();
List<ResourceType> resourceTypes = searchModel.getResourceType();
List<Crop> crops = searchModel.getCrop();
List<Pest> pests = searchModel.getPest();
// List<Language> languages = searchModel.getLanguage();
List<Region> regions = searchModel.getRegion();
Project project = searchModel.getProject();
String title = searchModel.getTitle();
if (title != null){
criteria.add(title);
}
if(sectors !=null && !sectors.isEmpty()) {
criteria.add(sectors.stream().map(Sector::getName).collect(Collectors.joining(",")));
}
if(resourceTypes !=null && !resourceTypes.isEmpty()) {
criteria.add(resourceTypes.stream().map(ResourceType::getName).collect(Collectors.joining(",")));
}
if(crops !=null && !crops.isEmpty()) {
criteria.add(crops.stream().map(Crop::getCommonName).collect(Collectors.joining(",")));
}
if(pests !=null && !pests.isEmpty()) {
criteria.add(pests.stream().map(Pest::getCommonName).collect(Collectors.joining(",")));
}
/* if(languages !=null && !languages.isEmpty()) {
criteria.add(languages.stream().map(Language::getName).collect(Collectors.joining(",")));
}*/
if(regions !=null && !regions.isEmpty()) {
criteria.add(regions.stream().map(Region::getName).collect(Collectors.joining(",")));
}
if(project !=null) {
criteria.add(project.getName());
}
return String.join(",", criteria);
}
private List<Resource> searchOrganicKnowledge(SearchModel searchModel){
List<Resource> result = new ArrayList();
try{
String searchCriteria = createSearchCriteria(searchModel);
List<LinkedHashMap> hashMaps = organicKnowledgeRest.getForObject(searchByKeyword+searchCriteria, List.class);
for (LinkedHashMap map : hashMaps) {
Resource r = createResourceFromOrganicKnowledge(map);
if(r !=null) {
result.add(r);
}
}
return result;
}catch (Exception e) {
e.printStackTrace();
System.out.println("Organic knowledge search error!");
return result;
}
}
private List<Resource> searchIPMDecision(SearchModel searchModel) throws Exception{
List<Resource> resourceList = new ArrayList<>();
String acceptLanguage = null;
IpmDecisionModel model = new IpmDecisionModel();
if(searchModel.getPest()!= null && !searchModel.getPest().isEmpty()){
for(Pest p: searchModel.getPest()) {
model.getPests().add(p.getEPPO());
}
}
if(searchModel.getCrop()!= null && !searchModel.getCrop().isEmpty()){
for(Crop c: searchModel.getCrop()) {
model.getCrops().add(c.getEPPO());
}
}
if(searchModel.getLanguage()!=null && !searchModel.getLanguage().isEmpty()){
List languages = new ArrayList();
for(Language l: searchModel.getLanguage()){
model.getLanguages().add(l.getCode());
languages.add(l.getCode());
}
acceptLanguage = String.join(",",languages);
}
if(searchModel.getRegion()!=null && !searchModel.getRegion().isEmpty()){
for(Region r: searchModel.getRegion()){
model.getRegions().add(r.getCode());
}
}
if(!model.isEmpty()) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept-Language", acceptLanguage);
model.getLanguages().clear();
HttpEntity entity = new HttpEntity(model, headers);
ResponseEntity<List> result = ipmDecisionRest.postForEntity("/search", entity, List.class);
for (LinkedHashMap map : (List<LinkedHashMap>) result.getBody()) {
Resource r = createResourceFromIPMDecisions(map);
resourceList.add(r);
}
}else{
ResourceType type = resourceTypeRepository.findByName("IPM Decisions Model");
if ((searchModel.getProject()!=null && searchModel.getProject().getName().equals("IPM Decisions")) || (searchModel.getResourceType() !=null && searchModel.isIPMDecision() )) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept-Language", acceptLanguage);
HttpEntity entity = new HttpEntity(new LinkedHashMap<>(), headers);
ResponseEntity<List> result = ipmDecisionRest.postForEntity("/search", entity, List.class);
for (LinkedHashMap map : (List<LinkedHashMap>)result.getBody()) {
Resource r = createResourceFromIPMDecisions(map);
resourceList.add(r);
}
}
}
return resourceList;
}
@PostMapping("/search")
public List<Resource> searchResource(@RequestBody SearchModel searchModel) throws Exception {
Query query = new Query();
Criteria current = new Criteria();
Criteria sectorsCriteria= null;
Criteria regionsCriteria= null;
Criteria resourceTypeCriteria= null;
Criteria cropCriteria= null;
Criteria pestCriteria= null;
Criteria languageCriteria= null;
Criteria titleCriteria = null;
if(searchModel.getTitle() !=null){
titleCriteria = new Criteria().where("resourceName").regex(".*"+searchModel.getTitle()+".*","i");
}
if(searchModel.getSector() !=null) {
List<Criteria> sectors = new ArrayList<Criteria>();
for (Sector s : searchModel.getSector()) {
Criteria c = new Criteria().where("sectors.name").is(s.getName());
sectors.add(c);
}
if (!sectors.isEmpty()) {
sectorsCriteria = new Criteria();
sectorsCriteria = sectorsCriteria.orOperator(sectors);
}
}
if(searchModel.getRegion() !=null) {
List<Criteria> regions = new ArrayList<Criteria>();
for (Region r : searchModel.getRegion()) {
if (r.getName().equalsIgnoreCase("All")){
Criteria c = new Criteria().where("regions.name").exists(true);
regions.add(c);
}else {
Criteria c = new Criteria().where("regions.name").is(r.getName());
regions.add(c);
}
}
if (!regions.isEmpty()) {
regionsCriteria = new Criteria();
regionsCriteria = regionsCriteria.orOperator(regions);
}
}
if(searchModel.getResourceType() !=null) {
List<Criteria> resourceTypes = new ArrayList<Criteria>();
for (ResourceType r : searchModel.getResourceType()) {
Criteria c = new Criteria().where("resourceType.name").is(r.getName());
resourceTypes.add(c);
}
if (!resourceTypes.isEmpty()) {
resourceTypeCriteria = new Criteria();
resourceTypeCriteria = resourceTypeCriteria.orOperator(resourceTypes);
}
}
if(searchModel.getCrop()!=null) {
List<Criteria> crops = new ArrayList<Criteria>();
for (Crop crop : searchModel.getCrop()) {
if (crop.getCommonName().equalsIgnoreCase("All")){
Criteria c = new Criteria().where("crops.commonName").exists(true);
crops.add(c);
}else {
Criteria c = new Criteria().where("crops.commonName").is(crop.getCommonName());
crops.add(c);
}
}
if (!crops.isEmpty()) {
cropCriteria = new Criteria();
cropCriteria = cropCriteria.orOperator(crops);
}
}
if(searchModel.getPest() !=null) {
List<Criteria> pests = new ArrayList<Criteria>();
for (Pest p : searchModel.getPest()) {
if (p.getCommonName().equalsIgnoreCase("All")){
Criteria c = new Criteria().where("pests.commonName").exists(true);
pests.add(c);
}else {
Criteria c = new Criteria().where("pests.commonName").is(p.getCommonName());
pests.add(c);
}
}
if (!pests.isEmpty()) {
pestCriteria = new Criteria();
pestCriteria = pestCriteria.orOperator(pests);
}
}
if(searchModel.getLanguage() !=null) {
List<Criteria> languages = new ArrayList<Criteria>();
for (Language l : searchModel.getLanguage()) {
Criteria c = new Criteria().where("language.name").is(l.getName());
languages.add(c);
}
if (!languages.isEmpty()) {
languageCriteria = new Criteria();
languageCriteria = languageCriteria.orOperator(languages);
}
}
List<Criteria> andCriteria = new ArrayList<Criteria>();
if (titleCriteria != null){
andCriteria.add(titleCriteria);
}
if (sectorsCriteria != null){
andCriteria.add(sectorsCriteria);
}
if (regionsCriteria != null){
andCriteria.add(regionsCriteria);
}
if (resourceTypeCriteria != null){
andCriteria.add(resourceTypeCriteria);
}
if (cropCriteria != null){
andCriteria.add(cropCriteria);
}
if (pestCriteria != null){
andCriteria.add(pestCriteria);
}
if (languageCriteria != null){
andCriteria.add(languageCriteria);
}
if (searchModel.getProject()!= null){
Criteria c = new Criteria().where("project").regex(".*"+searchModel.getProject().getName()+".*","i");
andCriteria.add(c);
}
if(!andCriteria.isEmpty()){
Criteria c = new Criteria().where("approved").is(true);
andCriteria.add(c);
current = current.andOperator(andCriteria);
query.addCriteria(current);
List<Resource> ipmWorksResult = mongoTemplate.find(query, Resource.class);
try {
List<Resource> ipmDecisionResult = searchIPMDecision(searchModel);
ipmWorksResult.addAll(ipmDecisionResult);
}catch (Exception e){
e.printStackTrace();
System.out.println("IpmDecision error!");
}
try {
List<Resource> organicKnowledgeResult = searchOrganicKnowledge(searchModel);
ipmWorksResult.addAll(organicKnowledgeResult);
}catch (Exception e){
System.out.println("organic eprints error!");
}
return ipmWorksResult;
}else{
return null;
}
}
@PostMapping("download")
public void downloadDetails(@RequestBody Resource resource, HttpServletResponse response){
try {
List<Resource> l = new ArrayList();
l.add(resource);
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(l);
InputStream inputStream = this.getClass().getResourceAsStream("/jasper/resurssheet.jasper");
Map<String, Object> params = new HashMap<String, Object>();
File logoFile = new ClassPathResource("/images/icons/logo.jpg").getFile();
Image logo = ImageIO.read(logoFile);
params.put("logo", logo);
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, params, dataSource);
inputStream.close();
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=resource.pdf;");
OutputStream out = response.getOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(out));
SimplePdfReportConfiguration configuration = new SimplePdfReportConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
}catch (Exception e){
e.printStackTrace();
}
}
}
package ipm.ipmworks.control;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import java.net.InetSocketAddress;
import java.net.Proxy;
@Configuration
public class RestConfiguration {
@Value("${ipm_decision.host.baseurl}")
private String apiHost;
@Value("${useProxy}")
private boolean useProxy;
@Value("${proxyhost}")
private String proxyhost;
@Value("${proxyport}")
private int proxyport ;
@Bean(name = "ipmDecisionRest")
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport));
if(useProxy){
requestFactory.setProxy(proxy);
}
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost));
return restTemplate;
}
@Bean(name = "organicKnowledgeRest")
public RestTemplate organicKnowledgeTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport));
if(useProxy){
requestFactory.setProxy(proxy);
}
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
}
package ipm.ipmworks.control;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class Test {
public static void main(String[] args) {
String password = "123456";
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode(password));
}
}
package ipm.ipmworks.control;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/user")
public class UserController {
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class AuthenticationRequest implements Serializable {
private String username;
private String password;
public AuthenticationRequest(String username, String password) {
this.username = username;
this.password = password;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
@Getter
@Setter
public class AuthenticationResponse implements Serializable {
private String username;
private String name;
private String token;
private List<String> roles;
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Crop")
@Getter
@Setter
public class Crop {
@Id
private String idCrop;
private String commonName;
private String latinName;
private String EPPO;
private String link;
private String img;
@Override
public String toString(){
return commonName;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
public class IpmDecisionModel {
List<String> pests = new ArrayList<String >();
List<String> crops = new ArrayList<String >();
List<String> regions = new ArrayList<String >();
List<String> languages = new ArrayList<String >();
public boolean isEmpty(){
if (!pests.isEmpty()){
return false;
}
if (!crops.isEmpty()){
return false;
}
if (!languages.isEmpty()){
return false;
}
if (!regions.isEmpty()){
return false;
}
return true;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Language")
@Getter
@Setter
@NoArgsConstructor
public class Language {
@Id
private String idLanguage;
private String name;
private String name_sr;
private String name_it;
private String name_pt;
private String name_el;
private String name_es;
private String name_nl;
private String name_da;
private String name_de;
private String name_sl;
private String name_fr;
private String name_fi;
private String name_pl;
private String code;
public Language(String name){
this.name = name;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Pest")
@Getter
@Setter
public class Pest {
@Id
private String idPest;
private String commonName;
private String latinName;
private String EPPO;
private String link;
private String img;
@Override
public String toString(){
return commonName;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Project")
@Getter
@Setter
public class Project {
@Id
private String idProject;
private String name;
private String description;
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Region")
@Getter
@Setter
public class Region {
@Id
private String idRegion;
private String name;
private String name_sr;
private String name_it;
private String name_pt;
private String name_el;
private String name_es;
private String name_nl;
private String name_da;
private String name_de;
private String name_sl;
private String name_fr;
private String name_fi;
private String name_pl;
private String code;
@Override
public String toString(){
return name;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Document(collection="Resource")
@Getter
@Setter
public class Resource {
@Id
private String idResource;
private String resourceOrigin;
private String resourceName;
private String description;
private String descriptionNative;
private ResourceType resourceType;
private String contactInstitution;
private String contactName;
private String contactEmail;
private String contactPhone;
private String contactAddress;
private List<String> links = new ArrayList<String>();
private List<Map> files = new ArrayList();
private String project;
private String projectWeb;
private String projectGrantNo;
private Language language;
private List<Sector> sectors = new ArrayList<Sector>();
private List<Region> regions = new ArrayList<Region>();
private String citation;
private String mainURL;
private User approvedBy;
private List<Pest> pests = new ArrayList<Pest>();
private List<Crop> crops = new ArrayList<Crop>();
private List<User> likes = new ArrayList<User>();
private Date creationDate;
private boolean approved;
private boolean canEdit;
private boolean external;
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="ResourceType")
@Getter
@Setter
public class ResourceType {
@Id
private String idResourceType;
private String name;
private String name_sr;
private String name_it;
private String name_pt;
private String name_el;
private String name_es;
private String name_nl;
private String name_da;
private String name_de;
private String name_sl;
private String name_fr;
private String name_fi;
private String name_pl;
private String iconName;
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
@Document(collection="Role")
@Getter
@Setter
public class Role implements GrantedAuthority {
@Id
private String idRole;
private String name;
@Override
public String getAuthority() {
return name;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
public class SearchModel {
private List<Sector> sector;
private List<Region> region;
private String pestType;
private Project project;
private List<ResourceType> resourceType;
private List<Pest> pest;
private List<Crop> crop;
private List<Language> language;
private String title;
public boolean isIPMDecision(){
int i =resourceType.stream().filter(r->r.getName().startsWith("IPM Decision")).collect(Collectors.toList()).size();
return i != 0;
}
}
package ipm.ipmworks.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="Sector")
@Getter
@Setter
public class Sector {
@Id
private String idSector;
private String name;
private String name_sr;
private String name_it;
private String name_pt;
private String name_el;
private String name_es;
private String name_nl;
private String name_da;
private String name_de;
private String name_sl;
private String name_fr;
private String name_fi;
private String name_pl;
private String sectorIcon;
@Override
public String toString(){
return name;
}
}
package ipm.ipmworks.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
import java.util.List;
@Document(collection="User")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
private String idUser;
private String username;
private String name;
private String password;
private String recoveryToken;
Collection<Role> authorities;
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Crop;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface CropRepository extends MongoRepository<Crop, String> {
List<Crop> findByEPPO(String name);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Language;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface LanguageRepository extends MongoRepository<Language, String> {
Language findByName(String name);
Language findByCode(String code);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Pest;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface PestRepository extends MongoRepository<Pest, String> {
List<Pest> findByEPPO(String epponame);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Project;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ProjectRepository extends MongoRepository<Project, String> {
Project findProjectByName(String name);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Region;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface RegionRepository extends MongoRepository<Region, String> {
public Region findByName(String name);
public Region findByCode(String code);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface ResourceRepository extends MongoRepository<Resource, String>, PagingAndSortingRepository<Resource,String> {
public List<Resource> findByApprovedIsFalse();
public Page<Resource> findByApprovedIsTrue(Pageable page);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.ResourceType;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ResourceTypeRepository extends MongoRepository<ResourceType, String> {
ResourceType findByName(String name);
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Role;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface RoleRepository extends MongoRepository<Role, String> {
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.Sector;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface SectorRepository extends MongoRepository<Sector, String> {
}
package ipm.ipmworks.repository;
import ipm.ipmworks.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.awt.dnd.DragSourceMotionListener;
import java.util.Optional;
public interface UserRepository extends MongoRepository<User, String> {
public Optional<User> findByUsername(String username);
public Optional<User> findByRecoveryToken(String token);
}
package ipm.ipmworks.security;
import ipm.ipmworks.model.AuthenticationRequest;
import ipm.ipmworks.model.AuthenticationResponse;
import ipm.ipmworks.model.User;
import ipm.ipmworks.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController()
@RequestMapping(value="/auth")
public class AuthenticationController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
IPMUserDetailsService userDetailsService;
@Autowired
UserRepository userRepository;
@Autowired
JWTUtil jwtUtil;
@Autowired
PasswordEncoder bCryptPasswordEncoder;
@PostMapping(value = "/authenticate")
public ResponseEntity<?> authenticate(@RequestBody AuthenticationRequest authenticationRequest) {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(), authenticationRequest.getPassword()));
} catch (DisabledException e) {
return new ResponseEntity<>("Disabled user", HttpStatus.BAD_REQUEST);
} catch (BadCredentialsException e) {
return new ResponseEntity<>("Incorrect username or password", HttpStatus.BAD_REQUEST);
} catch (Exception e){
e.printStackTrace();
return new ResponseEntity<>("Unknown error", HttpStatus.INTERNAL_SERVER_ERROR);
}
final IPMUserDetailsImpl userDetails = (IPMUserDetailsImpl)userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtUtil.generateToken(userDetails);
AuthenticationResponse authenticationResponse = new AuthenticationResponse();
authenticationResponse.setToken(token);
authenticationResponse.setName(userDetails.getName());
authenticationResponse.setUsername(userDetails.getUsername());
authenticationResponse.setRoles(userDetails.getRoles());
return ResponseEntity.ok(authenticationResponse);
}
void sendEmail(String receiver, String subject, String body) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(receiver);
msg.setSubject(subject);
msg.setText(body);
javaMailSender.send(msg);
}
@PostMapping(value = "/startChangingPassword")
public void startChangingPassword(@RequestBody String username) {
final IPMUserDetailsImpl userDetails = (IPMUserDetailsImpl)userDetailsService.loadUserByUsername(username);
if (userDetails != null){
final String token = jwtUtil.generateToken(userDetails).substring(0,40);
User user = userRepository.findByUsername(username).get();
user.setRecoveryToken(token);
userRepository.save(user);
String link = "http://ipmworks.net/toolbox/#/changePassword/"+token;
String body = "Someone requested change of your password. If that was not you please ignore this email. Otherwise, click on this link "+link+" (or copy this link to your browser) and follow instructions.";
StringBuilder builder = new StringBuilder();
builder.append("Dear "+userDetails.name+",\n");
builder.append("\n");
builder.append(body);
builder.append("\n");
builder.append("\n");
builder.append("Best regards\n");
builder.append("IPMWorks technical team");
sendEmail(userDetails.username,"IPMWorks password change request",builder.toString());
}
}
@GetMapping(value = "/validateToken/{token}")
public ResponseEntity<?> findUser(@PathVariable("token") String token){
Optional<User> userOpt = userRepository.findByRecoveryToken(token);
if(userOpt.isPresent()){
User user = userOpt.get();
AuthenticationResponse authenticationResponse = new AuthenticationResponse();
authenticationResponse.setUsername(user.getUsername());
return ResponseEntity.ok(authenticationResponse);
}else{
return new ResponseEntity<>("Unknown error", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping(value = "/changePassword")
public ResponseEntity<?> changePassword(@RequestBody AuthenticationRequest authenticationRequest){
Optional<User> userOpt= userRepository.findByUsername(authenticationRequest.getUsername());
if(userOpt.isPresent()) {
User user = userOpt.get();
String newPassword = bCryptPasswordEncoder.encode(authenticationRequest.getPassword());
user.setPassword(newPassword);
user.setRecoveryToken("");
userRepository.save(user);
return ResponseEntity.status(HttpStatus.OK).build();
}else{
return new ResponseEntity<>("Unknown error", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
package ipm.ipmworks.security;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private IPMUserDetailsService userDetailsService;
@Autowired
private JWTUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(request, response);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}
}
package ipm.ipmworks.security;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
}
};
}
}
package ipm.ipmworks.security;
import ipm.ipmworks.model.Role;
import ipm.ipmworks.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class IPMUserDetailsImpl implements UserDetails {
String id;
String username;
String password;
String name;
Collection<? extends GrantedAuthority> authorities;
List<String> roles;
public IPMUserDetailsImpl(User user) {
this.id = user.getIdUser();
this.username = user.getUsername();
this.password = user.getPassword();
this.authorities = user.getAuthorities();
this.name = user.getName();
this.roles = this.authorities.stream().map(a -> a.getAuthority()).collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public String getName() {
return name;
}
public String getID() {
return id;
}
public List<String> getRoles() {
return this.roles;
}
public void setName(String name) {
this.name = name;
}
}
package ipm.ipmworks.security;
import ipm.ipmworks.model.User;
import ipm.ipmworks.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class IPMUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUsername(username);
IPMUserDetailsImpl ipmUserDetails = null;
if (user.isPresent()) {
ipmUserDetails = new IPMUserDetailsImpl(user.get());
return ipmUserDetails;
} else {
throw new UsernameNotFoundException("Not found: " + username);
}
}
}
package ipm.ipmworks.security;
import io.jsonwebtoken.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JWTUtil {
private String SECRET_KEY="ipmworkssecurekey";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public String extractLibrary(String token) {
Claims claims = extractAllClaims(token);
return claims.get("library", String.class);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
//return extractExpiration(token).before(new Date());
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
IPMUserDetailsImpl ipmUserDetails = (IPMUserDetailsImpl)userDetails;
claims.put("userID", ipmUserDetails.getID());
claims.put("username", ipmUserDetails.getUsername());
claims.put("token_create_date", new Date());
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
//return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
return (username.equals(userDetails.getUsername()));
}
public Jws<Claims> parseToken(String token) {
if (token != null) {
try {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
| SignatureException | IllegalArgumentException e) {
return null;
}
}
return null;
}
}
package ipm.ipmworks.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
IPMUserDetailsService ipmUserDetailService;
@Autowired
AuthenticationTokenFilter authFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(ipmUserDetailService);
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
.antMatchers(
"/auth/**","/resource/**", "/file/get/**","/file/help/list","/codebooks/**").permitAll()
.antMatchers(
"/admin/**","/file/add/**","/file/delete/**").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
package ipm.ipmworks.service;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class FileService {
@Autowired
GridFsTemplate gridFsTemplate;
public GridFsResource getFileById(String id) throws IOException {
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
if (gridFSFile != null) {
return gridFsTemplate.getResource(gridFSFile);
}else{
return null;
}
}
public GridFsResource getResourceImage(String idResource,String type) {
Query query = new Query();
query.addCriteria(Criteria.where("metadata.idResource").is(idResource).and("metadata.type").is(type));
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (gridFSFile == null) return null;
return gridFsTemplate.getResource(gridFSFile);
}
public List<Map> getFileDescription(String type){
List fileDescList = new ArrayList();
Query query = new Query();
query.addCriteria(Criteria.where("metadata.type").is(type));
GridFSFindIterable gridFSFileList = gridFsTemplate.find(query);
MongoCursor<GridFSFile> iterator = gridFSFileList.iterator();
while (iterator.hasNext()){
GridFSFile gfs = iterator.next();
String description = (String)gfs.getMetadata().get("description");
String fileIdentifier = gfs.getObjectId().toHexString();
Map m = new HashMap();
m.put("description",description);
m.put("fileIdentifier",fileIdentifier);
fileDescList.add(m);
}
return fileDescList;
}
public boolean uploadFile(MultipartFile file,String description,String type) throws IOException {
if (file != null) {
BasicDBObject metaDataResource = new BasicDBObject();
metaDataResource.put("type", type);
metaDataResource.put("description", description);
gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType(), metaDataResource);
return true;
} else {
return false;
}
}
public boolean deleteFile(String id){
gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));
return true;
}
public boolean deleteFile(String id, String fileName){
gridFsTemplate.delete(new Query(Criteria.where("f").is(id)));
return true;
}
}
spring.data.mongodb.host=10.20.0.119
spring.data.mongodb.port=27017
spring.data.mongodb.database=ipmworks
spring.data.mongodb.authentication-database=ipmworks
spring.data.mongodb.username=ipmworks
spring.data.mongodb.password=some password
spring.mvc.view.prefix=/
server.servlet.context-path=/ipmworks
spring.data.mongodb.gridfs.bucket=ipmworks
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=ipmworks.toolbox@gmail.com
spring.mail.password=some password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
organic_knowledge.search.bykeword=https://orgprints.org/cgi/search/archive/advanced/export_orgprints_JSON.js?output=JSON&keywords_merge=ALL&keywords=
organic_knowledge.search.bytitle=https://orgprints.org/cgi/search/archive/advanced/export_orgprints_JSON.js?output=JSON&&eprintid=
ipm_decision.host.baseurl=https://ipmdecisions.nibio.no/api/sch
smartprotect.host.baseyrl=https://platform.smartprotect-h2020.eu/en/api/5XpZjIIJ0a
useProxy=true
proxyhost=proxy.uns.ac.rs
proxyport=8080
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.19.0.final using JasperReports Library version 6.19.0-646c68931cebf1a58bc65c4359d1f0ca223c5e94 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ipmworks_template" pageWidth="740" pageHeight="350" columnWidth="740" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="afb0df58-f0d7-4337-9a9e-52f1ca0fc5f3">
<property name="com.jaspersoft.studio.unit." value="pixel"/>
<property name="com.jaspersoft.studio.unit.pageHeight" value="pixel"/>
<property name="com.jaspersoft.studio.unit.pageWidth" value="pixel"/>
<property name="com.jaspersoft.studio.unit.topMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.bottomMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.leftMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/>
<property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/>
<property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/>
<parameter name="sector" class="java.awt.Image"/>
<parameter name="region" class="java.awt.Image"/>
<parameter name="projectLogo" class="java.awt.Image"/>
<parameter name="language" class="java.awt.Image"/>
<parameter name="userDefinedImg" class="java.awt.Image"/>
<parameter name="icon1" class="java.awt.Image"/>
<parameter name="icon2" class="java.awt.Image"/>
<parameter name="icon3" class="java.awt.Image"/>
<parameter name="icon4" class="java.awt.Image"/>
<parameter name="icon5" class="java.awt.Image"/>
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="350" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<image scaleImage="RetainShape" hAlign="Right" vAlign="Top" isUsingCache="true">
<reportElement stretchType="ContainerHeight" x="180" y="0" width="560" height="350" uuid="4b816add-ebec-4d9c-9ed0-1a92e93539ca">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.x" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{sector}]]></imageExpression>
</image>
<image scaleImage="RetainShape" hAlign="Left" vAlign="Middle">
<reportElement x="0" y="175" width="180" height="175" uuid="cb29db2f-249b-4d7d-a76f-a26e1be896a6">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{region}]]></imageExpression>
</image>
<image scaleImage="RetainShape" hAlign="Left" vAlign="Middle">
<reportElement x="0" y="0" width="180" height="175" uuid="63dc7d86-dc1a-4b81-8021-8ea188fe406a">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{projectLogo}]]></imageExpression>
</image>
<image hAlign="Right" vAlign="Top">
<reportElement stretchType="ContainerHeight" x="678" y="10" width="60" height="60" uuid="2d768576-cf9e-4788-918b-6dfa0b7c60f2">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.x" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{language}]]></imageExpression>
</image>
<image scaleImage="RetainShape" hAlign="Left" vAlign="Top">
<reportElement stretchType="ContainerHeight" x="180" y="0" width="280" height="247" uuid="323dcb07-55b0-4389-8638-449cf89bf353">
<property name="com.jaspersoft.studio.unit.x" value="px"/>
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{userDefinedImg}]]></imageExpression>
</image>
<image hAlign="Center" vAlign="Middle">
<reportElement stretchType="ContainerHeight" mode="Transparent" x="678" y="265" width="60" height="60" uuid="f794bca9-16da-4f48-b1ee-8c662ba4887b">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{icon1}]]></imageExpression>
</image>
<image hAlign="Center" vAlign="Middle">
<reportElement stretchType="ContainerHeight" mode="Transparent" x="613" y="265" width="60" height="60" uuid="14054cea-921a-4813-8c4b-73a3a0bf0239">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{icon2}]]></imageExpression>
</image>
<image hAlign="Center" vAlign="Middle">
<reportElement stretchType="ContainerHeight" mode="Transparent" x="548" y="265" width="60" height="60" uuid="8e30c3c2-005b-457d-a766-4ef70ad658a2">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{icon3}]]></imageExpression>
</image>
<image hAlign="Center" vAlign="Middle">
<reportElement stretchType="ContainerHeight" mode="Transparent" x="483" y="265" width="60" height="60" uuid="552fccfb-6158-4faf-8f2c-b39ffcd2f2c7">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{icon4}]]></imageExpression>
</image>
<image hAlign="Center" vAlign="Middle">
<reportElement stretchType="ContainerHeight" mode="Transparent" x="418" y="265" width="60" height="60" uuid="7d51e1cf-dc01-447b-9828-858c25ac7252">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<property name="com.jaspersoft.studio.unit.x" value="px"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<imageExpression><![CDATA[$P{icon5}]]></imageExpression>
</image>
</band>
</detail>
</jasperReport>
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.19.0.final using JasperReports Library version 6.19.0-646c68931cebf1a58bc65c4359d1f0ca223c5e94 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="resurssheet" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="f009fb91-1045-426c-9f50-72e4d3dc20b0">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<parameter name="logo" class="java.awt.Image"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="resourceName" class="java.lang.String">
<fieldDescription><![CDATA[resourceName]]></fieldDescription>
</field>
<field name="description" class="java.lang.String">
<fieldDescription><![CDATA[description]]></fieldDescription>
</field>
<field name="contactEmail" class="java.lang.String">
<fieldDescription><![CDATA[contactEmail]]></fieldDescription>
</field>
<field name="contactPhone" class="java.lang.String">
<fieldDescription><![CDATA[contactPhone]]></fieldDescription>
</field>
<field name="resourceOrigin" class="java.lang.String">
<fieldDescription><![CDATA[resourceOrigin]]></fieldDescription>
</field>
<field name="resourceType" class="java.lang.String">
<fieldDescription><![CDATA[resourceType.name]]></fieldDescription>
</field>
<field name="project" class="java.lang.String">
<fieldDescription><![CDATA[project]]></fieldDescription>
</field>
<field name="contactInstitution" class="java.lang.String">
<fieldDescription><![CDATA[contactInstitution]]></fieldDescription>
</field>
<field name="language" class="java.lang.String">
<fieldDescription><![CDATA[language.name]]></fieldDescription>
</field>
<field name="sectors" class="java.util.List">
<fieldDescription><![CDATA[sectors]]></fieldDescription>
</field>
<field name="regions" class="java.util.List">
<fieldDescription><![CDATA[regions]]></fieldDescription>
</field>
<field name="pests" class="java.util.List">
<fieldDescription><![CDATA[pests]]></fieldDescription>
</field>
<field name="crops" class="java.util.List">
<fieldDescription><![CDATA[crops]]></fieldDescription>
</field>
<pageHeader>
<band height="70" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<image>
<reportElement x="0" y="0" width="80" height="70" uuid="9528cf46-eb04-48d4-880f-8ab00bfd89e1"/>
<imageExpression><![CDATA[$P{logo}]]></imageExpression>
</image>
</band>
</pageHeader>
<detail>
<band height="350" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="0" y="79" width="120" height="30" backcolor="#DCEDD3" uuid="b5c23aa2-76c4-4d9e-abef-c0cd6cff54e4"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Project:]]></text>
</staticText>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="0" y="109" width="120" height="30" backcolor="#B6CFBB" uuid="9493b4b5-c4db-441e-8393-b78f250c3d2d"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Resource language:]]></text>
</staticText>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="0" y="139" width="120" height="31" backcolor="#DCEDD3" uuid="cedf7064-ab6f-4825-9e21-9da3fed350e9">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Resource type:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" x="0" y="309" width="550" height="30" isPrintWhenDetailOverflows="true" uuid="e5b0f44b-f901-4751-850d-657584b622a4"/>
<box topPadding="10" leftPadding="0" rightPadding="0">
<pen lineWidth="0.0"/>
<topPen lineWidth="2.0" lineColor="#17632D"/>
</box>
<textElement textAlignment="Left" verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{description}]]></textFieldExpression>
</textField>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="0" y="170" width="120" height="30" backcolor="#B6CFBB" uuid="b05f57c3-2965-4a9d-8aee-e4cd9076df52"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Resource origin:]]></text>
</staticText>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="1" y="200" width="119" height="30" backcolor="#DCEDD3" uuid="585a72c3-89a9-42aa-a9a1-faf0d4d284e6">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Organization name:]]></text>
</staticText>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="0" y="230" width="120" height="30" backcolor="#B6CFBB" uuid="a9f26bab-43f8-4518-9338-183c1fc200fc">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Contact email:]]></text>
</staticText>
<staticText>
<reportElement positionType="Float" mode="Opaque" x="1" y="260" width="119" height="30" backcolor="#DCEDD3" uuid="07f42087-fc37-487c-8fa1-9076edae07f0">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="10" isBold="true"/>
</textElement>
<text><![CDATA[Contact phone:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="79" width="430" height="30" backcolor="#DCEDD3" uuid="0f4dafdd-e477-47ed-a9ed-3b39dabd8f34"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{project}]]></textFieldExpression>
</textField>
<textField isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="109" width="430" height="30" backcolor="#B6CFBB" uuid="b3ed5ba4-4e61-4b2e-a00b-ec589cd3daff"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{language}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="139" width="430" height="31" backcolor="#DCEDD3" uuid="3b393762-eacb-4b56-aff9-2f0f13cdc52d">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{resourceType}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="170" width="430" height="30" backcolor="#B6CFBB" uuid="64274571-fb4a-4c5f-852f-a3cbd8db1310"/>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{resourceOrigin}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="200" width="430" height="30" backcolor="#DCEDD3" uuid="5beb1c45-aae8-4c2b-ba68-807c7922edeb">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{contactInstitution}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="230" width="430" height="30" backcolor="#B6CFBB" uuid="87f99cb0-5072-4156-9b2e-b18f027a714e">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{contactEmail}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" mode="Opaque" x="120" y="260" width="430" height="30" backcolor="#DCEDD3" uuid="28bdc461-a7c6-45da-aa75-427e45f6a8ff">
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{contactPhone}]]></textFieldExpression>
</textField>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement x="0" y="30" width="550" height="30" uuid="69b95620-6591-4ac0-81c4-b59b2df0ddbb"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="18"/>
</textElement>
<textFieldExpression><![CDATA[$F{resourceName}]]></textFieldExpression>
</textField>
</band>
<band height="50" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<staticText>
<reportElement positionType="Float" stretchType="ContainerHeight" mode="Opaque" x="0" y="10" width="120" height="30" backcolor="#FFFFFF" uuid="b5bb7605-7b93-4811-accd-9f52d83cd0cc"/>
<box>
<bottomPen lineWidth="0.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Sectors:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" x="120" y="10" width="430" height="30" isPrintWhenDetailOverflows="true" backcolor="#FFFFFF" uuid="a40363a2-18b8-4927-9006-99b296b40154"/>
<box>
<bottomPen lineWidth="1.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{sectors}]]></textFieldExpression>
</textField>
</band>
<band height="50" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<staticText>
<reportElement positionType="Float" stretchType="ContainerHeight" mode="Opaque" x="1" y="0" width="120" height="30" backcolor="#FFFFFF" uuid="6e337fd1-ffc8-40cf-8997-00aee48c16db"/>
<box>
<bottomPen lineWidth="0.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Pests:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" x="121" y="0" width="430" height="30" isPrintWhenDetailOverflows="true" backcolor="#FFFFFF" uuid="a4fea948-d4c4-4a63-9a6a-5abb1e803e7c"/>
<box>
<bottomPen lineWidth="1.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{pests}]]></textFieldExpression>
</textField>
</band>
<band height="50" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="px"/>
<staticText>
<reportElement positionType="Float" stretchType="ContainerHeight" mode="Opaque" x="0" y="0" width="120" height="30" backcolor="#FFFFFF" uuid="68210cd4-b602-4508-a504-6a15d83bb7f1"/>
<box>
<bottomPen lineWidth="0.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Crops:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" x="120" y="0" width="430" height="30" isPrintWhenDetailOverflows="true" backcolor="#FFFFFF" uuid="c1674741-7ba8-4fc8-ab36-7de3b25aaff0"/>
<box>
<bottomPen lineWidth="1.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{crops}]]></textFieldExpression>
</textField>
</band>
<band height="50" splitType="Stretch">
<staticText>
<reportElement positionType="Float" stretchType="ContainerHeight" mode="Opaque" x="0" y="0" width="120" height="30" backcolor="#FFFFFF" uuid="b29bfc67-aca6-4aa4-a79b-29cafb9a6a46"/>
<box>
<bottomPen lineWidth="0.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Regions:]]></text>
</staticText>
<textField textAdjust="StretchHeight" isBlankWhenNull="true">
<reportElement positionType="Float" x="120" y="0" width="430" height="30" isPrintWhenDetailOverflows="true" backcolor="#FFFFFF" uuid="1da8cf3e-8cbd-4549-a9b8-aac70cd662c6"/>
<box>
<bottomPen lineWidth="1.0"/>
</box>
<textElement verticalAlignment="Middle">
<font fontName="DejaVu Sans" size="12"/>
</textElement>
<textFieldExpression><![CDATA[$F{regions}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
package ipm.ipmworks;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class IpmworksBackendApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment