Initial commit for monitor-service.

This commit is contained in:
Konstantina Galouni 2019-11-04 09:03:49 +00:00
parent 408790a368
commit 1ff5f13223
27 changed files with 1562 additions and 0 deletions

81
pom.xml Normal file
View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-monitor-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>uoa-monitor-service</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--3d answer: https://stackoverflow.com/questions/23260057/the-forked-vm-terminated-without-saying-properly-goodbye-vm-crash-or-system-exi-->
<!--If you use openjdk there might be a problem with surfire plugin - uncomment following lines-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<!--<testFailureIgnore>true</testFailureIgnore>-->
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
<finalName>uoa-monitor-service</finalName>
</build>
</project>

View File

@ -0,0 +1,14 @@
package eu.dnetlib.uoamonitorservice;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
//import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(UoaMonitorServiceApplication.class);
}
}

View File

@ -0,0 +1,28 @@
package eu.dnetlib.uoamonitorservice;
import eu.dnetlib.uoamonitorservice.configuration.properties.GoogleConfig;
import eu.dnetlib.uoamonitorservice.configuration.properties.MailConfig;
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
import eu.dnetlib.uoamonitorservice.configuration.properties.SecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
@SpringBootApplication
@PropertySources({
@PropertySource("classpath:monitorservice.properties"),
@PropertySource(value = "file:/usr/share/tomcat7/lib/dnet-override.properties", ignoreResourceNotFound = true),
@PropertySource(value = "file:/var/lib/tomcat_dnet/8380/lib/dnet-override.properties", ignoreResourceNotFound = true)
})
@EnableConfigurationProperties({SecurityConfig.class, MailConfig.class, GoogleConfig.class, MongoConfig.class})
public class UoaMonitorServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UoaMonitorServiceApplication.class, args);
}
}

View File

@ -0,0 +1,33 @@
package eu.dnetlib.uoamonitorservice;
import eu.dnetlib.uoamonitorservice.configuration.properties.SecurityConfig;
import eu.dnetlib.uoamonitorservice.handlers.AuthorizationHandler;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class UoaMonitorServiceConfiguration extends WebMvcConfigurerAdapter {
private final Logger log = Logger.getLogger(this.getClass());
@Autowired
private SecurityConfig securityConfig;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed()))
.addPathPatterns("/**");
}
}

View File

@ -0,0 +1,46 @@
package eu.dnetlib.uoamonitorservice.configuration.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Collections;
@Configuration
@EnableMongoRepositories(basePackages = {"eu.dnetlib.uoamonitorservice.dao"})
public class MongoConnection {
@Autowired
private MongoConfig mongoConfig;
@Bean
@Primary
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(getMongoClient(), mongoConfig.getDatabase());
}
@Bean(name = "mongoTemplate")
@Primary
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(mongoDbFactory());
}
private MongoClient getMongoClient() {
if(mongoConfig.getUsername() != null && mongoConfig.getPassword() != null){
return new MongoClient(Collections.singletonList(
new ServerAddress(mongoConfig.getHost(), mongoConfig.getPort())),
Collections.singletonList(MongoCredential.createCredential(mongoConfig.getUsername(), mongoConfig.getDatabase(), mongoConfig.getPassword().toCharArray())));
} else {
return new MongoClient(Collections.singletonList(new ServerAddress(mongoConfig.getHost(), mongoConfig.getPort())));
}
}
}

View File

@ -0,0 +1,17 @@
package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("monitorservice.google")
public class GoogleConfig {
private String secret;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}

View File

@ -0,0 +1,65 @@
package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("monitorservice.mail")
public class MailConfig {
private String host;
private String port;
private String auth;
private String from;
private String username;
private String password;
public void setHost(String host) {
this.host = host;
}
public void setPort(String port) {
this.port = port;
}
public void setAuth(String auth) {
this.auth = auth;
}
public void setFrom(String from) {
this.from = from;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public String getAuth() {
return auth;
}
public String getFrom() {
return from;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,54 @@
package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("monitorservice.mongodb")
public class MongoConfig {
private String host;
private String database;
private String username;
private String password;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}

View File

@ -0,0 +1,40 @@
package eu.dnetlib.uoamonitorservice.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
@ConfigurationProperties("monitorservice.security")
public class SecurityConfig {
private String userInfoUrl;
private String originServer;
private List<String> postsAllowed = new ArrayList<>();
public void setUserInfoUrl(String userInfoUrl) {
this.userInfoUrl = userInfoUrl;
}
public void setOriginServer(String originServer) {
this.originServer = originServer;
}
public void setPostsAllowed(List<String> posts) {
this.postsAllowed = posts;
}
public String getUserInfoUrl() {
return userInfoUrl;
}
public String getOriginServer() {
return originServer;
}
public List<String> getPostsAllowed() {
return postsAllowed;
}
}

View File

@ -0,0 +1,106 @@
package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class StakeholderController {
private final Logger log = Logger.getLogger(this.getClass());
@Autowired
private StakeholderDAO stakeholderDAO;
@RequestMapping(value = "/stakeholder/all", method = RequestMethod.GET)
public List<Stakeholder> getAllStakeholders(@RequestParam(required = false) String type) {
List<Stakeholder> stakeholders;
if(type == null) {
stakeholders = stakeholderDAO.findAll();
} else {
stakeholders = stakeholderDAO.findByType(type);
}
return stakeholders;
}
@RequestMapping(value = "/stakeholder/default", method = RequestMethod.GET)
public List<Stakeholder> getAllDefaultStakeholders(@RequestParam(required = false) String type) {
List<Stakeholder> stakeholders;
if(type == null) {
stakeholders = stakeholderDAO.findByIsDefaultProfile(true);
} else {
stakeholders = stakeholderDAO.findByIsDefaultProfileAndType(true, type);
}
return stakeholders;
}
@RequestMapping(value = "/stakeholder", method = RequestMethod.GET)
public List<Stakeholder> getAllRealStakeholders(@RequestParam(required = false) String type) {
List<Stakeholder> stakeholders;
if(type == null) {
stakeholders = stakeholderDAO.findByIsDefaultProfile(false);
} else {
stakeholders = stakeholderDAO.findByIsDefaultProfileAndType(false, type);
}
log.debug(new Date());
return stakeholders;
}
@RequestMapping(value = "/stakeholder/dates", method = RequestMethod.GET)
public List<Date> getAllStakeholderDates() {
List<Stakeholder> profiles = stakeholderDAO.findAll();
List<Date> profileDates = new ArrayList<>();
int i=0;
for(Stakeholder profile : profiles) {
log.debug(profile.getCreationDate());
profileDates.add(profile.getCreationDate());
log.debug(profileDates.get(i));
i++;
}
return profileDates;
}
@RequestMapping(value = "/stakeholder/dates1", method = RequestMethod.GET)
public List<String> getAllStakeholderDates1() {
List<Stakeholder> profiles = stakeholderDAO.findAll();
List<String> profileDates = new ArrayList<>();
for(Stakeholder profile : profiles) {
log.debug(profile.getCreationDate().toString());
profileDates.add(profile.getCreationDate().toString());
}
return profileDates;
}
@RequestMapping(value = "/stakeholder/dates2", method = RequestMethod.GET)
public List<String> getAllStakeholderDates2() {
List<Stakeholder> profiles = stakeholderDAO.findAll();
List<String> profileDates = new ArrayList<>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(Stakeholder profile : profiles) {
log.debug(format.format(profile.getCreationDate()));
profileDates.add(format.format(profile.getCreationDate()));
}
return profileDates;
}
@RequestMapping(value = "/stakeholder/save", method = RequestMethod.POST)
public Stakeholder insertStakeholder(@RequestBody Stakeholder stakeholder) {
//Stakeholder stakeholder = new Stakeholder();
Stakeholder stakeholderSaved = stakeholderDAO.save(stakeholder);
return stakeholderSaved;
}
}

View File

@ -0,0 +1,45 @@
package eu.dnetlib.uoamonitorservice.controllers;
import eu.dnetlib.uoamonitorservice.dao.StakeholderDAO;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class TestController {
private final Logger log = Logger.getLogger(this.getClass());
@Autowired
private StakeholderDAO stakeholderDAO;
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
// Check ExceptionHandler
@RequestMapping(value = "/test-error1", method = RequestMethod.GET)
public Stakeholder getFirstStakeholder() {
List<Stakeholder> stakeholders;
stakeholders = stakeholderDAO.findAll();
return stakeholders.get(0);
}
@RequestMapping(value = "/test-error2", method = RequestMethod.GET)
public String getParam(@RequestParam() String param) {
return param;
}
@RequestMapping(value = "/test-error3", method = RequestMethod.GET)
public String getSubstringOfNull() {
String str = null;
return str.substring(2);
}
}

View File

@ -0,0 +1,16 @@
package eu.dnetlib.uoamonitorservice.dao;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface MongoDBStakeholderDAO extends StakeholderDAO, MongoRepository<Stakeholder, String> {
List<Stakeholder> findAll();
List<Stakeholder> findByType(String type);
List<Stakeholder> findByIsDefaultProfile(boolean isDefaultProfile);
List<Stakeholder> findByIsDefaultProfileAndType(boolean isDefaultProfile, String type);
Stakeholder save(Stakeholder stakeholder);
}

View File

@ -0,0 +1,15 @@
package eu.dnetlib.uoamonitorservice.dao;
import eu.dnetlib.uoamonitorservice.entities.Stakeholder;
import java.util.List;
public interface StakeholderDAO {
List<Stakeholder> findAll();
List<Stakeholder> findByType(String type);
List<Stakeholder> findByIsDefaultProfile(boolean isDefaultProfile);
List<Stakeholder> findByIsDefaultProfileAndType(boolean isDefaultProfile, String type);
Stakeholder save(Stakeholder stakeholder);
}

View File

@ -0,0 +1,69 @@
package eu.dnetlib.uoamonitorservice.entities;
import java.util.List;
public class Category {
private String name;
private String alias;
private String description;
private boolean isActive;
private boolean isPublic;
private boolean isOverview;
private List<SubCategory> subCategories;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public boolean isOverview() {
return isOverview;
}
public void setOverview(boolean overview) {
isOverview = overview;
}
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
}

View File

@ -0,0 +1,103 @@
package eu.dnetlib.uoamonitorservice.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.annotation.Id;
import java.util.List;
enum IndicatorType {
// Do not rename or remove existring values. This may cause problems with already stored values in DB
number, chart;
}
enum IndicatorWidth {
// Do not rename or remove existring values. This may cause problems with already stored values in DB
small, medium, large;
}
public class Indicator {
@Id
@JsonProperty("_id")
private String id;
private String name;
private String description;
private IndicatorType type; //number,chart
private IndicatorWidth width; //small,medium,large
private List<String> tags;
private boolean isActive;
private boolean isPublic;
private List<IndicatorPath> indicatorPaths;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public IndicatorType getType() {
return type;
}
public void setType(IndicatorType type) {
this.type = type;
}
public IndicatorWidth getWidth() {
return width;
}
public void setWidth(IndicatorWidth width) {
this.width = width;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean isPublic) {
this.isPublic = isPublic;
}
public List<IndicatorPath> getNdicatorPaths() {
return indicatorPaths;
}
public void setNdicatorPaths(List<IndicatorPath> ndicatorPaths) {
this.indicatorPaths = ndicatorPaths;
}
}

View File

@ -0,0 +1,47 @@
package eu.dnetlib.uoamonitorservice.entities;
import java.util.List;
enum IndicatorPathType {
// Do not rename or remove existring values. This may cause problems with already stored values in DB
table, bar, column;
}
public class IndicatorPath {
private IndicatorPathType type; // for charts is type of chart {table, bar, column, etc}
private String source; // for numbers is the service {statistics, search, metrics} for charts is the tool {stats-tool,old,metrics, fake}
private String url;
private List<String> jsonPath;
public IndicatorPathType getType() {
return type;
}
public void setType(IndicatorPathType type) {
this.type = type;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<String> getJsonPath() {
return jsonPath;
}
public void setJsonPath(List<String> jsonPath) {
this.jsonPath = jsonPath;
}
}

View File

@ -0,0 +1,139 @@
package eu.dnetlib.uoamonitorservice.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.annotation.Id;
import java.util.Date;
import java.util.List;
enum StakeholderType
{
// Do not rename or remove existring values. This may cause problems with already stored values in DB
funder, ri, project, organization;
}
public class Stakeholder {
@Id
@JsonProperty("_id")
private String id;
private StakeholderType type; // private StakeholderType type;
private String index_id;
private String index_name;
private String index_shortName;
private String alias;
private boolean isDefaultProfile;
private boolean isActive;
private boolean isPublic;
private Date creationDate;
private Date updateDate;
private List<String> managers;
private List<Topic> topics;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public StakeholderType getType() {
return type;
}
public void setType(StakeholderType type) {
this.type = type;
}
public String getIndex_id() {
return index_id;
}
public void setIndex_id(String index_id) {
this.index_id = index_id;
}
public String getIndex_name() {
return index_name;
}
public void setIndex_name(String index_name) {
this.index_name = index_name;
}
public String getIndex_shortName() {
return index_shortName;
}
public void setIndex_shortName(String index_shortName) {
this.index_shortName = index_shortName;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isDefaultProfile() {
return isDefaultProfile;
}
public void setDefaultProfile(boolean defaultProfile) {
isDefaultProfile = defaultProfile;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public List<String> getManagers() {
return managers;
}
public void setManagers(List<String> managers) {
this.managers = managers;
}
public List<Topic> getTopics() {
return topics;
}
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
}

View File

@ -0,0 +1,69 @@
package eu.dnetlib.uoamonitorservice.entities;
import java.util.List;
public class SubCategory {
private String name;
private String alias;
private String description;
private boolean isActive;
private boolean isPublic;
private List<Indicator> charts;
private List<Indicator> numbers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public List<Indicator> getCharts() {
return charts;
}
public void setCharts(List<Indicator> charts) {
this.charts = charts;
}
public List<Indicator> getNumbers() {
return numbers;
}
public void setNumbers(List<Indicator> numbers) {
this.numbers = numbers;
}
}

View File

@ -0,0 +1,60 @@
package eu.dnetlib.uoamonitorservice.entities;
import java.util.List;
public class Topic {
private String name;
private String alias;
private String description;
private boolean isActive;
private boolean isPublic;
private List<Category> categories;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
}

View File

@ -0,0 +1,68 @@
package eu.dnetlib.uoamonitorservice.handlers;
import eu.dnetlib.uoamonitorservice.handlers.utils.AuthorizationUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class AuthorizationHandler extends HandlerInterceptorAdapter {
private final Logger log = Logger.getLogger(this.getClass());
private AuthorizationUtils helper = new AuthorizationUtils();
private List<String> allowedPostRequests;
public AuthorizationHandler(String userInfoUrl, String originServer, List<String> allowedPostRequests){
helper.setOriginServer(originServer);
helper.setUserInfoUrl(userInfoUrl);
this.allowedPostRequests = allowedPostRequests;
}
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
// log.debug("request method " + request.getRemoteHost());
log.debug("properties: " + helper.getOriginServer() + " "+ helper.getUserInfoUrl());
log.debug(allowedPostRequests);
log.debug(allowedPostRequests.contains(request.getServletPath()));
log.debug(request.getServletPath());
if((request.getMethod().equals("POST") || request.getMethod().equals("DELETE")) &&
!allowedPostRequests.contains(request.getServletPath())) {
//TODO check domain & check user info
if(!this.helper.checkCookies(request) || !helper.isAuthorized(helper.getToken(request))){
response.setHeader("Access-Control-Allow-Credentials","true");
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Vary","Origin");
response.setStatus(403);
response.sendError(403, "Forbidden: You don't have permission to access. Maybe you are not registered.");
return false;
}
}
return true;
}
// @Override
// public void postHandle(
// HttpServletRequest request,
// HttpServletResponse response,
// Object handler,
// ModelAndView modelAndView) throws Exception {
// log.info("I am here - postHandle ");
// }
//
// @Override
// public void afterCompletion(
// HttpServletRequest request,
// HttpServletResponse response,
// Object handler, Exception ex) {
// log.info("I am here - afterCompletion ");
// }
}

View File

@ -0,0 +1,50 @@
package eu.dnetlib.uoamonitorservice.handlers;
import eu.dnetlib.uoamonitorservice.responses.ExceptionResponse;
import org.apache.log4j.Logger;
import org.springframework.data.crossstore.ChangeSetPersister;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
@ControllerAdvice
@RestController
public class ExceptionsHandler {
private final Logger log = Logger.getLogger(this.getClass());
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ExceptionResponse> invalidInput(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Validation Error");
response.setErrorMessage("Invalid inputs.");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.BAD_REQUEST);
log.debug("invalidInput exception");
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<ExceptionResponse> nullPointerException(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Null pointer Exception");
response.setErrorMessage("Null pointer Exception");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.BAD_REQUEST);
log.debug("nullPointerException exception");
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ChangeSetPersister.NotFoundException.class)
public ResponseEntity<ExceptionResponse> notFoundException(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("Not found Exception");
response.setErrorMessage("Not found Exception");
response.setErrors(ex.getMessage());
response.setStatus(HttpStatus.NOT_FOUND);
log.debug("notFoundException exception");
return new ResponseEntity<ExceptionResponse>(response, HttpStatus.NOT_FOUND);
}
}

View File

@ -0,0 +1,250 @@
package eu.dnetlib.uoamonitorservice.handlers.utils;
import org.apache.log4j.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import com.google.gson.Gson;
public class AuthorizationUtils {
private final Logger log = Logger.getLogger(this.getClass());
private String userInfoUrl = null;
// private String communityAPI ="";
// List<String> adminRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Portal Administrator"));
private String originServer= null;
public Boolean checkCookies(HttpServletRequest request){
Boolean valid = true;
String cookieValue = this.getCookie(request,"AccessToken");
if(cookieValue == null || cookieValue.isEmpty()){
log.info("no cookie available ");
valid = false;
}else {
String headerValue = this.getHeadersInfo(request, "x-xsrf-token");
if(headerValue == null || headerValue.isEmpty()){
log.info("no header available ");
valid = false;
}else{
if(!cookieValue.equals(headerValue)){
log.info("no proper header or cookie ");
valid = false;
}else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){
log.info("no proper origin ");
valid = false;
}
}
}
return valid;
}
public String getToken(HttpServletRequest request){
return this.getHeadersInfo(request, "x-xsrf-token");
}
private String getCookie(HttpServletRequest request, String cookieName){
if(request.getCookies() == null){
return null;
}
for(Cookie c: request.getCookies()){
// log.debug("cookie "+ c.getName()+ " "+ c.getValue());
if(c.getName().equals(cookieName)){
return c.getValue();
}
}
return null;
}
private String getHeadersInfo(HttpServletRequest request, String name) {
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
// log.debug(" key: "+ key+" value: "+ value);
if(name.equals(key)){
return value;
}
}
return null;
}
public boolean hasValidOrigin(String origin) {
if (origin != null && origin.indexOf(originServer)!=-1) {
return true;
}
log.debug("Not valid origin. Origin server is \"" + origin + "\", but expected value is \"" + originServer + "\". If the expec cted value is not right, check properties file. ");
return false;
}
public UserInfo getUserInfo(String accessToken){
String url=userInfoUrl+accessToken;
URL obj = null;
String responseStr=null;
// log.debug("User info url is "+url);
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (con.getResponseCode() != 200) {
log.debug("User info response code is: " + con.getResponseCode());
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine).append("\n");
}
in.close();
responseStr = response.toString();
}catch(Exception e){
log.error("An error occured while trying to fetch user info ",e);
return null;
}
return json2UserInfo(responseStr);
}
private UserInfo json2UserInfo(String json) {
// log.debug("Try to create userInfo class from json: "+json);
if (json == null){
return null;
}
BufferedReader br = new BufferedReader(new StringReader(json));
//convert the json string back to object
Gson gson = new Gson();
UserInfo userInfo = null;
try {
userInfo = gson.fromJson(br, UserInfo.class);
}catch(Exception e){
log.debug("Error in parsing json response. Given json is : "+json, e);
return null;
}
// log.debug("Original response.........: "+userInfo.toString());
try {
if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) {
for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) {
String role = userInfo.getEdu_person_entitlements().get(i);
// log.debug("AAI role: "+role);
role = role.split(":")[role.split(":").length-1];
role = role.replace("+"," ");
// log.debug("Adding parsed role : "+role);
userInfo.getEdu_person_entitlements().set(i,role);
}
}
}catch(Exception e){
log.debug("Error in parsing Edu_person_entitlements : ",e);
return null;
}
// log.debug("After handling roles : "+userInfo.toString());
return userInfo;
}
public boolean isAuthorized(String token) {
UserInfo userInfo = getUserInfo(token);
if (userInfo != null ) {
return true;
} else {
log.debug(" User has no Valid UserInfo");
return false;
}
}
public String getUserInfoUrl() {
return userInfoUrl;
}
public String getOriginServer() {
return originServer;
}
public void setUserInfoUrl(String userInfoUrl) {
this.userInfoUrl = userInfoUrl;
}
public void setOriginServer(String originServer) {
this.originServer = originServer;
}
// private boolean hasRole(List<String> givenRoles, List<String> authorizedRoles) {
// log.debug("It's registered with role " + givenRoles);
// for (String gRole : givenRoles) {
// if (authorizedRoles.indexOf(gRole) != -1) {
// return true;
// }
// }
// log.debug("Not Authorized. Authorized roles are" + authorizedRoles);
// return false;
//
// }
// private boolean isCommunityManager(String community, String email) {
//
// CommunityInfo communityInfo = getCommunityInfo(community);
// if(communityInfo != null && communityInfo.getManagers() != null ) {
//
// for (int i = 0; i < communityInfo.getManagers().size(); i++) {
// String manager = communityInfo.getManagers().get(i);
// log.debug("Community manager: "+manager);
//
// }
// }
// return false;
//
// }
// private CommunityInfo getCommunityInfo(String community) {
// String url = userInfoUrl + community;
// URL obj = null;
// String responseStr = null;
// log.debug("Community info url is " + url);
//
// try {
// obj = new URL(url);
// HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// log.debug("User info response code is: " + con.getResponseCode());
// if (con.getResponseCode() != 200) {
// return null;
// }
// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
// StringBuffer response = new StringBuffer();
// String inputLine;
// while ((inputLine = in.readLine()) != null) {
// response.append(inputLine).append("\n");
// }
// in.close();
// responseStr = response.toString();
// } catch (Exception e) {
// log.error("An error occured while trying to fetch user info ", e);
// return null;
// }
// return json2CommunityInfo(community);
// }
// private CommunityInfo json2CommunityInfo(String json){
//
// log.debug("Try to create CommunityInfo class from json: "+json);
// if (json == null){
// return null;
// }
//
// BufferedReader br = new BufferedReader(new StringReader(json));
// //convert the json string back to object
// Gson gson = new Gson();
// CommunityInfo communityInfo = null;
// try {
// communityInfo = gson.fromJson(br, CommunityInfo.class);
// }catch(Exception e){
// log.debug("Error in parsing json response. Given json is : "+json, e);
// return null;
// }
//
// log.debug("Original response.........: "+communityInfo.toString());
//
//
//
// return communityInfo;
// }
}

View File

@ -0,0 +1,43 @@
package eu.dnetlib.uoamonitorservice.handlers.utils;
import java.util.ArrayList;
import java.util.List;
public class UserInfo {
String name;
String email;
List<String> edu_person_entitlements = new ArrayList<String>();
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", edu_person_entitlements=" + edu_person_entitlements +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getEdu_person_entitlements() {
return edu_person_entitlements;
}
public void setEdu_person_entitlements(List<String> edu_person_entitlements) {
this.edu_person_entitlements = edu_person_entitlements;
}
}

View File

@ -0,0 +1,40 @@
package eu.dnetlib.uoamonitorservice.responses;
import org.springframework.http.HttpStatus;
public class ExceptionResponse {
private HttpStatus status;
private String errorCode;
private String errorMessage;
private String errors;
public ExceptionResponse() {}
public HttpStatus getStatus() { return status; }
public void setStatus(HttpStatus status) { this.status = status; }
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrors() {
return errors;
}
public void setErrors(String errors) {
this.errors = errors;
}
}

View File

@ -0,0 +1,19 @@
#mongodb
#beta
#spring.data.mongodb.host=beta.services.openaire.eu
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=openairemonitor
#production
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=openairemonitor
#spring.data.mongodb.authentication-database=openairemonitor
#spring.data.mongodb.username=dnet8480
#spring.data.mongodb.password=...
#dev
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=openaire_monitor

View File

@ -0,0 +1,20 @@
log4j.rootLogger = DEBUG, R
log4j.logger.eu.dnetlib = DEBUG
log4j.logger.org.springframework = DEBUG, S
log4j.additivity.org.springframework = false
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/var/log/dnet/uoa-monitor-service/uoa-monitor-service.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern= %d %p %t [%c] - %m%n
log4j.appender.S=org.apache.log4j.RollingFileAppender
log4j.appender.S.File=/var/log/dnet/uoa-monitor-service/uoa-monitor-service-spring.log
log4j.appender.S.MaxFileSize=10MB
log4j.appender.S.MaxBackupIndex=10
log4j.appender.S.layout=org.apache.log4j.PatternLayout
log4j.appender.S.layout.ConversionPattern= %d %p %t [%c] - %m%n

View File

@ -0,0 +1,25 @@
#dev
monitorservice.userInfoUrl = http://scoobydoo.di.uoa.gr:8080/dnet-openaire-users-1.0.0-SNAPSHOT/api/users/getUserInfo?accessToken=
monitorservice.originServer = .di.uoa.gr
monitorservice.host = smtp.gmail.com
monitorservice.port = 587
monitorservice.auth = true
monitorservice.from = openaire.test@gmail.com
monitorservice.username = openaire.test@gmail.com
monitorservice.password = ...
#beta
#monitorservice.userInfoUrl = https://beta.services.openaire.eu/uoa-user-management/api/users/getUserInfo?accessToken=
#monitorservice.originServer = .openaire.eu
#monitorservice.host = bwnmail.icm.edu.pl
#monitorservice.port = 25
#monitorservice.auth = false
#monitorservice.username = no-reply@openaire.eu
#monitorservice.from = no-reply@beta.openaire.eu
#monitorservice.password = ...
#production
#monitorservice.userInfoUrl = https://services.openaire.eu/uoa-user-management/api/users/getUserInfo?accessToken=
#monitorservice.originServer = .openaire.eu