diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..bf847c0 --- /dev/null +++ b/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + eu.dnetlib + uoa-monitor-service + 1.0.0-SNAPSHOT + war + + uoa-monitor-service + + + org.springframework.boot + spring-boot-starter-parent + 1.5.18.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + log4j + log4j + 1.2.17 + + + com.google.code.gson + gson + 2.8.2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + false + + + + uoa-monitor-service + + \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/ServletInitializer.java b/src/main/java/eu/dnetlib/uoamonitorservice/ServletInitializer.java new file mode 100644 index 0000000..2f0b319 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/ServletInitializer.java @@ -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); + } + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceApplication.java b/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceApplication.java new file mode 100644 index 0000000..35eb3f3 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceApplication.java @@ -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); + } + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceConfiguration.java b/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceConfiguration.java new file mode 100644 index 0000000..4818ea7 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceConfiguration.java @@ -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("/**"); + + } + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java new file mode 100644 index 0000000..3a75740 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/mongo/MongoConnection.java @@ -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()))); + } + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/GoogleConfig.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/GoogleConfig.java new file mode 100644 index 0000000..fb3d613 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/GoogleConfig.java @@ -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; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MailConfig.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MailConfig.java new file mode 100644 index 0000000..6405828 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MailConfig.java @@ -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; + } + + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MongoConfig.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MongoConfig.java new file mode 100644 index 0000000..75c283a --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/MongoConfig.java @@ -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; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/SecurityConfig.java b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/SecurityConfig.java new file mode 100644 index 0000000..ba4e033 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/SecurityConfig.java @@ -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 postsAllowed = new ArrayList<>(); + + public void setUserInfoUrl(String userInfoUrl) { + this.userInfoUrl = userInfoUrl; + } + + public void setOriginServer(String originServer) { + this.originServer = originServer; + } + + + public void setPostsAllowed(List posts) { + this.postsAllowed = posts; + } + + public String getUserInfoUrl() { + return userInfoUrl; + } + + public String getOriginServer() { + return originServer; + } + + public List getPostsAllowed() { + return postsAllowed; + } + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java new file mode 100644 index 0000000..c0bf752 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/StakeholderController.java @@ -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 getAllStakeholders(@RequestParam(required = false) String type) { + List stakeholders; + if(type == null) { + stakeholders = stakeholderDAO.findAll(); + } else { + stakeholders = stakeholderDAO.findByType(type); + } + return stakeholders; + } + + @RequestMapping(value = "/stakeholder/default", method = RequestMethod.GET) + public List getAllDefaultStakeholders(@RequestParam(required = false) String type) { + List stakeholders; + if(type == null) { + stakeholders = stakeholderDAO.findByIsDefaultProfile(true); + } else { + stakeholders = stakeholderDAO.findByIsDefaultProfileAndType(true, type); + } + return stakeholders; + } + + @RequestMapping(value = "/stakeholder", method = RequestMethod.GET) + public List getAllRealStakeholders(@RequestParam(required = false) String type) { + List 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 getAllStakeholderDates() { + List profiles = stakeholderDAO.findAll(); + List 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 getAllStakeholderDates1() { + List profiles = stakeholderDAO.findAll(); + List 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 getAllStakeholderDates2() { + List profiles = stakeholderDAO.findAll(); + List 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; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/controllers/TestController.java b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/TestController.java new file mode 100644 index 0000000..5ec4a3d --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/controllers/TestController.java @@ -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 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); + } + +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/dao/MongoDBStakeholderDAO.java b/src/main/java/eu/dnetlib/uoamonitorservice/dao/MongoDBStakeholderDAO.java new file mode 100644 index 0000000..c2ab289 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/dao/MongoDBStakeholderDAO.java @@ -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 { + List findAll(); + List findByType(String type); + + List findByIsDefaultProfile(boolean isDefaultProfile); + List findByIsDefaultProfileAndType(boolean isDefaultProfile, String type); + + Stakeholder save(Stakeholder stakeholder); +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/dao/StakeholderDAO.java b/src/main/java/eu/dnetlib/uoamonitorservice/dao/StakeholderDAO.java new file mode 100644 index 0000000..0095b5b --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/dao/StakeholderDAO.java @@ -0,0 +1,15 @@ +package eu.dnetlib.uoamonitorservice.dao; + +import eu.dnetlib.uoamonitorservice.entities.Stakeholder; + +import java.util.List; + +public interface StakeholderDAO { + List findAll(); + List findByType(String type); + + List findByIsDefaultProfile(boolean isDefaultProfile); + List findByIsDefaultProfileAndType(boolean isDefaultProfile, String type); + + Stakeholder save(Stakeholder stakeholder); +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/Category.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Category.java new file mode 100644 index 0000000..cb4fce1 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Category.java @@ -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 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 getSubCategories() { + return subCategories; + } + + public void setSubCategories(List subCategories) { + this.subCategories = subCategories; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/Indicator.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Indicator.java new file mode 100644 index 0000000..737eda2 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Indicator.java @@ -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 tags; + private boolean isActive; + private boolean isPublic; + private List 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 getTags() { + return tags; + } + + public void setTags(List 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 getNdicatorPaths() { + return indicatorPaths; + } + + public void setNdicatorPaths(List ndicatorPaths) { + this.indicatorPaths = ndicatorPaths; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/IndicatorPath.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/IndicatorPath.java new file mode 100644 index 0000000..2161998 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/IndicatorPath.java @@ -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 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 getJsonPath() { + return jsonPath; + } + + public void setJsonPath(List jsonPath) { + this.jsonPath = jsonPath; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/Stakeholder.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Stakeholder.java new file mode 100644 index 0000000..38e90b5 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Stakeholder.java @@ -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 managers; + + private List 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 getManagers() { + return managers; + } + + public void setManagers(List managers) { + this.managers = managers; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/SubCategory.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/SubCategory.java new file mode 100644 index 0000000..e07cec8 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/SubCategory.java @@ -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 charts; + private List 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 getCharts() { + return charts; + } + + public void setCharts(List charts) { + this.charts = charts; + } + + public List getNumbers() { + return numbers; + } + + public void setNumbers(List numbers) { + this.numbers = numbers; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/entities/Topic.java b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Topic.java new file mode 100644 index 0000000..3654d4a --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/entities/Topic.java @@ -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 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 getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/handlers/AuthorizationHandler.java b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/AuthorizationHandler.java new file mode 100644 index 0000000..9a2c01f --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/AuthorizationHandler.java @@ -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 allowedPostRequests; + + public AuthorizationHandler(String userInfoUrl, String originServer, List 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 "); +// } + +} \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/handlers/ExceptionsHandler.java b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/ExceptionsHandler.java new file mode 100644 index 0000000..b1dd5ca --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/ExceptionsHandler.java @@ -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 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(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(NullPointerException.class) + public ResponseEntity 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(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(ChangeSetPersister.NotFoundException.class) + public ResponseEntity 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(response, HttpStatus.NOT_FOUND); + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/AuthorizationUtils.java b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/AuthorizationUtils.java new file mode 100644 index 0000000..eb6124d --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/AuthorizationUtils.java @@ -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 adminRoles = new ArrayList(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 givenRoles, List 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; +// } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/UserInfo.java b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/UserInfo.java new file mode 100644 index 0000000..446b49e --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/UserInfo.java @@ -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 edu_person_entitlements = new ArrayList(); + + @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 getEdu_person_entitlements() { + return edu_person_entitlements; + } + + public void setEdu_person_entitlements(List edu_person_entitlements) { + this.edu_person_entitlements = edu_person_entitlements; + } +} diff --git a/src/main/java/eu/dnetlib/uoamonitorservice/responses/ExceptionResponse.java b/src/main/java/eu/dnetlib/uoamonitorservice/responses/ExceptionResponse.java new file mode 100644 index 0000000..076ba63 --- /dev/null +++ b/src/main/java/eu/dnetlib/uoamonitorservice/responses/ExceptionResponse.java @@ -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; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..736bee7 --- /dev/null +++ b/src/main/resources/application.properties @@ -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 \ No newline at end of file diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 0000000..9c99950 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -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 \ No newline at end of file diff --git a/src/main/resources/monitorservice.properties b/src/main/resources/monitorservice.properties new file mode 100644 index 0000000..8a572c8 --- /dev/null +++ b/src/main/resources/monitorservice.properties @@ -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 +