initial service commit

This commit is contained in:
argirok 2024-10-11 10:59:30 +03:00
commit 65342d36e0
18 changed files with 540 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
.idea/
dnet-override.properties
log4j2.xml
mvnw
mvnw.cmd
target/

46
pom.xml Normal file
View File

@ -0,0 +1,46 @@
<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>deposit-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-spring-boot-parent</artifactId>
<version>2.0.4-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>eu.dnetlib.deposit.DepositServiceApplication</mainClass>
<executable>true</executable>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,26 @@
package eu.dnetlib.deposit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@PropertySources({
@PropertySource("classpath:application.properties"),
@PropertySource("classpath:deposit.properties"),
@PropertySource(value = "classpath:dnet-override.properties", ignoreResourceNotFound = true)
})
public class DepositServiceApplication {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(DepositServiceApplication.class, args);
}
}

View File

@ -0,0 +1,27 @@
package eu.dnetlib.deposit.config;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
@Configuration
public class MongoDBConfig {
private final MongoProperties mongoProperties;
public MongoDBConfig(MongoProperties mongoProperties) {
this.mongoProperties = mongoProperties;
}
@Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoProperties.getUri());
}
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), mongoProperties.getDatabase());
}
}

View File

@ -0,0 +1,20 @@
package eu.dnetlib.deposit.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "services.deposit.db")
public class MongoProperties {
private String uri;
private String database;
private String username;
private String password;
}

View File

@ -0,0 +1,57 @@
package eu.dnetlib.deposit.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HealthController {
private final Logger log = LogManager.getLogger(this.getClass());
public static Instant dateInstant = Instant.now();
@Value("${services.deposit.zenodo.API}")
private String zenodoAPI;
@Value("${services.deposit.zenodo.clientId}")
private String clientId;
@Value("${services.deposit.zenodo.clientSecret}")
private String clientSecret;
@Value("${services.deposit.redirectURI}")
private String redirectURI;
@Value("${services.deposit.db.uri}")
private String dbUri;
@Value("${services.deposit.db.database}")
private String database;
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
log.debug("Hello from Claims service!");
return "Hello from Deposit service!";
}
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map<String, String> checkEverything() {
Map<String, String> response = new HashMap<>();
response.put("Date of deploy", HealthController.dateInstant.toString());
response.put("zenodo API",zenodoAPI);
response.put("Redirect", redirectURI);
// response.put("Date of build", buildProperties.getTime().toString());
// response.put("Version", buildProperties.getVersion());
// response.put("DB Uri", dbUri);
response.put("DB", database);
return response;
}
}

View File

@ -0,0 +1,47 @@
package eu.dnetlib.deposit.controller;
import eu.dnetlib.deposit.repository.RecordRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import eu.dnetlib.deposit.model.Record;
import java.util.Date;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/deposit/record")
public class RecordController {
@Autowired
public RecordRepository recordRepository;
private Logger logger = LogManager.getLogger(this.getClass());
@GetMapping("get")
public List<Record> getRecords(@RequestParam("pid") List<String> pid, @RequestParam("aaiId") String aaiId, @RequestParam("openaireId") String openaireId) {
logger.info("Get records " + pid);
return recordRepository.findByIdsAndAaiId(pid,openaireId, aaiId);
}
@GetMapping("user")
public List<Record> getRecords( @RequestParam("aaiId") String aaiId) {
logger.info("Get records for user" + aaiId);
return recordRepository.findByAaiId(aaiId);
}
@PostMapping("save")
public Record saveRecord(@RequestBody Record record){
System.out.println(record);
record.setDepositDate(new Date());
return recordRepository.save(record);
}
@DeleteMapping("delete")
public Boolean saveRecord(@RequestParam("id") String id){
recordRepository.deleteById(id);
return true;
}
@GetMapping("count")
public Number getRecords( ) {
Number n = recordRepository.count();
logger.info("Get total record: " + n);
return n;
}
}

View File

@ -0,0 +1,42 @@
package eu.dnetlib.deposit.controller;
import eu.dnetlib.deposit.model.User;
import eu.dnetlib.deposit.repository.UserRepository;
import eu.dnetlib.deposit.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/deposit/user")
public class UserController {
@Autowired
public UserService userService;
@Autowired
public UserRepository userRepository;
private Logger logger = LogManager.getLogger(this.getClass());
@GetMapping("/token")
public User getUser(@RequestParam("aaiId") String aaiId) {
logger.info("Get user by aaiId: " + aaiId);
// return new User();
return userService.getUser(aaiId);
}
@PostMapping("save")
public User saveUser(@RequestBody User user){
System.out.println(user);
user.setLastUpdateDate(new Date());
return userRepository.save(user);
}
@GetMapping("count")
public Number getRecords( ) {
Number n = userRepository.count();
logger.info("Get total users: " + n);
return n;
}
}

View File

@ -0,0 +1,32 @@
package eu.dnetlib.deposit.controller;
import eu.dnetlib.deposit.service.UserService;
import eu.dnetlib.deposit.service.ZenodoAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/deposit/zenodo")
public class ZenodoController {
@Autowired
private ZenodoAuthService zenodoAuthService;
@Autowired
private UserService userService;
@GetMapping("/info")
public String getClaimById(/*@Query Integer id*/) {
return "Hello!";
}
@GetMapping("getTokenByCode")
public String getTokenByCode(@RequestParam(required = true, name = "code") String code) {
System.out.println("Access by code: " + code);
return this.zenodoAuthService.getAccessTokenByCode(code);
}
@GetMapping("getTokenByRefresh")
public String getTokenByRefresh(@RequestParam(required = true, name = "token") String token) {
System.out.println("Access by refresh: " + token);
return this.zenodoAuthService.getAccessTokenByRefresh(token);
}
}

View File

@ -0,0 +1,30 @@
package eu.dnetlib.deposit.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
import java.util.List;
@Getter
@Setter
@ToString
@Document(collection = "records")
public class Record {
@Id
@JsonProperty("_id")
public String id;
String aaiId;
Object record;
List<String> filenames;
List<String> pids;
String openAIREId;
String recordId;
String ownerId;
Date depositDate;
}

View File

@ -0,0 +1,38 @@
package eu.dnetlib.deposit.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Getter
@Setter
@ToString
@Document(collection = "users")
public class User {
@Id
@JsonProperty("_id")
public String id;
public String firstName;
public String lastName;
public String email;
public String zenodoToken;
public String zenodoDuration;
public String zenodoRefresh;
public String zenodoUserId;
@LastModifiedDate
public Date lastUpdateDate;
public String code;
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}

View File

@ -0,0 +1,17 @@
package eu.dnetlib.deposit.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import eu.dnetlib.deposit.model.Record;
import java.util.List;
public interface RecordRepository extends MongoRepository<Record, String> {
List<Record> findByAaiId(String aaiId);
@Query("{ 'aaiId': ?2, $or: [ { 'pids': { $in: ?0 } }, { 'openAIREId': ?1 } ] }")
List<Record> findByIdsAndAaiId(List<String> pids, String openaireId, String aaiId);
}

View File

@ -0,0 +1,15 @@
package eu.dnetlib.deposit.repository;
import eu.dnetlib.deposit.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface UserRepository extends MongoRepository<User, String> {
Optional<User> findById(String id);
// Optional<User> findByAaiId(String id);
}

View File

@ -0,0 +1,19 @@
package eu.dnetlib.deposit.service;
import eu.dnetlib.deposit.model.User;
import eu.dnetlib.deposit.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser(String id) {
return this.userRepository.findById(id).orElse(null);
}
}

View File

@ -0,0 +1,86 @@
package eu.dnetlib.deposit.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Service
public class ZenodoAuthService {
@Value("${services.deposit.zenodo.API}")
private String zenodoAPI;
@Value("${services.deposit.zenodo.clientId}")
private String clientId;
@Value("${services.deposit.zenodo.clientSecret}")
private String clientSecret;
@Value("${services.deposit.redirectURI}")
private String redirectURI;
private final RestTemplate restTemplate;
public ZenodoAuthService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getAccessTokenByCode(String code) {
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("client_id", this.clientId);
map.add("client_secret", this.clientSecret);
map.add("redirect_uri", this.redirectURI);
map.add("grant_type", "authorization_code");
map.add("code", code);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> res = restTemplate.postForEntity(this.zenodoAPI + "oauth/token", request, String.class);
return res.getBody();
}
public String getAccessTokenByRefresh(String refresh) {
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("client_id", this.clientId);
map.add("client_secret", this.clientSecret);
map.add("redirect_uri", this.redirectURI);
map.add("grant_type", "refresh_token");
map.add("refresh_token", refresh);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> res = restTemplate.postForEntity(this.zenodoAPI + "oauth/token", request, String.class);
return res.getBody();
}
public ResponseEntity<String> getInfo(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
/*Map<String, String> params = new HashMap<>();
params.put("client_id", this.clientId);
params.put("client_secret", this.clientSecret);
params.put("redirect_uri", this.redirectURI);
params.put("grant_type", "refresh_token");
params.put("refresh_token", refresh);
StringBuilder formData = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (formData.length() != 0) formData.append('&');
formData.append(entry.getKey()).append('=').append(entry.getValue());
}*/
HttpEntity<String> request = new HttpEntity<>( headers);
String url = UriComponentsBuilder.fromHttpUrl(this.zenodoAPI + "api/deposit/depositions").toUriString();
return restTemplate.exchange(url, HttpMethod.GET, request, String.class);
}
}

View File

@ -0,0 +1,6 @@
spring.application.name=deposit-api
server.port=8182
#debug=true
logging.file.name=/var/log/dnet/deposit-api/deposit-api.log
logging.file.path=/var/log/dnet/deposit-api/
spring.main.allow-bean-definition-overriding=true

View File

@ -0,0 +1,10 @@
# sandbox
services.deposit.zenodo.API =
services.deposit.zenodo.clientId =
services.deposit.zenodo.clientSecret =
services.deposit.redirectURI = http://localhost:4300/deposit
services.deposit.db.uri= mongodb://localhost:27017/deposit
services.deposit.db.database= deposit

View File

@ -0,0 +1,15 @@
/*
package eu.dnetlib.claims;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UoaClaimsServiceApplicationTests {
@Test
void contextLoads() {
}
}
*/