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 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
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