1. fixed authorization in RepositoryController
2. created new methods and classes 3. made authorities mapping the same as with other openaire projects 4. refactoring
This commit is contained in:
parent
f9b12e56f5
commit
b58d9d38f0
6
pom.xml
6
pom.xml
|
@ -15,11 +15,6 @@
|
|||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>eu.dnetlib</groupId>
|
||||
<artifactId>uoa-login-core</artifactId>
|
||||
<version>[1.0.0-SNAPSHOT, 2.0.0)</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
|
@ -322,6 +317,7 @@
|
|||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<configuration>
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package eu.dnetlib.repo.manager.config;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod;
|
||||
import org.mitre.oauth2.model.RegisteredClient;
|
||||
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
|
||||
|
@ -18,9 +17,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
|
|||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
@ -46,11 +42,6 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||
@Value("${webapp.dev.front}")
|
||||
private String webAppFrontEnd;
|
||||
|
||||
private Map<String, String> userRoles = new HashMap<String, String>(){{
|
||||
put("urn:geant:openaire.eu:group:Super+Administrator#aai.openaire.eu", "ROLE_ADMIN");
|
||||
put("urn:geant:openaire.eu:group:Content+Provider+Dashboard+Administrator#aai.openaire.eu","ROLE_PROVIDE_ADMIN");
|
||||
}};
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
|
@ -58,12 +49,12 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
protected void configure(AuthenticationManagerBuilder auth) {
|
||||
auth.authenticationProvider(openIdConnectAuthenticationProvider());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) throws Exception {
|
||||
public void configure(WebSecurity web) {
|
||||
web.ignoring().antMatchers("/stats/**");
|
||||
}
|
||||
|
||||
|
@ -74,33 +65,33 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||
.authorizeRequests()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint())
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint())
|
||||
.and()
|
||||
.logout().logoutUrl("/openid_logout")
|
||||
.invalidateHttpSession(true)
|
||||
.deleteCookies("openAIRESession")
|
||||
.logoutSuccessUrl(logoutSuccessUrl)
|
||||
.logout().logoutUrl("/openid_logout")
|
||||
.invalidateHttpSession(true)
|
||||
.deleteCookies("openAIRESession")
|
||||
.logoutSuccessUrl(logoutSuccessUrl)
|
||||
.and()
|
||||
.addFilterBefore(openIdConnectAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
|
||||
.addFilterBefore(openIdConnectAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
|
||||
;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OIDCAuthenticationProvider openIdConnectAuthenticationProvider(){
|
||||
public OIDCAuthenticationProvider openIdConnectAuthenticationProvider() {
|
||||
OIDCAuthenticationProvider oidcProvider = new OIDCAuthenticationProvider();
|
||||
oidcProvider.setAuthoritiesMapper(authoritiesMapper());
|
||||
return oidcProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OpenAireProviderAuthoritiesMapper authoritiesMapper(){
|
||||
OpenAireProviderAuthoritiesMapper authoritiesMapper = new OpenAireProviderAuthoritiesMapper(userRoles);
|
||||
public OpenAIREAuthoritiesMapper authoritiesMapper() {
|
||||
OpenAIREAuthoritiesMapper authoritiesMapper = new OpenAIREAuthoritiesMapper();
|
||||
return authoritiesMapper;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public StaticServerConfigurationService staticServerConfigurationService(){
|
||||
public StaticServerConfigurationService staticServerConfigurationService() {
|
||||
StaticServerConfigurationService staticServerConfigurationService = new StaticServerConfigurationService();
|
||||
Map<String, ServerConfiguration> servers = new HashMap<>();
|
||||
servers.put(oidcIssuer, serverConfiguration());
|
||||
|
@ -109,49 +100,49 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||
}
|
||||
|
||||
@Bean
|
||||
public StaticClientConfigurationService staticClientConfigurationService(){
|
||||
public StaticClientConfigurationService staticClientConfigurationService() {
|
||||
StaticClientConfigurationService staticClientConfigurationService = new StaticClientConfigurationService();
|
||||
Map<String, RegisteredClient> clients = new HashMap<>();
|
||||
clients.put(oidcIssuer,registeredClient());
|
||||
clients.put(oidcIssuer, registeredClient());
|
||||
staticClientConfigurationService.setClients(clients);
|
||||
return staticClientConfigurationService;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RegisteredClient registeredClient(){
|
||||
public RegisteredClient registeredClient() {
|
||||
RegisteredClient registeredClient = new RegisteredClient();
|
||||
registeredClient.setClientId(oidcId);
|
||||
registeredClient.setClientSecret(oidcSecret);
|
||||
registeredClient.setScope(new HashSet<>(Arrays.asList("openid","eduperson_entitlement","profile", "email")));
|
||||
registeredClient.setScope(new HashSet<>(Arrays.asList("openid", "eduperson_entitlement", "profile", "email")));
|
||||
registeredClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
|
||||
registeredClient.setRedirectUris(new HashSet<>(Collections.singletonList(oidcDevHome)));
|
||||
return registeredClient;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public StaticAuthRequestOptionsService staticAuthRequestOptionsService(){
|
||||
public StaticAuthRequestOptionsService staticAuthRequestOptionsService() {
|
||||
return new StaticAuthRequestOptionsService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlainAuthRequestUrlBuilder plainAuthRequestUrlBuilder(){
|
||||
public PlainAuthRequestUrlBuilder plainAuthRequestUrlBuilder() {
|
||||
return new PlainAuthRequestUrlBuilder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ServerConfiguration serverConfiguration(){
|
||||
public ServerConfiguration serverConfiguration() {
|
||||
ServerConfiguration serverConfiguration = new ServerConfiguration();
|
||||
serverConfiguration.setIssuer(oidcIssuer);
|
||||
serverConfiguration.setAuthorizationEndpointUri(oidcIssuer+"authorize");
|
||||
serverConfiguration.setTokenEndpointUri(oidcIssuer+"token");
|
||||
serverConfiguration.setUserInfoUri(oidcIssuer+"userinfo");
|
||||
serverConfiguration.setJwksUri(oidcIssuer+"jwk");
|
||||
serverConfiguration.setRevocationEndpointUri(oidcIssuer+"revoke");
|
||||
serverConfiguration.setAuthorizationEndpointUri(oidcIssuer + "authorize");
|
||||
serverConfiguration.setTokenEndpointUri(oidcIssuer + "token");
|
||||
serverConfiguration.setUserInfoUri(oidcIssuer + "userinfo");
|
||||
serverConfiguration.setJwksUri(oidcIssuer + "jwk");
|
||||
serverConfiguration.setRevocationEndpointUri(oidcIssuer + "revoke");
|
||||
return serverConfiguration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LoginUrlAuthenticationEntryPoint authenticationEntryPoint(){
|
||||
public LoginUrlAuthenticationEntryPoint authenticationEntryPoint() {
|
||||
return new LoginUrlAuthenticationEntryPoint("/openid_connect_login");
|
||||
}
|
||||
|
||||
|
@ -170,14 +161,14 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
|||
}
|
||||
|
||||
@Bean
|
||||
public StaticSingleIssuerService staticSingleIssuerService(){
|
||||
public StaticSingleIssuerService staticSingleIssuerService() {
|
||||
StaticSingleIssuerService staticSingleIssuerService = new StaticSingleIssuerService();
|
||||
staticSingleIssuerService.setIssuer(oidcIssuer);
|
||||
return staticSingleIssuerService;
|
||||
}
|
||||
|
||||
@Bean(initMethod = "init")
|
||||
public FrontEndLinkURIAuthenticationSuccessHandler frontEndRedirect(){
|
||||
public FrontEndLinkURIAuthenticationSuccessHandler frontEndRedirect() {
|
||||
FrontEndLinkURIAuthenticationSuccessHandler frontEnd = new FrontEndLinkURIAuthenticationSuccessHandler();
|
||||
frontEnd.setFrontEndURI(webAppFrontEnd);
|
||||
return frontEnd;
|
||||
|
|
|
@ -2,11 +2,13 @@ package eu.dnetlib.repo.manager.config;
|
|||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.Cookie;
|
||||
|
@ -14,6 +16,10 @@ import javax.servlet.http.HttpServletRequest;
|
|||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
|
||||
|
@ -22,7 +28,7 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
|
|||
private static final Logger LOGGER = Logger
|
||||
.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class);
|
||||
|
||||
public void init(){
|
||||
public void init() {
|
||||
LOGGER.debug("Front end uri : " + frontEndURI);
|
||||
}
|
||||
|
||||
|
@ -32,8 +38,9 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
|
|||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
|
||||
|
||||
OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
|
||||
request.getSession().setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, authOIDC.getUserInfo().getEmail());
|
||||
|
||||
JsonObject userInfo = new JsonObject();
|
||||
|
||||
if (authOIDC.getUserInfo().getSub() == null)
|
||||
|
@ -42,7 +49,7 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
|
|||
userInfo.addProperty("sub", URLEncoder.encode(authOIDC.getUserInfo().getSub(), "UTF-8"));
|
||||
|
||||
|
||||
if(authOIDC.getUserInfo().getName() != null)
|
||||
if (authOIDC.getUserInfo().getName() != null)
|
||||
userInfo.addProperty("fullname", URLEncoder.encode(authOIDC.getUserInfo().getName(), "UTF-8"));
|
||||
|
||||
if (authOIDC.getUserInfo().getGivenName() == null)
|
||||
|
@ -51,34 +58,44 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
|
|||
userInfo.addProperty("firstname", URLEncoder.encode(authOIDC.getUserInfo().getGivenName(), "UTF-8") + "");
|
||||
|
||||
if (authOIDC.getUserInfo().getFamilyName() == null)
|
||||
userInfo.addProperty("lastname", "");
|
||||
userInfo.addProperty("lastname", "");
|
||||
else
|
||||
userInfo.addProperty("lastname", URLEncoder.encode(authOIDC.getUserInfo().getFamilyName(), "UTF-8") + "");
|
||||
|
||||
userInfo.addProperty("email", authOIDC.getUserInfo().getEmail() + "");
|
||||
if (authOIDC.getUserInfo().getSource().getAsJsonArray("edu_person_entitlements") == null)
|
||||
userInfo.addProperty("role", "");
|
||||
userInfo.addProperty("role", "");
|
||||
else
|
||||
userInfo.addProperty("role", URLEncoder.encode(authOIDC.getUserInfo()
|
||||
.getSource().getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
|
||||
|
||||
|
||||
Cookie openAIREUser = new Cookie("openAIREUser", new Gson().toJson(userInfo) );
|
||||
openAIREUser.setMaxAge(14400);
|
||||
openAIREUser.setPath("/");
|
||||
if(aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta"))
|
||||
openAIREUser .setDomain(".openaire.eu");
|
||||
// openAIREUser.setDomain(".athenarc.gr");
|
||||
response.addCookie(openAIREUser);
|
||||
|
||||
|
||||
Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());
|
||||
accessToken.setMaxAge(14400);
|
||||
if(aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta"))
|
||||
String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$";
|
||||
Matcher matcher = Pattern.compile(regex).matcher(authOIDC.getAccessTokenValue());
|
||||
if (matcher.find()) {
|
||||
long exp = new JsonParser().parse(new String(Base64.getDecoder().decode(matcher.group(2)))).getAsJsonObject().get("exp").getAsLong();
|
||||
accessToken.setMaxAge((int) (exp - (new Date().getTime() / 1000)));
|
||||
} else {
|
||||
accessToken.setMaxAge(3600);
|
||||
}
|
||||
if (aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta"))
|
||||
accessToken.setDomain(".openaire.eu");
|
||||
accessToken.setPath("/");
|
||||
|
||||
// accessToken.setDomain(".athenarc.gr");
|
||||
|
||||
Cookie openAIREUser = new Cookie("openAIREUser", new Gson().toJson(userInfo));
|
||||
openAIREUser.setMaxAge(accessToken.getMaxAge());
|
||||
openAIREUser.setPath("/");
|
||||
if (aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta"))
|
||||
openAIREUser.setDomain(".openaire.eu");
|
||||
|
||||
// if (frontDomain!=null) {
|
||||
// accessToken.setDomain(frontDomain);
|
||||
// // openAIREUser.setDomain(frontDomain);
|
||||
// }
|
||||
|
||||
response.addCookie(openAIREUser);
|
||||
response.addCookie(accessToken);
|
||||
response.sendRedirect(frontEndURI);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
package eu.dnetlib.repo.manager.config;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.nimbusds.jwt.JWT;
|
||||
import eu.dnetlib.repo.manager.service.security.AuthoritiesMapper;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
|
||||
import org.mitre.openid.connect.model.UserInfo;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
@ComponentScan
|
||||
@Component
|
||||
public class OpenAIREAuthoritiesMapper implements OIDCAuthoritiesMapper {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(OpenAIREAuthoritiesMapper.class);
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> mapAuthorities(JWT jwtToken, UserInfo userInfo) {
|
||||
logger.info("entitlements" + userInfo.getSource().getAsJsonArray("edu_person_entitlements").size());
|
||||
JsonArray entitlements = userInfo.getSource().getAsJsonArray("edu_person_entitlements");
|
||||
return AuthoritiesMapper.map(entitlements);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
package eu.dnetlib.repo.manager.config;
|
||||
|
||||
import com.nimbusds.jwt.JWT;
|
||||
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
|
||||
import org.mitre.openid.connect.model.UserInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class OpenAireProviderAuthoritiesMapper implements OIDCAuthoritiesMapper {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(OpenAireProviderAuthoritiesMapper.class);
|
||||
|
||||
final private static String ROLE_CLAIMS = "edu_person_entitlements";
|
||||
|
||||
private Map<String,SimpleGrantedAuthority> userRolesMap;
|
||||
|
||||
OpenAireProviderAuthoritiesMapper(Map<String,String> userRoles) {
|
||||
userRolesMap = new HashMap<>();
|
||||
userRoles.forEach((openaireRole, appRole) -> userRolesMap.put(openaireRole, new SimpleGrantedAuthority(appRole)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> mapAuthorities(JWT idToken, UserInfo userInfo) {
|
||||
Set<GrantedAuthority> out = new HashSet<>();
|
||||
out.add(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
|
||||
if(userInfo.getSource().getAsJsonArray(ROLE_CLAIMS) != null) {
|
||||
userInfo.getSource().getAsJsonArray(ROLE_CLAIMS).forEach(role -> {
|
||||
SimpleGrantedAuthority authority = userRolesMap.get(role.getAsString());
|
||||
if (authority != null) {
|
||||
logger.debug("Role mapped " + role);
|
||||
out.add(authority);
|
||||
}
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
|
@ -1,39 +1,43 @@
|
|||
package eu.dnetlib.repo.manager.controllers;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import eu.dnetlib.repo.manager.domain.dto.Role;
|
||||
import eu.dnetlib.repo.manager.service.AaiUserRoleService;
|
||||
import eu.dnetlib.repo.manager.utils.AuthorizationService;
|
||||
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
|
||||
import eu.dnetlib.repo.manager.utils.JsonUtils;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/aai-user-management")
|
||||
@RequestMapping(value = "/aai-user-management")
|
||||
@Api(description = "AAI User Management", value = "aai-user-management")
|
||||
public class AaiUserRoleController {
|
||||
|
||||
@Autowired
|
||||
private AaiUserRoleService calls;
|
||||
|
||||
@Autowired
|
||||
private JsonUtils jsonUtils;
|
||||
private final AaiRegistryService aaiRegistryService;
|
||||
|
||||
// TODO: Antonis K. This should be uncommented
|
||||
// @Autowired
|
||||
// private AuthoritiesUpdater authoritiesUpdater;
|
||||
//
|
||||
// @Autowired
|
||||
// private AuthorizationService authorizationService;
|
||||
|
||||
@Autowired
|
||||
private AuthorizationService authorizationService;
|
||||
AaiUserRoleController(AaiRegistryService aaiRegistryService) {
|
||||
this.aaiRegistryService = aaiRegistryService;
|
||||
}
|
||||
|
||||
private String sendEmail() {
|
||||
OIDCAuthenticationToken authenticationToken = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
|
||||
|
@ -43,38 +47,48 @@ public class AaiUserRoleController {
|
|||
/**
|
||||
* Create a new role with the given name and description.
|
||||
**/
|
||||
@Path("/createRole")
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/role/id/get")
|
||||
// @PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @RequestParam("id") String id) {
|
||||
int roleId = aaiRegistryService.getCouId(type, id);
|
||||
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new role with the given name and description.
|
||||
**/
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/createRole")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response createRole(@RequestBody Role role) {
|
||||
calls.createRole(role);
|
||||
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
aaiRegistryService.createRole(role);
|
||||
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
|
||||
*/
|
||||
@Path("/subscribe/{type}/{id}")
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response subscribe(@PathParam("type") String type, @PathParam("id") String id) {
|
||||
Integer coPersonId = calls.getCoPersonIdByIdentifier();
|
||||
Integer couId = calls.getCouId(type, id);
|
||||
@ApiOperation(value = "subscribe")
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or (hasRole(@Converter.convertRepoIdToRoleId(#repository.id)) or hasRole(@Converter.convertRepoIdToRoleId(returnObject.id)))")
|
||||
// TODO: Perhaps less roles here
|
||||
public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) {
|
||||
Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier();
|
||||
if (coPersonId == null) {
|
||||
coPersonId = aaiRegistryService.getCoPersonIdByEmail();
|
||||
}
|
||||
Integer couId = aaiRegistryService.getCouId(type, id);
|
||||
if (couId != null) {
|
||||
Integer role = calls.getRoleId(coPersonId, couId);
|
||||
calls.assignMemberRole(coPersonId, couId, role);
|
||||
Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
|
||||
aaiRegistryService.assignMemberRole(coPersonId, couId, role);
|
||||
// TODO: Antonis K. This should be uncommented to make a role DATASOURCE.OP... for every new repo
|
||||
// authoritiesUpdater.update(sendEmail(), old -> {
|
||||
// HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
|
||||
// authorities.add(new SimpleGrantedAuthority(authorizationService.member(type, id)));
|
||||
// return authorities;
|
||||
// });
|
||||
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -82,98 +96,107 @@ public class AaiUserRoleController {
|
|||
/**
|
||||
* Remove the member role from user with email for a type(Community, etc.) with id(ee, egi, etc.)
|
||||
*/
|
||||
@Path("/{type}/{id}/member/{email}")
|
||||
@DELETE
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@ApiOperation(value = "Remove role from member")
|
||||
@RequestMapping(method = RequestMethod.DELETE, path = "/{type}/{id}/member/{email}")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response removeMemberRole(@PathParam("type") String type, @PathParam("id") String
|
||||
id, @PathParam("email") String email) {
|
||||
Integer coPersonId = calls.getCoPersonIdByEmail(email);
|
||||
public Response removeMemberRole(@PathVariable("type") String type, @PathVariable("id") String
|
||||
id, @PathVariable("email") String email) {
|
||||
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
|
||||
if (coPersonId != null) {
|
||||
Integer couId = calls.getCouId(type, id);
|
||||
Integer couId = aaiRegistryService.getCouId(type, id);
|
||||
Integer role = null;
|
||||
if (couId != null) {
|
||||
role = calls.getRoleId(coPersonId, couId);
|
||||
role = aaiRegistryService.getRoleId(coPersonId, couId);
|
||||
}
|
||||
if (couId != null && role != null) {
|
||||
calls.removeMemberRole(coPersonId, couId, role);
|
||||
aaiRegistryService.removeMemberRole(coPersonId, couId, role);
|
||||
// TODO: Antonis K. This should be uncommented to make a role DATASOURCE.OP... for every new repo
|
||||
// authoritiesUpdater.update(email, old -> {
|
||||
// HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
|
||||
// authorities.remove(new SimpleGrantedAuthority(authorizationService.member(type, id)));
|
||||
// return authorities;
|
||||
// });
|
||||
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the users that have the role that is associated with repoId
|
||||
*/
|
||||
@Path("/repo/{id}/all-users")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response getAllUserOfARepo(@PathParam("id") String id) {
|
||||
|
||||
// find roleId by repoId
|
||||
String roleId = calls.getRoleIdByRepoId(id, "datasource");
|
||||
|
||||
// find couId by role name
|
||||
if (roleId != null) {
|
||||
Integer couId = calls.getCouId("datasource", roleId);
|
||||
if (couId != null) {
|
||||
JsonArray users = calls.getUsersByCouId(couId);
|
||||
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(users).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Subscribe to role-repo by his email
|
||||
*/
|
||||
@Path("/subscribe/repo-role/{id}/email/{email}")
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/subscribe/repo-role/{id}")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public Response subscribeRoleByEmail(@PathParam("id") String id, @PathParam("email") String email) {
|
||||
Integer coPersonId = calls.getCoPersonIdByEmail(email);
|
||||
public Response subscribeRoleByEmail(@PathVariable("id") String id, @RequestParam("email") String email) {
|
||||
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
|
||||
if (coPersonId != null) {
|
||||
String roleId = calls.getRoleIdByRepoId(id, "datasource");
|
||||
if (roleId != null) {
|
||||
Integer couId = calls.getCouId("datasource", roleId);
|
||||
if (couId != null) {
|
||||
Integer role = calls.getRoleId(coPersonId, couId);
|
||||
calls.assignMemberRole(coPersonId, couId, role);
|
||||
// TODO: Antonis K. This should be uncommented to make a role DATASOURCE.OP... for every new repo
|
||||
Integer couId = aaiRegistryService.getCouId("datasource", id);
|
||||
if (couId != null) {
|
||||
Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
|
||||
aaiRegistryService.assignMemberRole(coPersonId, couId, role);
|
||||
// TODO: Antonis K. This should be uncommented to make a role DATASOURCE.OP... for every new repo
|
||||
// authoritiesUpdater.update(sendEmail(), old -> {
|
||||
// HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
|
||||
// authorities.add(new SimpleGrantedAuthority(authorizationService.member("datasource", id)));
|
||||
// return authorities;
|
||||
// });
|
||||
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User with this email has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("User with this email has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the users that have the role that is associated with repoId
|
||||
*/
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/repo/{id}/all-users")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // TODO: Perhaps less roles here
|
||||
public ResponseEntity<List<String>> getAllUsersOfARepo(@PathVariable("id") String id) {
|
||||
|
||||
List<String> userList = new ArrayList<>();
|
||||
|
||||
// find couId by role name
|
||||
Integer couId = aaiRegistryService.getCouId("datasource", id);
|
||||
if (couId != null) {
|
||||
JsonArray users = aaiRegistryService.getUsersByCouId(couId);
|
||||
for (JsonElement jsonElement : users) {
|
||||
userList.add(jsonElement.toString());
|
||||
}
|
||||
return ResponseEntity.ok(userList);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
|
||||
public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) {
|
||||
// calls.getUserByCoId()
|
||||
return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString());
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/user/roles")
|
||||
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
|
||||
public ResponseEntity<List<String>> getRolesByEmail(@RequestParam("email") String email) {
|
||||
int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
|
||||
List<String> list = new ArrayList<>();
|
||||
for (JsonElement element : aaiRegistryService.getRoles(coPersonId)) {
|
||||
list.add(element.toString());
|
||||
}
|
||||
return ResponseEntity.ok(list);
|
||||
}
|
||||
|
||||
}
|
|
@ -5,14 +5,12 @@ import eu.dnetlib.domain.data.RepositoryInterface;
|
|||
import eu.dnetlib.repo.manager.domain.*;
|
||||
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
|
||||
import eu.dnetlib.repo.manager.service.RepositoryServiceImpl;
|
||||
import eu.dnetlib.repo.manager.utils.Converter;
|
||||
import io.swagger.annotations.Api;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.json.JSONException;
|
||||
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.prepost.PostAuthorize;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
@ -24,16 +22,14 @@ import java.util.Map;
|
|||
|
||||
@RestController
|
||||
@RequestMapping(value = "/repository")
|
||||
@Api(description = "Repository API", tags = {"repository"})
|
||||
@Api(description = "Repository API", tags = {"repository"})
|
||||
public class RepositoryController {
|
||||
|
||||
private static Logger logger = Logger.getLogger(RepositoryController.class);
|
||||
private static final Logger logger = Logger.getLogger(RepositoryController.class);
|
||||
|
||||
@Autowired
|
||||
private RepositoryServiceImpl repositoryService;
|
||||
|
||||
// @Autowired
|
||||
// private Converter converter;
|
||||
|
||||
@RequestMapping(value = "/getCountries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
|
@ -46,28 +42,38 @@ public class RepositoryController {
|
|||
@ResponseBody
|
||||
public List<RepositorySnippet> getRepositoriesByCountry(@PathVariable("country") String country,
|
||||
@PathVariable("mode") String mode,
|
||||
@RequestParam(value = "managed",required=false) Boolean managed) throws JSONException, IOException {
|
||||
@RequestParam(value = "managed", required = false) Boolean managed) throws JSONException, IOException {
|
||||
return repositoryService.getRepositoriesByCountry(country, mode, managed);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getRepositoriesOfUser/{page}/{size}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getRepositoriesOfUser/{page}/{size}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_USER')")
|
||||
public List<RepositorySnippet> getRepositoriesOfUser(
|
||||
@PathVariable("page") String page,
|
||||
@PathVariable("size") String size) throws JSONException, IOException {
|
||||
return repositoryService.getRepositoriesSnippetOfUser(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
|
||||
public List<RepositorySnippet> getRepositoriesSnippetOfUser(
|
||||
@PathVariable("page") String page,
|
||||
@PathVariable("size") String size) throws JSONException, IOException {
|
||||
return repositoryService.getRepositoriesSnippetOfUser(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/searchRegisteredRepositories/{page}/{size}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/user/repositories/{page}/{size}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_USER')")
|
||||
public List<Repository> getRepositoriesOfUser(
|
||||
@PathVariable("page") String page,
|
||||
@PathVariable("size") String size) throws JSONException, IOException {
|
||||
return repositoryService.getRepositoriesOfUser(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/searchRegisteredRepositories/{page}/{size}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
|
||||
public List<RepositorySnippet> searchRegisteredRepositories(@RequestParam(name="country", required=false) String country,
|
||||
@RequestParam(name="typology", required=false) String typology,
|
||||
@RequestParam(name="englishName", required=false) String englishName,
|
||||
@RequestParam(name="officialName", required=false) String officialName,
|
||||
public List<RepositorySnippet> searchRegisteredRepositories(@RequestParam(name = "country", required = false) String country,
|
||||
@RequestParam(name = "typology", required = false) String typology,
|
||||
@RequestParam(name = "englishName", required = false) String englishName,
|
||||
@RequestParam(name = "officialName", required = false) String officialName,
|
||||
@RequestParam("requestSortBy") String requestSortBy,
|
||||
@RequestParam("order") String order,
|
||||
@PathVariable("page") int page,
|
||||
|
@ -81,15 +87,14 @@ public class RepositoryController {
|
|||
@RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
// @PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or ((returnObject.registeredBy=='null' or returnObject.registeredBy==authentication.userInfo.email) and hasRole('ROLE_USER'))")
|
||||
@PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@Converter.convertRepoIdToRoleId(returnObject.id)))")
|
||||
public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException,ResourceNotFoundException {
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#id)")
|
||||
public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
|
||||
Repository repo = repositoryService.getRepositoryById(id);
|
||||
|
||||
if (repo != null)
|
||||
logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
|
||||
else
|
||||
logger.info("Requested repository " + id + " not found");
|
||||
if (repo != null)
|
||||
logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
|
||||
else
|
||||
logger.info("Requested repository " + id + " not found");
|
||||
return repo;
|
||||
}
|
||||
|
||||
|
@ -97,7 +102,7 @@ public class RepositoryController {
|
|||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
|
||||
return repositoryService.getRepositoryAggregations(id,0,20);
|
||||
return repositoryService.getRepositoryAggregations(id, 0, 20);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getRepositoryAggregationsByYear/{id}", method = RequestMethod.GET,
|
||||
|
@ -119,8 +124,7 @@ public class RepositoryController {
|
|||
@RequestMapping(value = "/getRepositoryInterface/{id}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
// @PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or ((@repositoryService.getRepositoryById(#id).registeredBy==authentication.userInfo.email or @repositoryService.getRepositoryById(#id).registeredBy=='null' ) and hasRole('ROLE_USER'))")
|
||||
@PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or hasRole(@Converter.convertRepoIdToRoleId(@RepositoryService.getRepositoryById(#id).id))")
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#id)")
|
||||
public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
|
||||
return repositoryService.getRepositoryInterface(id);
|
||||
}
|
||||
|
@ -128,53 +132,58 @@ public class RepositoryController {
|
|||
@RequestMapping(value = "/addRepository", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@Converter.convertRepoIdToRoleId(#repository.id)) or hasRole(@Converter.convertRepoIdToRoleId(returnObject.id)))")
|
||||
// @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@aaiUserRoleService.convertRepoIdToRoleId(#repository.id)) or hasRole(@aaiUserRoleService.convertRepoIdToRoleId(returnObject.id)))")
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or hasRole('ROLE_USER')")
|
||||
public Repository addRepository(@RequestParam("datatype") String datatype,
|
||||
@RequestBody Repository repository) throws Exception {
|
||||
|
||||
// TODO:
|
||||
// 1) add repository
|
||||
// 2) get repository id and create new role
|
||||
// 3) assign new role to authenticated user
|
||||
return repositoryService.addRepository(datatype, repository);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getDnetCountries", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public List<String> getDnetCountries(){
|
||||
public List<String> getDnetCountries() {
|
||||
return repositoryService.getDnetCountries();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getTypologies", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public List<String> getTypologies(){
|
||||
public List<String> getTypologies() {
|
||||
return repositoryService.getTypologies();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getTimezones", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public List<Timezone> getTimezones(){
|
||||
public List<Timezone> getTimezones() {
|
||||
return repositoryService.getTimezones();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@Converter.convertRepoIdToRoleId(#repository.id)) or hasRole(@Converter.convertRepoIdToRoleId(returnObject.id)))")
|
||||
public Repository updateRepository(@RequestBody Repository repository,Authentication authentication) throws Exception {
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repository.id)")
|
||||
public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
|
||||
return repositoryService.updateRepository(repository, authentication);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
|
||||
@PreAuthorize("hasRole('ROLE_USER') and #registeredBy == authentication.userInfo.email")
|
||||
public void deleteRepositoryInterface(@RequestParam("id") String id ,
|
||||
@RequestParam("registeredBy") String registeredBy){
|
||||
@PreAuthorize("@aaiUserRoleService.isMemberOf(#id)")
|
||||
public void deleteRepositoryInterface(@RequestParam("id") String id,
|
||||
@RequestParam("registeredBy") String registeredBy) {
|
||||
repositoryService.deleteRepositoryInterface(id, registeredBy);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/addInterface", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@Converter.convertRepoIdToRoleId(@RepositoryService.getRepositoryById(#repoId).id)))")
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repoId)")
|
||||
public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
|
||||
@RequestParam("repoId") String repoId,
|
||||
@RequestParam("registeredBy") String registeredBy,
|
||||
|
@ -183,56 +192,54 @@ public class RepositoryController {
|
|||
return repositoryService.addRepositoryInterface(datatype, repoId, registeredBy, comment, repositoryInterface);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_USER')")
|
||||
public List<String> getUrlsOfUserRepos(
|
||||
@PathVariable("page") String page,
|
||||
@PathVariable("size") String size) throws JSONException {
|
||||
public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
|
||||
return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getDatasourceVocabularies/{mode}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getDatasourceVocabularies/{mode}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
|
||||
return repositoryService.getDatasourceVocabularies(mode);
|
||||
return repositoryService.getDatasourceVocabularies(mode);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getCompatibilityClasses/{mode}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getCompatibilityClasses/{mode}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
|
||||
public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
|
||||
|
||||
return repositoryService.getCompatibilityClasses(mode);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getDatasourceClasses/{mode}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getDatasourceClasses/{mode}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
|
||||
return repositoryService.getDatasourceClasses(mode);
|
||||
public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
|
||||
return repositoryService.getDatasourceClasses(mode);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getMetricsInfoForRepository/{repoId}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getMetricsInfoForRepository/{repoId}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public MetricsInfo getMetricsInfoForRepository(@PathVariable("repoId") String repoId) throws RepositoryServiceException {
|
||||
public MetricsInfo getMetricsInfoForRepository(@PathVariable("repoId") String repoId) throws RepositoryServiceException {
|
||||
return repositoryService.getMetricsInfoForRepository(repoId);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/getListLatestUpdate/{mode}",method = RequestMethod.GET,
|
||||
@RequestMapping(value = "/getListLatestUpdate/{mode}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
|
||||
public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
|
||||
return repositoryService.getListLatestUpdate(mode);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or hasRole(@Converter.convertRepoIdToRoleId(@RepositoryService.getRepositoryById(#repoId).id))")
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repoId)")
|
||||
public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String repoId,
|
||||
@RequestParam("registeredBy") String registeredBy,
|
||||
@RequestParam(value = "comment", required = false) String comment,
|
||||
|
|
|
@ -1,79 +0,0 @@
|
|||
package eu.dnetlib.repo.manager.service;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import eu.dnetlib.repo.manager.domain.dto.Role;
|
||||
|
||||
public interface AaiUserRoleService {
|
||||
|
||||
/**
|
||||
* 1. Get CoPersonId by Email
|
||||
*/
|
||||
Integer getCoPersonIdByEmail(String email);
|
||||
|
||||
Integer getCoPersonIdByIdentifier();
|
||||
|
||||
|
||||
/**
|
||||
* 3. Get all OpenAIRE cous
|
||||
*/
|
||||
JsonArray getCous();
|
||||
|
||||
/**
|
||||
* 4. Get a couId by type.id
|
||||
*
|
||||
* @param type
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
Integer getCouId(String type, String id);
|
||||
|
||||
/**
|
||||
* 5. Get User non admin roles
|
||||
*/
|
||||
JsonArray getRoles(Integer coPersonId);
|
||||
|
||||
/**
|
||||
* 6. Get Role id of User base on couId.
|
||||
*/
|
||||
Integer getRoleId(Integer coPersonId, Integer couId);
|
||||
|
||||
/**
|
||||
* 16. Create a new role
|
||||
*/
|
||||
void createRole(Role role);
|
||||
|
||||
/**
|
||||
* 14. Assign a member role to a User
|
||||
*/
|
||||
void assignMemberRole(Integer coPersonId, Integer couId, Integer id);
|
||||
|
||||
/**
|
||||
* 15. Remove a member role from a User
|
||||
*/
|
||||
void removeMemberRole(Integer coPersonId, Integer couId, Integer id);
|
||||
|
||||
|
||||
/**
|
||||
* Util function to remove the datasource prefix in role Id
|
||||
* @param fullName
|
||||
* @param prefix
|
||||
* @return
|
||||
*/
|
||||
String getRepoNameWithoutType(String fullName, String prefix);
|
||||
|
||||
/**
|
||||
* Util function to transform repoId name to roleId name
|
||||
* @param repoId
|
||||
* @param prefix
|
||||
* @return
|
||||
*/
|
||||
String getRoleIdByRepoId(String repoId, String prefix);
|
||||
|
||||
/**
|
||||
* 12. Get All Users that have a specific role
|
||||
* @param couId
|
||||
* @return
|
||||
*/
|
||||
JsonArray getUsersByCouId(Integer couId);
|
||||
|
||||
}
|
|
@ -1,225 +0,0 @@
|
|||
package eu.dnetlib.repo.manager.service;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import eu.dnetlib.repo.manager.domain.dto.Role;
|
||||
import eu.dnetlib.repo.manager.utils.HttpUtils;
|
||||
import eu.dnetlib.repo.manager.utils.JsonUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class AaiUserRoleServiceImpl implements AaiUserRoleService {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(AaiUserRoleServiceImpl.class);
|
||||
|
||||
@Value("2")
|
||||
private String coid;
|
||||
|
||||
@Autowired
|
||||
public HttpUtils httpUtils;
|
||||
|
||||
@Autowired
|
||||
public JsonUtils jsonUtils;
|
||||
|
||||
private String mapType(String type) {
|
||||
if(type.equals("datasource")) {
|
||||
type = "datasource";
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getRepoNameWithoutType(String fullName, String prefix) {
|
||||
if ( fullName != null && prefix != null && fullName.startsWith(prefix) ) {
|
||||
return fullName.substring(prefix.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getRoleIdByRepoId(String repoId, String prefix) {
|
||||
String roleId = "";
|
||||
if ( repoId != null && prefix != null ) {
|
||||
roleId = prefix + "." + repoId.replaceAll(":", "$");
|
||||
return roleId;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Get CoPersonId by Email
|
||||
* @param email
|
||||
* @return
|
||||
*/
|
||||
public Integer getCoPersonIdByEmail(String email) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("coid", coid);
|
||||
params.put("mail", email);
|
||||
JsonElement response = httpUtils.get("co_people.json", params);
|
||||
if(response != null) {
|
||||
JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
|
||||
if(coPeople.size() > 0) {
|
||||
return coPeople.get(0).getAsJsonObject().get("Id").getAsInt();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Get CoPersonId by AAI identifier
|
||||
*/
|
||||
public Integer getCoPersonIdByIdentifier() {
|
||||
try {
|
||||
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
|
||||
String sub = authentication.getUserInfo().getSub();
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("coid", coid);
|
||||
params.put("search.identifier", sub);
|
||||
JsonElement response = httpUtils.get("co_people.json", params);
|
||||
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
|
||||
} catch (Exception e) {
|
||||
logger.error("Get User info: An error occurred ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Get all OpenAIRE cous
|
||||
*/
|
||||
public JsonArray getCous() {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("coid", coid);
|
||||
JsonElement response = httpUtils.get("cous.json", params);
|
||||
return (response != null) ? response.getAsJsonObject().get("Cous").getAsJsonArray() : new JsonArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Get a couId by type.id
|
||||
*
|
||||
* @param type
|
||||
* @param id It is the datasourceId (e.g openaire____$$45e3c7b69bcee6cc5fa945c9e183deb9)
|
||||
* @return
|
||||
*/
|
||||
public Integer getCouId(String type, String id) {
|
||||
JsonArray cous = getCous();
|
||||
Integer couId = null;
|
||||
for (JsonElement cou : cous) {
|
||||
if (cou.getAsJsonObject().get("Name").getAsString().equals(mapType(type) + "." + id)) {
|
||||
couId = cou.getAsJsonObject().get("Id").getAsInt();
|
||||
}
|
||||
}
|
||||
return couId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. Get User non admin roles
|
||||
* @param coPersonId
|
||||
* @return
|
||||
*/
|
||||
public JsonArray getRoles(Integer coPersonId) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("copersonid", coPersonId.toString());
|
||||
JsonElement response = httpUtils.get("co_person_roles.json", params);
|
||||
return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 6. Get Role id of User base on couId.
|
||||
* @param coPersonId
|
||||
* @param couId
|
||||
* @return
|
||||
*/
|
||||
public Integer getRoleId(Integer coPersonId, Integer couId) {
|
||||
JsonArray roles = getRoles(coPersonId);
|
||||
for (JsonElement role : roles) {
|
||||
JsonObject object = role.getAsJsonObject();
|
||||
if (object.get("CouId").getAsInt() == couId && !object.get("Status").getAsString().equals("Deleted")) {
|
||||
return object.get("Id").getAsInt();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 16. Create a new role
|
||||
* @param role
|
||||
*/
|
||||
public void createRole(Role role) {
|
||||
httpUtils.post("cous.json", jsonUtils.createNewCou(role));
|
||||
}
|
||||
|
||||
/**
|
||||
* 14. Assign a member role to a User
|
||||
* @param coPersonId The id of a person in OpenAIRE
|
||||
* @param couId The id of a role in OpenAIRE (result of getCouId)
|
||||
* @param id The id that is returned from getRoleId (role's id)
|
||||
*/
|
||||
public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) {
|
||||
if (id != null) {
|
||||
httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
|
||||
} else {
|
||||
httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 15. Remove a member role from a User
|
||||
* @param coPersonId The id of a person in OpenAIRE
|
||||
* @param couId The id of a role in OpenAIRE (result of getCouId)
|
||||
* @param id The id that is returned from getRoleId (role's id)
|
||||
*/
|
||||
public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) {
|
||||
httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 12. Get All Users that have a specific role
|
||||
*/
|
||||
public JsonArray getUsersByCouId(Integer couId) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("couid", couId.toString());
|
||||
JsonElement response = httpUtils.get("co_person_roles.json", params);
|
||||
JsonArray infos = (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
|
||||
// JsonArray users = new JsonArray();
|
||||
// infos.forEach(info -> {
|
||||
// JsonObject user = new JsonObject();
|
||||
// user.addProperty("email", info.getAsJsonObject().get("Mail").getAsString());
|
||||
// user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
|
||||
// emails.add(user);
|
||||
// });
|
||||
return infos;
|
||||
}
|
||||
|
||||
/**
|
||||
* 9. Get Groups of a Cou
|
||||
*/
|
||||
public JsonArray getCouGroups(Integer couId) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("coid", coid);
|
||||
params.put("couid", couId.toString());
|
||||
JsonElement response = httpUtils.get("co_groups.json", params);
|
||||
return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 10. Get Admin Group of a Cou
|
||||
*/
|
||||
public JsonObject getCouAdminGroup(Integer couId) {
|
||||
JsonArray groups = getCouGroups(couId);
|
||||
for (JsonElement group : groups) {
|
||||
if (group.getAsJsonObject().get("Name").getAsString().contains("admins")) {
|
||||
return group.getAsJsonObject();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -12,7 +12,8 @@ import eu.dnetlib.domain.functionality.validator.JobForValidation;
|
|||
import eu.dnetlib.repo.manager.domain.*;
|
||||
import eu.dnetlib.repo.manager.domain.dto.Role;
|
||||
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
|
||||
import eu.dnetlib.repo.manager.utils.AuthorizationService;
|
||||
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
|
||||
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
|
||||
import eu.dnetlib.repo.manager.utils.Converter;
|
||||
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
|
@ -27,7 +28,6 @@ import org.springframework.core.ParameterizedTypeReference;
|
|||
import org.springframework.http.*;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
|
@ -36,7 +36,6 @@ import org.springframework.web.util.UriComponents;
|
|||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.*;
|
||||
|
@ -80,7 +79,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
ValidatorService validatorService;
|
||||
|
||||
@Autowired
|
||||
private AaiUserRoleService calls;
|
||||
private AaiRegistryService registryCalls;
|
||||
|
||||
// TODO: Antonis K. This should be uncommented
|
||||
// @Autowired
|
||||
|
@ -95,9 +94,9 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
private Map<String, String> countriesMap = new HashMap<>();
|
||||
private Map<String, String> inverseCountriesMap = new HashMap<>();
|
||||
|
||||
private static Map<String,List<String>> dataSourceClass = new HashMap<>();
|
||||
private static Map<String, List<String>> dataSourceClass = new HashMap<>();
|
||||
|
||||
private static Map<String,String> invertedDataSourceClass = new HashMap<>();
|
||||
private static Map<String, String> invertedDataSourceClass = new HashMap<>();
|
||||
|
||||
private String sendEmail() {
|
||||
OIDCAuthenticationToken authenticationToken = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
|
||||
|
@ -105,27 +104,26 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
LOGGER.debug("Initialization method of repository api!");
|
||||
LOGGER.debug("Updated version!");
|
||||
|
||||
dataSourceClass.put("opendoar",Arrays.asList("pubsrepository::institutional","pubsrepository::thematic","pubsrepository::unknown","pubsrepository::mock"));
|
||||
dataSourceClass.put("opendoar", Arrays.asList("pubsrepository::institutional", "pubsrepository::thematic", "pubsrepository::unknown", "pubsrepository::mock"));
|
||||
dataSourceClass.put("re3data", Collections.singletonList("datarepository::unknown"));
|
||||
dataSourceClass.put("journal", Collections.singletonList("pubsrepository::journal"));
|
||||
dataSourceClass.put("aggregator",Arrays.asList("aggregator::pubsrepository::institutional","aggregator::pubsrepository::journals","aggregator::datarepository", "aggregator::pubsrepository::unknown"));
|
||||
dataSourceClass.put("aggregator", Arrays.asList("aggregator::pubsrepository::institutional", "aggregator::pubsrepository::journals", "aggregator::datarepository", "aggregator::pubsrepository::unknown"));
|
||||
|
||||
invertedDataSourceClass.put("pubsrepository::institutional","opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::thematic","opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::unknown","opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::mock","opendoar");
|
||||
invertedDataSourceClass.put("datarepository::unknown","re3data");
|
||||
invertedDataSourceClass.put("pubsrepository::journal","journal");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::institutional","aggregator");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::journals","aggregator");
|
||||
invertedDataSourceClass.put("aggregator::datarepository","aggregator");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::unknown","aggregator");
|
||||
invertedDataSourceClass.put("pubsrepository::institutional", "opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::thematic", "opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::unknown", "opendoar");
|
||||
invertedDataSourceClass.put("pubsrepository::mock", "opendoar");
|
||||
invertedDataSourceClass.put("datarepository::unknown", "re3data");
|
||||
invertedDataSourceClass.put("pubsrepository::journal", "journal");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::institutional", "aggregator");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::journals", "aggregator");
|
||||
invertedDataSourceClass.put("aggregator::datarepository", "aggregator");
|
||||
invertedDataSourceClass.put("aggregator::pubsrepository::unknown", "aggregator");
|
||||
|
||||
|
||||
httpHeaders = new HttpHeaders();
|
||||
|
@ -174,32 +172,32 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
LOGGER.debug("Country code equals : " + country);
|
||||
LOGGER.debug("Filter mode equals : " + filterKey);
|
||||
|
||||
UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
|
||||
UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setCountry(country);
|
||||
requestFilter.setCollectedfrom(filterKey);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
while (jsonArray.length() > 0 ) {
|
||||
while (jsonArray.length() > 0) {
|
||||
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
|
||||
mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
||||
page += 1;
|
||||
uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
|
||||
rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
|
||||
rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
}
|
||||
return resultSet;
|
||||
}catch (Exception e){
|
||||
LOGGER.debug("Exception on getRepositoriesByCountry" , e);
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on getRepositoriesByCountry", e);
|
||||
// emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public List<RepositorySnippet> searchRegisteredRepositories(String country, String typology, String englishName,
|
||||
String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
|
||||
String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
|
||||
|
||||
LOGGER.debug("Searching registered repositories");
|
||||
|
||||
|
@ -215,14 +213,14 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
requestFilter.setEnglishname(englishName);
|
||||
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
|
||||
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
||||
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
||||
|
||||
return resultSet;
|
||||
}catch (Exception e){
|
||||
LOGGER.error("Error searching registered datasources" , e);
|
||||
return resultSet;
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Error searching registered datasources", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
@ -230,9 +228,9 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
private Repository updateRepositoryInfo(Repository r) throws JSONException {
|
||||
|
||||
/*
|
||||
* from datasource class
|
||||
* we get the datasource type form the inverted map
|
||||
* */
|
||||
* from datasource class
|
||||
* we get the datasource type form the inverted map
|
||||
* */
|
||||
r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
|
||||
r.setInterfaces(this.getRepositoryInterface(r.getId()));
|
||||
r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
|
||||
|
@ -257,68 +255,60 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
String page,
|
||||
String size) throws JSONException {
|
||||
|
||||
LOGGER.debug("Retreiving repositories of user : " + userEmail );
|
||||
UriComponents uriComponents = searchDatasource(page,size);
|
||||
LOGGER.debug("Retreiving repositories of user : " + userEmail);
|
||||
UriComponents uriComponents = searchDatasource(page, size);
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setRegisteredby(userEmail);
|
||||
// requestFilter.setRegisteredby(userEmail);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
List<String> repoIds = getRepoIdsFromUserRoles(userEmail);
|
||||
List<Repository> repos = new ArrayList<>();
|
||||
|
||||
List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
|
||||
for (Repository r : repos)
|
||||
r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
|
||||
return repos;
|
||||
}catch (Exception e){
|
||||
LOGGER.debug("Exception on getRepositoriesOfUser" , e);
|
||||
try {
|
||||
for (String repoId : repoIds) {
|
||||
requestFilter.setId(repoId);
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
|
||||
repos.addAll(Converter.jsonToRepositoryList(new JSONObject(rs)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on getRepositoriesOfUser", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
for (Repository r : repos)
|
||||
r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
|
||||
return repos;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RepositorySnippet> getRepositoriesSnippetOfUser(String userEmail, String page, String size) throws IOException, JSONException {
|
||||
|
||||
// TODO: Antonis K. - Change the below content. get repos of User by his roles
|
||||
// TODO: Step 1 - Get all roles (cous) of the user
|
||||
// TODO: From the result replace $$ with ::
|
||||
// TODO: Step 2 - For each role call getRepositoryById to get the repositoryId
|
||||
// TODO: Step 3 - For each repo from the previous step call findByRepositoryId piwik_site to get the full info of repo
|
||||
Integer coPersonId = calls.getCoPersonIdByEmail(userEmail);
|
||||
JsonArray roles;
|
||||
ArrayList<String> rolesId = new ArrayList<>();
|
||||
if (coPersonId != null ) {
|
||||
roles = calls.getRoles(coPersonId);
|
||||
for (JsonElement role : roles) {
|
||||
JsonObject object = role.getAsJsonObject();
|
||||
String roleStr = object.get("Name").getAsString().replaceAll(":", "$");
|
||||
String repoBareId = calls.getRepoNameWithoutType(roleStr, "datasource.");
|
||||
rolesId.add(roleStr);
|
||||
}
|
||||
}
|
||||
List<String> repoIds = getRepoIdsFromUserRoles(userEmail);
|
||||
|
||||
List<RepositorySnippet> resultSet = new ArrayList<>();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
// here page should be 0
|
||||
UriComponents uriComponents = searchSnipperDatasource(page,size);
|
||||
UriComponents uriComponents = searchSnipperDatasource(page, size);
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
|
||||
for ( int i = 0; i < rolesId.size(); i++ ) {
|
||||
if ( rolesId.get(i) != "ROLE_ADMIN" && rolesId.get(i) != "ROLE_PROVIDE_ADMIN" && rolesId.get(i) != "ROLE_USER" )
|
||||
requestFilter.setId(rolesId.get(i));
|
||||
try {
|
||||
for (String repoId : repoIds) {
|
||||
requestFilter.setId(repoId);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
|
||||
mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
|
||||
}catch (Exception e){
|
||||
LOGGER.debug("Exception on getRepositoriesByCountry" , e);
|
||||
throw e;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on getRepositoriesSnippetOfUser", e);
|
||||
throw e;
|
||||
}
|
||||
System.out.println("resultSet:" + resultSet);
|
||||
|
||||
LOGGER.debug("resultSet:" + resultSet);
|
||||
resultSet.parallelStream().forEach(repositorySnippet -> {
|
||||
repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId()));
|
||||
});
|
||||
|
@ -326,25 +316,25 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public RepositorySnippet getRepositorySnippetById(String id) throws JSONException,ResourceNotFoundException {
|
||||
public RepositorySnippet getRepositorySnippetById(String id) throws JSONException, ResourceNotFoundException {
|
||||
|
||||
LOGGER.debug("Retreiving repositories with id : " + id );
|
||||
LOGGER.debug("Retreiving repositories with id : " + id);
|
||||
RepositorySnippet repo = null;
|
||||
UriComponents uriComponents = searchSnipperDatasource("0","100");
|
||||
UriComponents uriComponents = searchSnipperDatasource("0", "100");
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setId(id);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
|
||||
if(jsonArray.length() == 0)
|
||||
if (jsonArray.length() == 0)
|
||||
throw new ResourceNotFoundException();
|
||||
|
||||
repo = Converter.jsonToRepositorySnippetObject(jsonArray.getJSONObject(0));
|
||||
return repo;
|
||||
}catch (JSONException e){
|
||||
LOGGER.debug("Exception on getRepositoryById" , e);
|
||||
} catch (JSONException e) {
|
||||
LOGGER.debug("Exception on getRepositoryById", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -352,25 +342,25 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Repository getRepositoryById(String id) throws JSONException,ResourceNotFoundException {
|
||||
public Repository getRepositoryById(String id) throws JSONException, ResourceNotFoundException {
|
||||
|
||||
LOGGER.debug("Retreiving repositories with id : " + id );
|
||||
LOGGER.debug("Retreiving repositories with id : " + id);
|
||||
Repository repo = null;
|
||||
UriComponents uriComponents = searchDatasource("0","100");
|
||||
UriComponents uriComponents = searchDatasource("0", "100");
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setId(id);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
|
||||
|
||||
if(jsonArray.length() == 0)
|
||||
if (jsonArray.length() == 0)
|
||||
throw new ResourceNotFoundException();
|
||||
|
||||
repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
|
||||
return updateRepositoryInfo(repo);
|
||||
}catch (JSONException e){
|
||||
LOGGER.debug("Exception on getRepositoryById" , e);
|
||||
} catch (JSONException e) {
|
||||
LOGGER.debug("Exception on getRepositoryById", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -381,8 +371,8 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
@Override
|
||||
public List<AggregationDetails> getRepositoryAggregations(String id, int from, int size) throws JSONException {
|
||||
|
||||
LOGGER.debug("Retreiving aggregations for repository with id : " + id );
|
||||
UriComponents uriComponents = searchDatasource(from+"",size+"");
|
||||
LOGGER.debug("Retreiving aggregations for repository with id : " + id);
|
||||
UriComponents uriComponents = searchDatasource(from + "", size + "");
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setId(id);
|
||||
|
||||
|
@ -390,26 +380,26 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
try {
|
||||
long start = System.currentTimeMillis();
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
long end = System.currentTimeMillis();
|
||||
|
||||
System.out.println("Aggregations request through rest template took " + (end-start)+"ms");
|
||||
System.out.println("Aggregations request through rest template took " + (end - start) + "ms");
|
||||
JSONObject repository = new JSONObject(rs);
|
||||
|
||||
if(repository.getJSONArray("datasourceInfo").length() == 0)
|
||||
if (repository.getJSONArray("datasourceInfo").length() == 0)
|
||||
return aggregationHistory;
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
||||
end = System.currentTimeMillis();
|
||||
|
||||
System.out.println("Getting aggregations history from json " + (end-start)+"ms");
|
||||
return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
|
||||
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
||||
.limit(size)
|
||||
.collect(Collectors.toList());
|
||||
System.out.println("Getting aggregations history from json " + (end - start) + "ms");
|
||||
return aggregationHistory.size() == 0 ? aggregationHistory : aggregationHistory.stream()
|
||||
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
||||
.limit(size)
|
||||
.collect(Collectors.toList());
|
||||
} catch (JSONException e) {
|
||||
LOGGER.debug("Exception on getRepositoryAggregations" , e);
|
||||
LOGGER.debug("Exception on getRepositoryAggregations", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -418,38 +408,38 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
@Override
|
||||
public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException {
|
||||
LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
|
||||
UriComponents uriComponents = searchDatasource("0","100");
|
||||
LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id);
|
||||
UriComponents uriComponents = searchDatasource("0", "100");
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setId(id);
|
||||
|
||||
List<AggregationDetails> aggregationHistory = new ArrayList<>();
|
||||
Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
JSONObject repository = new JSONObject(rs);
|
||||
|
||||
if(repository.getJSONArray("datasourceInfo").length() == 0)
|
||||
if (repository.getJSONArray("datasourceInfo").length() == 0)
|
||||
return aggregationByYear;
|
||||
|
||||
aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
|
||||
return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
|
||||
return aggregationHistory.size() == 0 ? aggregationByYear : createYearMap(aggregationHistory);
|
||||
|
||||
} catch (JSONException e) {
|
||||
LOGGER.debug("Exception on getRepositoryAggregations" , e);
|
||||
LOGGER.debug("Exception on getRepositoryAggregations", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
|
||||
private Map<String, List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
|
||||
Map<String, List<AggregationDetails>> aggregationByYear;
|
||||
aggregationHistory = aggregationHistory.stream()
|
||||
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
||||
.collect(Collectors.toList());
|
||||
.sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return aggregationHistory.stream()
|
||||
.collect(Collectors.groupingBy(AggregationDetails::getYear));
|
||||
return aggregationHistory.stream()
|
||||
.collect(Collectors.groupingBy(AggregationDetails::getYear));
|
||||
}
|
||||
|
||||
|
||||
|
@ -458,19 +448,19 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
String page,
|
||||
String size) throws JSONException {
|
||||
|
||||
LOGGER.debug("Retreiving repositories with official name : " + name );
|
||||
UriComponents uriComponents = searchDatasource("0","100");
|
||||
LOGGER.debug("Retreiving repositories with official name : " + name);
|
||||
UriComponents uriComponents = searchDatasource("0", "100");
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setOfficialname(name);
|
||||
|
||||
try{
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
|
||||
try {
|
||||
String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
|
||||
List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
|
||||
for (Repository r : repos)
|
||||
updateRepositoryInfo(r);
|
||||
return repos;
|
||||
}catch (Exception e){
|
||||
LOGGER.debug("Exception on getRepositoriesByName" , e);
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on getRepositoriesByName", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -485,11 +475,11 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
.path("/{id}")
|
||||
.build().expand(id).encode();
|
||||
|
||||
try{
|
||||
try {
|
||||
String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
|
||||
return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
|
||||
}catch (Exception e ){
|
||||
LOGGER.debug("Exception on getRepositoryInterface" , e);
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on getRepositoryInterface", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -510,11 +500,11 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
repository.setId("openaire____::issn" + repository.getIssn());
|
||||
repository.setNamespacePrefix("issn" + repository.getIssn());
|
||||
this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
|
||||
}else if (datatype.equals("aggregator")) {
|
||||
} else if (datatype.equals("aggregator")) {
|
||||
repository.setId("openaire____::" + com.unboundid.util.Base64.encode(repository.getOfficialName()));
|
||||
repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0,12));
|
||||
repository.setNamespacePrefix(DigestUtils.md5Hex(repository.getOfficialName()).substring(0, 12));
|
||||
this.storeRepository(repository, SecurityContextHolder.getContext().getAuthentication());
|
||||
}else {
|
||||
} else {
|
||||
this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
|
@ -524,19 +514,19 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
String newRoleDescr = repository.getId().replaceAll(":", "\\$");
|
||||
Role newRole = new Role(newRoleName, newRoleDescr);
|
||||
try {
|
||||
calls.createRole(newRole);
|
||||
registryCalls.createRole(newRole);
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on create role during add repository" , e);
|
||||
LOGGER.debug("Exception on create role during add repository", e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Assign new role to the user that created it
|
||||
Integer coPersonId = calls.getCoPersonIdByIdentifier();
|
||||
Integer couId = calls.getCouId("datasource", newRoleName);
|
||||
Integer coPersonId = registryCalls.getCoPersonIdByIdentifier();
|
||||
Integer couId = registryCalls.getCouId("datasource", newRoleName);
|
||||
if (couId != null) {
|
||||
Integer role = calls.getRoleId(coPersonId, couId);
|
||||
try{
|
||||
calls.assignMemberRole(coPersonId, couId, role);
|
||||
Integer role = registryCalls.getRoleId(coPersonId, couId);
|
||||
try {
|
||||
registryCalls.assignMemberRole(coPersonId, couId, role);
|
||||
// TODO: Antonis K. This should be uncommented to make a role DATASOURCE.OP... for every new repo
|
||||
// authoritiesUpdater.update(sendEmail(), old -> {
|
||||
// HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
|
||||
|
@ -544,7 +534,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
// return authorities;
|
||||
// });
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on assign role to user during add repository" , e);
|
||||
LOGGER.debug("Exception on assign role to user during add repository", e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
|
@ -566,7 +556,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
LOGGER.debug("JSON to add(update) -> " + json_repository);
|
||||
|
||||
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class);
|
||||
|
||||
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
||||
// emailUtils.sendUserRegistrationEmail(repository, authentication);
|
||||
|
@ -576,7 +566,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
return repository;
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on updateRepository" , e);
|
||||
LOGGER.debug("Exception on updateRepository", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -585,7 +575,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Repository updateRepository(Repository repository,Authentication authentication) throws Exception {
|
||||
public Repository updateRepository(Repository repository, Authentication authentication) throws Exception {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/update/")
|
||||
.build()
|
||||
|
@ -597,7 +587,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
LOGGER.debug("JSON to update -> " + json_repository);
|
||||
|
||||
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity
|
||||
, ResponseEntity.class);
|
||||
|
||||
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
||||
|
@ -608,7 +598,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
return repository;
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on updateRepository" , e);
|
||||
LOGGER.debug("Exception on updateRepository", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -627,10 +617,10 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
.build()
|
||||
.encode();
|
||||
String json_repository = Converter.repositoryObjectToJson(repository);
|
||||
HttpEntity<String> httpEntity = new HttpEntity <String> (json_repository,httpHeaders);
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, httpEntity, ResponseEntity.class);
|
||||
HttpEntity<String> httpEntity = new HttpEntity<String>(json_repository, httpHeaders);
|
||||
ResponseEntity responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, httpEntity, ResponseEntity.class);
|
||||
|
||||
if(responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
||||
if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
|
||||
emailUtils.sendUserRegistrationEmail(repository, authentication);
|
||||
emailUtils.sendAdminRegistrationEmail(repository, authentication);
|
||||
} else {
|
||||
|
@ -639,8 +629,8 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void deleteRepositoryInterface(String id ,
|
||||
String registeredBy){
|
||||
public void deleteRepositoryInterface(String id,
|
||||
String registeredBy) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/api/")
|
||||
.path("/{id}")
|
||||
|
@ -656,17 +646,17 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
String comment, RepositoryInterface repositoryInterface) throws Exception {
|
||||
try {
|
||||
Repository e = this.getRepositoryById(repoId);
|
||||
repositoryInterface = createRepositoryInterface(e,repositoryInterface,datatype);
|
||||
String json_interface = Converter.repositoryInterfaceObjectToJson(e,repositoryInterface);
|
||||
repositoryInterface = createRepositoryInterface(e, repositoryInterface, datatype);
|
||||
String json_interface = Converter.repositoryInterfaceObjectToJson(e, repositoryInterface);
|
||||
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/api/add/")
|
||||
.build()
|
||||
.encode();
|
||||
|
||||
HttpEntity<String> httpEntity = new HttpEntity <> (json_interface,httpHeaders);
|
||||
HttpEntity<String> httpEntity = new HttpEntity<>(json_interface, httpHeaders);
|
||||
|
||||
restTemplate.postForObject(uriComponents.toUri(),httpEntity, String.class);
|
||||
restTemplate.postForObject(uriComponents.toUri(), httpEntity, String.class);
|
||||
|
||||
emailUtils.sendAdminRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
||||
emailUtils.sendUserRegisterInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
||||
|
@ -676,7 +666,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
return repositoryInterface;
|
||||
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception on addRepositoryInterface" , e);
|
||||
LOGGER.error("Exception on addRepositoryInterface", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -687,14 +677,14 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
String registeredBy,
|
||||
String comment, RepositoryInterface repositoryInterface) throws Exception {
|
||||
|
||||
this.updateBaseUrl(repoId,repositoryInterface.getId(),repositoryInterface.getBaseUrl());
|
||||
this.updateCompliance(repoId,repositoryInterface.getId(),repositoryInterface.getCompliance());
|
||||
this.updateValidationSet(repoId,repositoryInterface.getId(),repositoryInterface.getAccessSet());
|
||||
this.updateBaseUrl(repoId, repositoryInterface.getId(), repositoryInterface.getBaseUrl());
|
||||
this.updateCompliance(repoId, repositoryInterface.getId(), repositoryInterface.getCompliance());
|
||||
this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet());
|
||||
|
||||
Repository e = this.getRepositoryById(repoId);
|
||||
emailUtils.sendAdminUpdateInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
||||
emailUtils.sendUserUpdateInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
|
||||
submitInterfaceValidation(getRepositoryById(repoId),registeredBy,repositoryInterface,true);
|
||||
submitInterfaceValidation(getRepositoryById(repoId), registeredBy, repositoryInterface, true);
|
||||
|
||||
return repositoryInterface;
|
||||
}
|
||||
|
@ -766,25 +756,25 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
@Override
|
||||
public List<Timezone> getTimezones() {
|
||||
List<String> timezones = Converter.readFile("timezones.txt");
|
||||
List<String> timezones = Converter.readFile("timezones.txt");
|
||||
return Converter.toTimezones(timezones);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getUrlsOfUserRepos(String userEmail,
|
||||
String page,
|
||||
String size){
|
||||
String size) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/api/baseurl/")
|
||||
.path("/{page}/{size}")
|
||||
.build().expand(page,size).encode();
|
||||
.build().expand(page, size).encode();
|
||||
|
||||
try{
|
||||
try {
|
||||
RequestFilter requestFilter = new RequestFilter();
|
||||
requestFilter.setRegisteredby(userEmail);
|
||||
return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(),requestFilter, String[].class));
|
||||
}catch (Exception e){
|
||||
LOGGER.debug("Exception on addRepositoryInterface" , e);
|
||||
return Arrays.asList(restTemplate.postForObject(uriComponents.toUri(), requestFilter, String[].class));
|
||||
} catch (Exception e) {
|
||||
LOGGER.debug("Exception on addRepositoryInterface", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -824,7 +814,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
|
||||
@Override
|
||||
public Map<String, String> getCompatibilityClasses(String mode) {
|
||||
public Map<String, String> getCompatibilityClasses(String mode) {
|
||||
|
||||
LOGGER.debug("Getting compatibility classes for mode: " + mode);
|
||||
Map<String, String> retMap = new HashMap<String, String>();
|
||||
|
@ -853,7 +843,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getDatasourceClasses(String mode) {
|
||||
public Map<String, String> getDatasourceClasses(String mode) {
|
||||
|
||||
LOGGER.debug("Getting datasource classes for mode: " + mode);
|
||||
|
||||
|
@ -874,16 +864,16 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
retMap.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return filterResults(retMap,mode);
|
||||
return filterResults(retMap, mode);
|
||||
|
||||
}
|
||||
|
||||
private Map<String,String> filterResults(Map<String, String> map,String mode) {
|
||||
private Map<String, String> filterResults(Map<String, String> map, String mode) {
|
||||
|
||||
HashMap<String,String> filteredMap = new HashMap<>();
|
||||
for(String key:map.keySet())
|
||||
if(dataSourceClass.get(mode).contains(key))
|
||||
filteredMap.put(key,map.get(key));
|
||||
HashMap<String, String> filteredMap = new HashMap<>();
|
||||
for (String key : map.keySet())
|
||||
if (dataSourceClass.get(mode).contains(key))
|
||||
filteredMap.put(key, map.get(key));
|
||||
|
||||
return filteredMap;
|
||||
}
|
||||
|
@ -911,23 +901,23 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
|
||||
@Override
|
||||
public Map<String, String> getListLatestUpdate(String mode) throws JSONException {
|
||||
if(mode.equals("opendoar"))
|
||||
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(0).getLastCollectionDate());
|
||||
if (mode.equals("opendoar"))
|
||||
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::" + mode).get(0).getLastCollectionDate());
|
||||
else
|
||||
/*
|
||||
* first api of re3data has null value on collection date
|
||||
* */
|
||||
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::"+mode).get(1).getLastCollectionDate());
|
||||
* first api of re3data has null value on collection date
|
||||
* */
|
||||
return Collections.singletonMap("lastCollectionDate", getRepositoryInterface("openaire____::" + mode).get(1).getLastCollectionDate());
|
||||
}
|
||||
|
||||
private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/api/oaiset")
|
||||
.queryParam("dsId",repositoryId)
|
||||
.queryParam("apiId",repositoryInterfaceId)
|
||||
.queryParam("oaiSet",validationSet)
|
||||
.queryParam("dsId", repositoryId)
|
||||
.queryParam("apiId", repositoryInterfaceId)
|
||||
.queryParam("oaiSet", validationSet)
|
||||
.build().encode();
|
||||
restTemplate.exchange(uriComponents.toUri(),HttpMethod.POST, null, ResponseEntity.class);
|
||||
restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST, null, ResponseEntity.class);
|
||||
|
||||
}
|
||||
|
||||
|
@ -935,21 +925,21 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
private void updateBaseUrl(String repositoryId, String repositoryInterfaceId, String baseUrl) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/api/baseurl")
|
||||
.queryParam("dsId",repositoryId)
|
||||
.queryParam("apiId",repositoryInterfaceId)
|
||||
.queryParam("baseUrl",baseUrl)
|
||||
.queryParam("dsId", repositoryId)
|
||||
.queryParam("apiId", repositoryInterfaceId)
|
||||
.queryParam("baseUrl", baseUrl)
|
||||
.build().encode();
|
||||
restTemplate.postForObject(uriComponents.toUri(),null,String.class);
|
||||
restTemplate.postForObject(uriComponents.toUri(), null, String.class);
|
||||
}
|
||||
|
||||
private void updateCompliance(String repositoryId, String repositoryInterfaceId,String compliance) {
|
||||
private void updateCompliance(String repositoryId, String repositoryInterfaceId, String compliance) {
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/api/compliance")
|
||||
.queryParam("dsId",repositoryId)
|
||||
.queryParam("apiId",repositoryInterfaceId)
|
||||
.queryParam("compliance",compliance)
|
||||
.queryParam("dsId", repositoryId)
|
||||
.queryParam("apiId", repositoryInterfaceId)
|
||||
.queryParam("compliance", compliance)
|
||||
.build().encode();
|
||||
restTemplate.postForObject(uriComponents.toUri(),null,String.class);
|
||||
restTemplate.postForObject(uriComponents.toUri(), null, String.class);
|
||||
}
|
||||
|
||||
private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
|
||||
|
@ -970,7 +960,7 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
new ParameterizedTypeReference<MetricsNumbers>() {
|
||||
});
|
||||
} catch (RestClientException e) {
|
||||
LOGGER.debug("Exception on getMetricsNumbers" , e);
|
||||
LOGGER.debug("Exception on getMetricsNumbers", e);
|
||||
emailUtils.reportException(e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -987,39 +977,70 @@ public class RepositoryServiceImpl implements RepositoryService {
|
|||
return null;
|
||||
}
|
||||
|
||||
private UriComponents searchDatasource(String page,String size){
|
||||
private UriComponents searchDatasource(String page, String size) {
|
||||
|
||||
return UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/search/")
|
||||
.path("/{page}/{size}/")
|
||||
.queryParam("requestSortBy","officialname")
|
||||
.queryParam("order","ASCENDING")
|
||||
.queryParam("requestSortBy", "officialname")
|
||||
.queryParam("order", "ASCENDING")
|
||||
.build().expand(page, size).encode();
|
||||
}
|
||||
|
||||
private UriComponents searchSnipperDatasource(String page,String size){
|
||||
private UriComponents searchSnipperDatasource(String page, String size) {
|
||||
|
||||
return UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/searchsnippet/")
|
||||
.path("/{page}/{size}/")
|
||||
.queryParam("requestSortBy","officialname")
|
||||
.queryParam("order","ASCENDING")
|
||||
.queryParam("requestSortBy", "officialname")
|
||||
.queryParam("order", "ASCENDING")
|
||||
.build().expand(page, size).encode();
|
||||
}
|
||||
|
||||
private UriComponents searchRegisteredDatasource(String requestSortBy, String order, String page,String size){
|
||||
private UriComponents searchRegisteredDatasource(String requestSortBy, String order, String page, String size) {
|
||||
|
||||
return UriComponentsBuilder
|
||||
.fromHttpUrl(baseAddress + "/ds/searchregistered/")
|
||||
.path("/{page}/{size}/")
|
||||
.queryParam("requestSortBy",requestSortBy)
|
||||
.queryParam("order",order)
|
||||
.queryParam("requestSortBy", requestSortBy)
|
||||
.queryParam("order", order)
|
||||
.build().expand(page, size).encode();
|
||||
}
|
||||
|
||||
private String getRepositoryType(String typology){
|
||||
private String getRepositoryType(String typology) {
|
||||
return invertedDataSourceClass.get(typology);
|
||||
}
|
||||
|
||||
private List<String> getRoleIdsFromUserRoles(String userEmail) {
|
||||
Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail);
|
||||
JsonArray roles;
|
||||
ArrayList<String> roleIds = new ArrayList<>();
|
||||
ArrayList<Integer> couIds = new ArrayList<>();
|
||||
if (coPersonId != null) {
|
||||
roles = registryCalls.getRoles(coPersonId);
|
||||
for (JsonElement role : roles) {
|
||||
JsonObject object = role.getAsJsonObject();
|
||||
if (object.get("CouId") == null) {
|
||||
continue;
|
||||
}
|
||||
couIds.add(object.get("CouId").getAsInt());
|
||||
}
|
||||
|
||||
roleIds.addAll(registryCalls.getCouNames(couIds).values());
|
||||
|
||||
}
|
||||
return roleIds;
|
||||
}
|
||||
|
||||
private List<String> getRepoIdsFromUserRoles(String userEmail) {
|
||||
List<String> roleIds = getRoleIdsFromUserRoles(userEmail);
|
||||
List<String> repoIds = new ArrayList<>();
|
||||
for (String role : roleIds) {
|
||||
if (role.contains("datasource")) {
|
||||
// TODO: ask if checking for BETA prefix is required
|
||||
repoIds.add(role.replaceFirst(".*datasource\\.", "").replace("$", ":"));
|
||||
}
|
||||
}
|
||||
return repoIds;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
package eu.dnetlib.repo.manager.service.security;
|
||||
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
public interface AaiUserRoleService {
|
||||
|
||||
/**
|
||||
* @param fullName
|
||||
* @param prefix
|
||||
* @return
|
||||
*/
|
||||
String getRepoNameWithoutType(String fullName, String prefix);
|
||||
|
||||
/**
|
||||
* @param repoId
|
||||
* @param prefix
|
||||
* @return
|
||||
*/
|
||||
String getRoleIdByRepoId(String repoId, String prefix);
|
||||
|
||||
/**
|
||||
* @param repoId
|
||||
* @return
|
||||
*/
|
||||
String convertRepoIdToAuthorityId(String repoId);
|
||||
|
||||
/**
|
||||
* @param repoId
|
||||
* @return
|
||||
*/
|
||||
String convertRepoIdToEncodedAuthorityId(String repoId);
|
||||
|
||||
/**
|
||||
* @param repoId
|
||||
* @return
|
||||
*/
|
||||
SimpleGrantedAuthority convertRepoIdToAuthority(String repoId);
|
||||
|
||||
/**
|
||||
* @param repoId
|
||||
* @return
|
||||
*/
|
||||
boolean isMemberOf(String repoId);
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package eu.dnetlib.repo.manager.service.security;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
|
||||
@Service("aaiUserRoleService")
|
||||
public class AaiUserRoleServiceImpl implements AaiUserRoleService {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(AaiUserRoleServiceImpl.class);
|
||||
|
||||
@Value("${registry.production:true}")
|
||||
private boolean production;
|
||||
|
||||
|
||||
private String createRepoRoleName(String prefix, String repoId) {
|
||||
return prefix + "." + repoId.replace(":", "$");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRepoNameWithoutType(String fullName, String prefix) {
|
||||
if (fullName != null && prefix != null && fullName.startsWith(prefix)) {
|
||||
return fullName.substring(prefix.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRoleIdByRepoId(String repoId, String prefix) {
|
||||
String roleId = "";
|
||||
if (repoId != null && prefix != null) {
|
||||
roleId = createRepoRoleName(prefix, repoId);
|
||||
return roleId;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertRepoIdToAuthorityId(String repoId) {
|
||||
StringBuilder roleBuilder = new StringBuilder();
|
||||
String role = "";
|
||||
if (repoId != null) {
|
||||
roleBuilder.append(production ? "" : "beta.");
|
||||
roleBuilder.append("datasource.");
|
||||
roleBuilder.append(repoId.replace(":", "$"));
|
||||
role = roleBuilder.toString().replace(".", "_").toUpperCase();
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertRepoIdToEncodedAuthorityId(String repoId) {
|
||||
return URLEncoder.encode(convertRepoIdToAuthorityId(repoId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimpleGrantedAuthority convertRepoIdToAuthority(String repoId) {
|
||||
String role = convertRepoIdToEncodedAuthorityId(repoId);
|
||||
if (role != null) {
|
||||
role = URLEncoder.encode(role);
|
||||
}
|
||||
return new SimpleGrantedAuthority(role);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isMemberOf(String repoId) {
|
||||
String repoRole = convertRepoIdToEncodedAuthorityId(repoId);
|
||||
return SecurityContextHolder.getContext().getAuthentication().getAuthorities()
|
||||
.parallelStream().anyMatch(authority -> authority.toString().equals(repoRole));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package eu.dnetlib.repo.manager.service.security;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.session.ExpiringSession;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@Service
|
||||
public class AuthoritiesUpdater extends HttpSessionSecurityContextRepository {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(AuthoritiesUpdater.class);
|
||||
|
||||
@Autowired
|
||||
FindByIndexNameSessionRepository sessions;
|
||||
|
||||
public void update(String id, Update update) {
|
||||
if (sessions != null) {
|
||||
Map<String, ExpiringSession> map = sessions.
|
||||
findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, id);
|
||||
logger.debug(map.values().toArray().length);
|
||||
for (ExpiringSession session : map.values()) {
|
||||
logger.debug(session.getId());
|
||||
if (!session.isExpired()) {
|
||||
SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
|
||||
Authentication authentication = securityContext.getAuthentication();
|
||||
if (authentication instanceof OIDCAuthenticationToken) {
|
||||
OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
|
||||
Collection<? extends GrantedAuthority> authorities = update.authorities(authentication.getAuthorities());
|
||||
logger.debug(authorities);
|
||||
securityContext.setAuthentication(new OIDCAuthenticationToken(authOIDC.getSub(), authOIDC.getIssuer(),
|
||||
authOIDC.getUserInfo(), authorities, authOIDC.getIdToken(),
|
||||
authOIDC.getAccessTokenValue(), authOIDC.getRefreshTokenValue()));
|
||||
logger.debug("Update authorities");
|
||||
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
|
||||
sessions.save(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface Update {
|
||||
Collection<? extends GrantedAuthority> authorities(Collection<? extends GrantedAuthority> old);
|
||||
}
|
||||
}
|
|
@ -1,16 +1,16 @@
|
|||
package eu.dnetlib.repo.manager.utils;
|
||||
package eu.dnetlib.repo.manager.service.security;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component("AuthorizationService")
|
||||
public class AuthorizationService {
|
||||
public class AuthorizationServiceImpl implements AuthorizationService {
|
||||
|
||||
public final String ROLE_ADMIN = "ROLE_ADMIN";
|
||||
public final String ROLE_PROVIDE_ADMIN = "ROLE_PROVIDE_ADMIN";
|
||||
public final String ROLE_USER = "ROLE_USER";
|
||||
|
||||
private String mapType(String type) {
|
||||
if(type.equals("datasource")) {
|
||||
if (type.equals("datasource")) {
|
||||
type = "datasource";
|
||||
}
|
||||
return type;
|
||||
|
@ -18,8 +18,7 @@ public class AuthorizationService {
|
|||
|
||||
/**
|
||||
* Type = DATASOURCE
|
||||
*
|
||||
* */
|
||||
*/
|
||||
public String member(String type, String id) {
|
||||
return mapType(type).toUpperCase() + "_" + id.toUpperCase();
|
||||
}
|
|
@ -12,6 +12,7 @@ import org.apache.log4j.Logger;
|
|||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
|
@ -21,6 +22,7 @@ import java.text.ParseException;
|
|||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
public class Converter {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(Converter.class);
|
||||
|
@ -28,7 +30,7 @@ public class Converter {
|
|||
public static Repository jsonToRepositoryObject(JSONObject repositoryObject) throws JSONException {
|
||||
|
||||
Repository repository = new Repository();
|
||||
|
||||
|
||||
JSONObject datasource = repositoryObject.getJSONObject("datasource");
|
||||
|
||||
//if( datasource.equals(null))
|
||||
|
@ -37,51 +39,51 @@ public class Converter {
|
|||
repository.setId(datasource.get("id").toString());
|
||||
repository.setOfficialName(datasource.get("officialname").toString());
|
||||
|
||||
repository.setEnglishName( datasource.get("englishname").toString());
|
||||
if(repository.getEnglishName().equals("null"))
|
||||
repository.setEnglishName(datasource.get("englishname").toString());
|
||||
if (repository.getEnglishName().equals("null"))
|
||||
repository.setEnglishName("");
|
||||
|
||||
repository.setWebsiteUrl(datasource.get("websiteurl").toString());
|
||||
if(repository.getWebsiteUrl().equals("null"))
|
||||
if (repository.getWebsiteUrl().equals("null"))
|
||||
repository.setWebsiteUrl("");
|
||||
|
||||
repository.setLogoUrl(datasource.get("logourl").toString());
|
||||
if(repository.getLogoUrl().equals("null"))
|
||||
if (repository.getLogoUrl().equals("null"))
|
||||
repository.setLogoUrl("");
|
||||
|
||||
repository.setContactEmail(datasource.get("contactemail").toString());
|
||||
if(repository.getContactEmail().equals("null"))
|
||||
if (repository.getContactEmail().equals("null"))
|
||||
repository.setContactEmail("");
|
||||
|
||||
|
||||
repository.setLatitude( toDouble(datasource.get("latitude").toString()));
|
||||
repository.setLatitude(toDouble(datasource.get("latitude").toString()));
|
||||
repository.setLongitude(toDouble(datasource.get("longitude").toString()));
|
||||
Double timezone = toDouble(datasource.get("timezone").toString());
|
||||
repository.setTimezone(timezone!=null?timezone:0.0);
|
||||
repository.setTimezone(timezone != null ? timezone : 0.0);
|
||||
repository.setNamespacePrefix(datasource.get("namespaceprefix").toString());
|
||||
repository.setOdLanguages(datasource.get("languages").toString());
|
||||
repository.setDateOfValidation(convertStringToDate( datasource.get("dateofvalidation").toString()));
|
||||
repository.setDateOfValidation(convertStringToDate(datasource.get("dateofvalidation").toString()));
|
||||
|
||||
/* typology -> platform
|
||||
* datasource class -> typology */
|
||||
repository.setTypology(datasource.get("platform").toString());
|
||||
if(repository.getTypology().equals("null"))
|
||||
if (repository.getTypology().equals("null"))
|
||||
repository.setTypology("");
|
||||
repository.setDatasourceClass(datasource.get("typology").toString());
|
||||
|
||||
repository.setDateOfCollection(convertStringToDate( datasource.get("dateofcollection").toString()));
|
||||
repository.setDateOfCollection(convertStringToDate(datasource.get("dateofcollection").toString()));
|
||||
repository.setActivationId(datasource.get("activationId").toString());
|
||||
|
||||
repository.setDescription(datasource.get("description").toString());
|
||||
if(repository.getDescription().equals("null"))
|
||||
if (repository.getDescription().equals("null"))
|
||||
repository.setDescription("");
|
||||
|
||||
repository.setIssn(datasource.get("issn").toString());
|
||||
repository.setLissn(datasource.get("lissn").toString());
|
||||
if(repository.getLissn().equals("null"))
|
||||
if (repository.getLissn().equals("null"))
|
||||
repository.setLissn("");
|
||||
repository.setEissn(datasource.get("eissn").toString());
|
||||
if(repository.getEissn().equals("null"))
|
||||
if (repository.getEissn().equals("null"))
|
||||
repository.setEissn("");
|
||||
repository.setRegisteredBy(datasource.get("registeredby").toString());
|
||||
|
||||
|
@ -94,8 +96,8 @@ public class Converter {
|
|||
repository.setCollectedFrom(datasource.get("collectedfrom").toString());
|
||||
|
||||
//TODO change organization to list
|
||||
JSONArray organizations = ((JSONArray)datasource.get("organizations"));
|
||||
if(organizations.length() != 0) {
|
||||
JSONArray organizations = ((JSONArray) datasource.get("organizations"));
|
||||
if (organizations.length() != 0) {
|
||||
repository.setOrganization(((JSONArray) datasource.get("organizations")).getJSONObject(0).get("legalname").toString());
|
||||
String countryCode = ((JSONArray) datasource.get("organizations")).getJSONObject(0).get("country").toString();
|
||||
repository.setCountryCode(countryCode);
|
||||
|
@ -106,31 +108,31 @@ public class Converter {
|
|||
return repository;
|
||||
}
|
||||
|
||||
public static Date convertStringToDate(String date){
|
||||
public static Date convertStringToDate(String date) {
|
||||
|
||||
if(Objects.equals(date, "null"))
|
||||
if (Objects.equals(date, "null"))
|
||||
return null;
|
||||
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
try {
|
||||
return formatter.parse(date);
|
||||
} catch (ParseException e) {
|
||||
LOGGER.error(e);
|
||||
LOGGER.error(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String convertDateToString(Date date){
|
||||
public static String convertDateToString(Date date) {
|
||||
|
||||
if(Objects.equals(date, null))
|
||||
if (Objects.equals(date, null))
|
||||
return null;
|
||||
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return formatter.format(date);
|
||||
}
|
||||
|
||||
public static Double toDouble(String number){
|
||||
if(Objects.equals(number, "null"))
|
||||
public static Double toDouble(String number) {
|
||||
if (Objects.equals(number, "null"))
|
||||
return 0.0;
|
||||
else
|
||||
return Double.valueOf(number);
|
||||
|
@ -140,8 +142,8 @@ public class Converter {
|
|||
|
||||
List<RepositorySnippet> resultSet = new ArrayList<>();
|
||||
JSONArray rs = json.getJSONArray("datasourceInfo");
|
||||
for(int i=0;i<rs.length();i++)
|
||||
resultSet.add(jsonToRepositorySnippetObject( rs.getJSONObject(i)) );
|
||||
for (int i = 0; i < rs.length(); i++)
|
||||
resultSet.add(jsonToRepositorySnippetObject(rs.getJSONObject(i)));
|
||||
return resultSet;
|
||||
}
|
||||
|
||||
|
@ -156,16 +158,16 @@ public class Converter {
|
|||
repositorySnippet.setId(repositorySnippetObject.get("id").toString());
|
||||
repositorySnippet.setOfficialname(repositorySnippetObject.get("officialname").toString());
|
||||
|
||||
repositorySnippet.setEnglishname( repositorySnippetObject.get("englishname").toString());
|
||||
if(repositorySnippet.getEnglishname().equals("null"))
|
||||
repositorySnippet.setEnglishname(repositorySnippetObject.get("englishname").toString());
|
||||
if (repositorySnippet.getEnglishname().equals("null"))
|
||||
repositorySnippet.setEnglishname("");
|
||||
|
||||
repositorySnippet.setWebsiteurl(repositorySnippetObject.get("websiteurl").toString());
|
||||
if(repositorySnippet.getWebsiteurl().equals("null"))
|
||||
if (repositorySnippet.getWebsiteurl().equals("null"))
|
||||
repositorySnippet.setWebsiteurl("");
|
||||
|
||||
repositorySnippet.setRegisteredby(repositorySnippetObject.get("registeredby").toString());
|
||||
if(repositorySnippet.getRegisteredby().equals("null"))
|
||||
if (repositorySnippet.getRegisteredby().equals("null"))
|
||||
repositorySnippet.setRegisteredby("");
|
||||
return repositorySnippet;
|
||||
|
||||
|
@ -175,8 +177,8 @@ public class Converter {
|
|||
|
||||
List<Repository> resultSet = new ArrayList<>();
|
||||
JSONArray rs = json.getJSONArray("datasourceInfo");
|
||||
for(int i=0;i<rs.length();i++)
|
||||
resultSet.add(jsonToRepositoryObject( rs.getJSONObject(i)) );
|
||||
for (int i = 0; i < rs.length(); i++)
|
||||
resultSet.add(jsonToRepositoryObject(rs.getJSONObject(i)));
|
||||
return resultSet;
|
||||
}
|
||||
|
||||
|
@ -184,8 +186,8 @@ public class Converter {
|
|||
|
||||
List<RepositoryInterface> resultSet = new ArrayList<>();
|
||||
JSONArray rs = json.getJSONArray("api");
|
||||
for(int i=0;i<rs.length();i++)
|
||||
resultSet.add(jsonToRepositoryInterfaceObject( rs.getJSONObject(i)) );
|
||||
for (int i = 0; i < rs.length(); i++)
|
||||
resultSet.add(jsonToRepositoryInterfaceObject(rs.getJSONObject(i)));
|
||||
return resultSet;
|
||||
}
|
||||
|
||||
|
@ -204,7 +206,7 @@ public class Converter {
|
|||
repositoryInterface.setRemovable(Boolean.parseBoolean(repositoryInterfaceObject.get("removable").toString()));
|
||||
|
||||
|
||||
// repositoryInterface.setMetadataIdentifierPath(repositoryInterfaceObject.get("metadataIdentifierPath").toString());
|
||||
// repositoryInterface.setMetadataIdentifierPath(repositoryInterfaceObject.get("metadataIdentifierPath").toString());
|
||||
repositoryInterface.setDesiredCompatibilityLevel(repositoryInterfaceObject.get("compatibility").toString());
|
||||
//repositoryInterface.setActive(Boolean.parseBoolean(repositoryInterfaceObject.get("active").toString()));
|
||||
|
||||
|
@ -215,8 +217,8 @@ public class Converter {
|
|||
ObjectMapper mapper = new ObjectMapper();
|
||||
JSONArray apiparams = repositoryInterfaceObject.getJSONArray("apiParams");
|
||||
|
||||
for(int i=0;i<apiparams.length();i++)
|
||||
accessParams.put(apiparams.getJSONObject(i).getString("param"),apiparams.getJSONObject(i).getString("value"));
|
||||
for (int i = 0; i < apiparams.length(); i++)
|
||||
accessParams.put(apiparams.getJSONObject(i).getString("param"), apiparams.getJSONObject(i).getString("value"));
|
||||
|
||||
repositoryInterface.setAccessParams(accessParams);
|
||||
|
||||
|
@ -225,58 +227,58 @@ public class Converter {
|
|||
|
||||
public static String repositoryObjectToJson(Repository repository) throws JSONException, JsonProcessingException {
|
||||
|
||||
HashMap<String,Object> repositoryMap = new HashMap<>();
|
||||
HashMap<String, Object> repositoryMap = new HashMap<>();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
repositoryMap.put("id",repository.getId());
|
||||
repositoryMap.put("openaireId",getOpenaireId(repository.getId()));
|
||||
repositoryMap.put("officialname",repository.getOfficialName());
|
||||
repositoryMap.put("englishname",repository.getEnglishName());
|
||||
repositoryMap.put("websiteurl",repository.getWebsiteUrl());
|
||||
repositoryMap.put("logourl",repository.getLogoUrl());
|
||||
repositoryMap.put("contactemail",repository.getContactEmail());
|
||||
repositoryMap.put("longitude",repository.getLongitude().toString());
|
||||
repositoryMap.put("latitude",repository.getLatitude().toString());
|
||||
repositoryMap.put("timezone",repository.getTimezone());
|
||||
repositoryMap.put("id", repository.getId());
|
||||
repositoryMap.put("openaireId", getOpenaireId(repository.getId()));
|
||||
repositoryMap.put("officialname", repository.getOfficialName());
|
||||
repositoryMap.put("englishname", repository.getEnglishName());
|
||||
repositoryMap.put("websiteurl", repository.getWebsiteUrl());
|
||||
repositoryMap.put("logourl", repository.getLogoUrl());
|
||||
repositoryMap.put("contactemail", repository.getContactEmail());
|
||||
repositoryMap.put("longitude", repository.getLongitude().toString());
|
||||
repositoryMap.put("latitude", repository.getLatitude().toString());
|
||||
repositoryMap.put("timezone", repository.getTimezone());
|
||||
|
||||
repositoryMap.put("namespaceprefix",repository.getNamespacePrefix()!=null?repository.getNamespacePrefix():"");
|
||||
repositoryMap.put("languages",repository.getOdLanguages()!=null?repository.getOdLanguages():"");
|
||||
repositoryMap.put("namespaceprefix", repository.getNamespacePrefix() != null ? repository.getNamespacePrefix() : "");
|
||||
repositoryMap.put("languages", repository.getOdLanguages() != null ? repository.getOdLanguages() : "");
|
||||
|
||||
repositoryMap.put("dateofcollection",repository.getDateOfCollection()!=null?convertDateToString(repository.getDateOfCollection()):"");
|
||||
repositoryMap.put("dateofcollection", repository.getDateOfCollection() != null ? convertDateToString(repository.getDateOfCollection()) : "");
|
||||
|
||||
/*
|
||||
* typology -> platform
|
||||
* datasource class -> typology
|
||||
* */
|
||||
repositoryMap.put("typology",repository.getDatasourceClass());
|
||||
repositoryMap.put("platform",repository.getTypology());
|
||||
* typology -> platform
|
||||
* datasource class -> typology
|
||||
* */
|
||||
repositoryMap.put("typology", repository.getDatasourceClass());
|
||||
repositoryMap.put("platform", repository.getTypology());
|
||||
|
||||
repositoryMap.put("dateofvalidation",repository.getDateOfCollection()!=null?convertDateToString(repository.getDateOfCollection()):"");
|
||||
repositoryMap.put("activationId",repository.getActivationId()!=null?repository.getActivationId():"");
|
||||
repositoryMap.put("dateofvalidation", repository.getDateOfCollection() != null ? convertDateToString(repository.getDateOfCollection()) : "");
|
||||
repositoryMap.put("activationId", repository.getActivationId() != null ? repository.getActivationId() : "");
|
||||
|
||||
repositoryMap.put("description",repository.getDescription());
|
||||
repositoryMap.put("description", repository.getDescription());
|
||||
|
||||
repositoryMap.put("eissn",repository.getEissn()!=null?repository.getEissn():"");
|
||||
repositoryMap.put("issn",repository.getIssn()!=null?repository.getIssn():"");
|
||||
repositoryMap.put("lissn",repository.getLissn()!=null?repository.getLissn():"");
|
||||
repositoryMap.put("eissn", repository.getEissn() != null ? repository.getEissn() : "");
|
||||
repositoryMap.put("issn", repository.getIssn() != null ? repository.getIssn() : "");
|
||||
repositoryMap.put("lissn", repository.getLissn() != null ? repository.getLissn() : "");
|
||||
|
||||
repositoryMap.put("registeredby",repository.getRegisteredBy());
|
||||
repositoryMap.put("registeredby", repository.getRegisteredBy());
|
||||
|
||||
repositoryMap.put("aggregator",repository.getAggregator()!=null?repository.getAggregator():"");
|
||||
repositoryMap.put("collectedfrom",repository.getCollectedFrom()!=null?repository.getCollectedFrom():"");
|
||||
repositoryMap.put("aggregator", repository.getAggregator() != null ? repository.getAggregator() : "");
|
||||
repositoryMap.put("collectedfrom", repository.getCollectedFrom() != null ? repository.getCollectedFrom() : "");
|
||||
|
||||
repositoryMap.put("managed",repository.isRegistered());
|
||||
repositoryMap.put("managed", repository.isRegistered());
|
||||
|
||||
Map<String,String> organization = new HashMap<>();
|
||||
organization.put("legalname",repository.getOrganization());
|
||||
organization.put("country",repository.getCountryCode());
|
||||
organization.put("legalshortname","");
|
||||
organization.put("websiteurl","");
|
||||
organization.put("logourl","");
|
||||
Map<String, String> organization = new HashMap<>();
|
||||
organization.put("legalname", repository.getOrganization());
|
||||
organization.put("country", repository.getCountryCode());
|
||||
organization.put("legalshortname", "");
|
||||
organization.put("websiteurl", "");
|
||||
organization.put("logourl", "");
|
||||
|
||||
List organizations = new ArrayList();
|
||||
organizations.add(organization);
|
||||
repositoryMap.put("organizations",organizations);
|
||||
repositoryMap.put("organizations", organizations);
|
||||
|
||||
//TODO check identitites
|
||||
//Map<String,String> identity = new HashMap<>();
|
||||
|
@ -293,43 +295,43 @@ public class Converter {
|
|||
repositoryMap.put("identities", identities);
|
||||
}
|
||||
|
||||
repositoryMap.put("subjects","");
|
||||
repositoryMap.put("subjects", "");
|
||||
|
||||
return mapper.writeValueAsString(repositoryMap);
|
||||
}
|
||||
|
||||
public static String repositoryInterfaceObjectToJson(Repository repository,RepositoryInterface repositoryInterface) throws JSONException {
|
||||
public static String repositoryInterfaceObjectToJson(Repository repository, RepositoryInterface repositoryInterface) throws JSONException {
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
|
||||
jsonObject.put("id",repositoryInterface.getId());
|
||||
jsonObject.put("protocol",repositoryInterface.getAccessProtocol());
|
||||
jsonObject.put("datasource",repository.getId());
|
||||
jsonObject.put("contentdescription",repositoryInterface.getContentDescription());
|
||||
jsonObject.put("typology",repositoryInterface.getTypology());
|
||||
jsonObject.put("compatibility",repositoryInterface.getDesiredCompatibilityLevel());
|
||||
jsonObject.put("compatibilityOverride",repositoryInterface.getDesiredCompatibilityLevel());
|
||||
jsonObject.put("id", repositoryInterface.getId());
|
||||
jsonObject.put("protocol", repositoryInterface.getAccessProtocol());
|
||||
jsonObject.put("datasource", repository.getId());
|
||||
jsonObject.put("contentdescription", repositoryInterface.getContentDescription());
|
||||
jsonObject.put("typology", repositoryInterface.getTypology());
|
||||
jsonObject.put("compatibility", repositoryInterface.getDesiredCompatibilityLevel());
|
||||
jsonObject.put("compatibilityOverride", repositoryInterface.getDesiredCompatibilityLevel());
|
||||
|
||||
jsonObject.put("lastCollectionTotal","");
|
||||
jsonObject.put("lastCollectionTotal", "");
|
||||
|
||||
jsonObject.put("lastCollectionDate",repositoryInterface.getLastCollectionDate());
|
||||
jsonObject.put("lastAggregationTotal","");
|
||||
jsonObject.put("lastAggregationDate","");
|
||||
jsonObject.put("lastDownloadTotal","");
|
||||
jsonObject.put("lastDownloadDate","");
|
||||
jsonObject.put("lastCollectionDate", repositoryInterface.getLastCollectionDate());
|
||||
jsonObject.put("lastAggregationTotal", "");
|
||||
jsonObject.put("lastAggregationDate", "");
|
||||
jsonObject.put("lastDownloadTotal", "");
|
||||
jsonObject.put("lastDownloadDate", "");
|
||||
|
||||
jsonObject.put("baseurl", repositoryInterface.getBaseUrl());
|
||||
jsonObject.put("removable", repositoryInterface.isRemovable());
|
||||
|
||||
jsonObject.put("baseurl",repositoryInterface.getBaseUrl());
|
||||
jsonObject.put("removable",repositoryInterface.isRemovable());
|
||||
|
||||
|
||||
JSONArray apiparams = new JSONArray();
|
||||
for(String param: repositoryInterface.getAccessParams().keySet()){
|
||||
for (String param : repositoryInterface.getAccessParams().keySet()) {
|
||||
JSONObject jo = new JSONObject();
|
||||
jo.put("param",param);
|
||||
jo.put("value",repositoryInterface.getAccessParams().get(param));
|
||||
jo.put("param", param);
|
||||
jo.put("value", repositoryInterface.getAccessParams().get(param));
|
||||
apiparams.put(jo);
|
||||
}
|
||||
jsonObject.put("apiParams",apiparams);
|
||||
jsonObject.put("apiParams", apiparams);
|
||||
|
||||
|
||||
// jsonObject.put("metadataIdentifierPath",repositoryInterface.getMetadataIdentifierPath());
|
||||
|
@ -345,7 +347,7 @@ public class Converter {
|
|||
//InputStream in = Converter.class.getResourceAsStream("resources/eu/dnetlib/repo/manager/service/utils/"+filename);
|
||||
InputStream in = Converter.class.getClass().getResourceAsStream("/eu/**/" + filename);
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(in));
|
||||
while((line = br.readLine()) != null) {
|
||||
while ((line = br.readLine()) != null) {
|
||||
list.add(line.trim());
|
||||
}
|
||||
br.close();
|
||||
|
@ -375,9 +377,9 @@ public class Converter {
|
|||
AggregationDetails aggregationDetails = new AggregationDetails();
|
||||
|
||||
aggregationDetails.setAggregationStage(aggregationObject.get("aggregationStage").toString());
|
||||
if(aggregationObject.has("collectionMode"))
|
||||
if (aggregationObject.has("collectionMode"))
|
||||
aggregationDetails.setCollectionMode(aggregationObject.get("collectionMode").toString());
|
||||
if(aggregationObject.has("indexedVersion"))
|
||||
if (aggregationObject.has("indexedVersion"))
|
||||
aggregationDetails.setIndexedVersion(Boolean.parseBoolean(aggregationObject.get("indexedVersion").toString()));
|
||||
aggregationDetails.setDate(convertStringToDate(aggregationObject.get("date").toString()));
|
||||
aggregationDetails.setNumberOfRecords(Integer.parseInt(aggregationObject.get("numberOfRecords").toString()));
|
||||
|
@ -388,9 +390,9 @@ public class Converter {
|
|||
public static List<Timezone> toTimezones(List<String> timezones) {
|
||||
|
||||
List<Timezone> tmz = new ArrayList<>();
|
||||
for(String t : timezones){
|
||||
for (String t : timezones) {
|
||||
String[] s = t.split("\t");
|
||||
tmz.add(new Timezone(s[1],Double.parseDouble(s[0])));
|
||||
tmz.add(new Timezone(s[1], Double.parseDouble(s[0])));
|
||||
}
|
||||
return tmz;
|
||||
}
|
||||
|
@ -401,11 +403,4 @@ public class Converter {
|
|||
return null;
|
||||
}
|
||||
|
||||
public static String convertRepoIdToRoleId(String repoId) {
|
||||
if ( repoId != null ) {
|
||||
return "datasource." + repoId.replaceAll(":", "$");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -18,6 +18,7 @@ public class HttpUtils {
|
|||
|
||||
private static final Logger logger = Logger.getLogger(HttpUtils.class);
|
||||
|
||||
//TODO: refactor
|
||||
// TODO: To be changed the values
|
||||
// @Value("https://aai.openaire.eu/registry/")
|
||||
@Value("https://openaire-dev.aai-dev.grnet.gr/registry/")
|
||||
|
@ -35,7 +36,7 @@ public class HttpUtils {
|
|||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
|
||||
ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.POST, request, String.class);
|
||||
if(responseEntity.getBody() != null) {
|
||||
if (responseEntity.getBody() != null) {
|
||||
return new JsonParser().parse(responseEntity.getBody());
|
||||
} else {
|
||||
return null;
|
||||
|
@ -48,7 +49,7 @@ public class HttpUtils {
|
|||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
|
||||
ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.PUT, request, String.class);
|
||||
if(responseEntity.getBody() != null) {
|
||||
if (responseEntity.getBody() != null) {
|
||||
return new JsonParser().parse(responseEntity.getBody());
|
||||
} else {
|
||||
return null;
|
||||
|
@ -60,7 +61,7 @@ public class HttpUtils {
|
|||
String url = issuer + path + ((params != null) ? createParams(params) : null);
|
||||
ResponseEntity<String> responseEntity = restTemplate.exchange
|
||||
(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
|
||||
if(responseEntity.getBody() != null) {
|
||||
if (responseEntity.getBody() != null) {
|
||||
return new JsonParser().parse(responseEntity.getBody());
|
||||
} else {
|
||||
return null;
|
||||
|
@ -72,7 +73,7 @@ public class HttpUtils {
|
|||
String url = issuer + path;
|
||||
ResponseEntity<String> responseEntity = restTemplate.exchange
|
||||
(url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class);
|
||||
if(responseEntity.getBody() != null) {
|
||||
if (responseEntity.getBody() != null) {
|
||||
return new JsonParser().parse(responseEntity.getBody());
|
||||
} else {
|
||||
return null;
|
||||
|
|
|
@ -1,57 +1,11 @@
|
|||
package eu.dnetlib.repo.manager.utils;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import eu.dnetlib.repo.manager.domain.dto.Role;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class JsonUtils {
|
||||
|
||||
@Value("1.0")
|
||||
private String version;
|
||||
|
||||
@Value("2")
|
||||
private String coid;
|
||||
|
||||
public JsonObject coPersonRoles(Integer coPersonId, Integer couId, String status) {
|
||||
JsonObject role = new JsonObject();
|
||||
JsonArray coPersonRoles = new JsonArray();
|
||||
JsonObject coPersonRole = new JsonObject();
|
||||
JsonObject person = new JsonObject();
|
||||
person.addProperty("Type", "CO");
|
||||
person.addProperty("Id", coPersonId.toString());
|
||||
coPersonRole.addProperty("Version", version);
|
||||
coPersonRole.add("Person", person);
|
||||
coPersonRole.addProperty("CouId", couId.toString());
|
||||
coPersonRole.addProperty("Affiliation", "member");
|
||||
coPersonRole.addProperty("Title", "");
|
||||
coPersonRole.addProperty("O", "Openaire");
|
||||
coPersonRole.addProperty("Status", status);
|
||||
coPersonRole.addProperty("ValidFrom", "");
|
||||
coPersonRole.addProperty("ValidThrough", "");
|
||||
coPersonRoles.add(coPersonRole);
|
||||
role.addProperty("RequestType", "CoPersonRoles");
|
||||
role.addProperty("Version", version);
|
||||
role.add("CoPersonRoles", coPersonRoles);
|
||||
return role;
|
||||
}
|
||||
|
||||
public JsonObject createNewCou(Role role) {
|
||||
JsonObject cou = new JsonObject();
|
||||
JsonArray cous = new JsonArray();
|
||||
JsonObject newCou = new JsonObject();
|
||||
newCou.addProperty("Version", version);
|
||||
newCou.addProperty("CoId", coid);
|
||||
newCou.addProperty("Name", role.getName());
|
||||
newCou.addProperty("Description", role.getDescription());
|
||||
cous.add(newCou);
|
||||
cou.addProperty("RequestType", "Cous");
|
||||
cou.addProperty("Version", version);
|
||||
cou.add("Cous", cous);
|
||||
return cou;
|
||||
private JsonUtils() {
|
||||
}
|
||||
|
||||
public JsonObject createResponse(JsonElement response) {
|
||||
|
@ -60,7 +14,7 @@ public class JsonUtils {
|
|||
return json;
|
||||
}
|
||||
|
||||
public JsonObject createResponse(String response) {
|
||||
public static JsonObject createResponse(String response) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("response", response);
|
||||
return json;
|
||||
|
@ -72,13 +26,13 @@ public class JsonUtils {
|
|||
return json;
|
||||
}
|
||||
|
||||
public JsonObject createResponse(Boolean response) {
|
||||
public static JsonObject createResponse(Boolean response) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("response", response);
|
||||
return json;
|
||||
}
|
||||
|
||||
public JsonObject createResponse(Character response) {
|
||||
public static JsonObject createResponse(Character response) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("response", response);
|
||||
return json;
|
||||
|
|
Loading…
Reference in New Issue