Project

General

Profile

« Previous | Next » 

Revision 49733

Creation of newAPI branch

View differences:

modules/uoa-repository-manager-gui/branches/newAPI/deploy.info
1
{
2
"type_source": "SVN",
3
"goal": "package -U source:jar",
4
"url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-repository-manager-gui/trunk/",
5
"deploy_repository": "dnet45-snapshots",
6
"version": "4",
7
"mail": "antleb@di.uoa.gr",
8
"deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-snapshots",
9
"name": "uoa-repository-manager-gui"
10
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/utils/EmailUtils.java
1
package eu.dnetlib.repo.manager.server.utils;
2

  
3
import eu.dnetlib.domain.functionality.UserProfile;
4

  
5
/**
6
 * Created by nikonas on 11/12/15.
7
 */
8
public interface EmailUtils {
9

  
10
    void sendActivationEmail(UserProfile user, String activationId) throws Exception;
11

  
12
    void sendResetPasswordEmail(String user, String securityCode) throws Exception;
13

  
14
    void reportException(Exception exception);
15

  
16
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/utils/OaiTools.java
1
package eu.dnetlib.repo.manager.server.utils;
2

  
3
import org.apache.log4j.Logger;
4
import org.dom4j.io.DOMWriter;
5
import org.springframework.beans.factory.annotation.Configurable;
6
import org.w3c.dom.Document;
7
import se.kb.oai.OAIException;
8
import se.kb.oai.pmh.*;
9

  
10
import javax.net.ssl.*;
11
import javax.xml.namespace.NamespaceContext;
12
import javax.xml.xpath.XPath;
13
import javax.xml.xpath.XPathExpressionException;
14
import javax.xml.xpath.XPathFactory;
15
import java.security.KeyManagementException;
16
import java.security.NoSuchAlgorithmException;
17
import java.security.cert.X509Certificate;
18
import java.util.ArrayList;
19
import java.util.Collections;
20
import java.util.Iterator;
21
import java.util.List;
22

  
23
public class OaiTools {
24

  
25
	{
26
		disableSslVerification();
27
	}
28

  
29
	private static Logger LOGGER = Logger.getLogger(OaiTools.class);
30

  
31
	public static List<String> getSetsOfRepo(String baseUrl) throws Exception {
32
		try {
33
			LOGGER.debug("Getting sets of repository " + baseUrl);
34
			OaiPmhServer harvester = new OaiPmhServer(baseUrl);
35
			SetsList setList = harvester.listSets();
36
			ResumptionToken token = setList.getResumptionToken();
37
			List<Set> sets = new ArrayList<Set>();
38
			sets.addAll(setList.asList());
39
			while (token != null) {
40
				setList = harvester.listSets(token);
41
				token = setList.getResumptionToken();
42
				sets.addAll(setList.asList());
43
			}
44

  
45
			List<String> ret = new ArrayList<String>();
46
			for (Set set : sets) {
47
				ret.add(set.getSpec().trim());
48
			}
49
			if (ret.size() > 0 )
50
				Collections.sort(ret);
51
			return ret;
52

  
53
		} catch (Exception e) {
54
			LOGGER.error("Error getting sets of repository " + baseUrl, e);
55
			return new ArrayList<String>();
56
			//throw e;
57
		}
58
	}
59

  
60
	public static boolean identifyRepository(String baseUrl) throws Exception {
61
		LOGGER.debug("sending identify request to repo " + baseUrl);
62

  
63
		OaiPmhServer harvester = new OaiPmhServer(baseUrl);
64

  
65
		if (baseUrl.trim().isEmpty()) {
66
			return false;
67
		}
68

  
69
		try {
70
			Identification identification = harvester.identify();
71
			DOMWriter d4Writer = new DOMWriter();
72
			Document d = d4Writer.write(identification.getResponse());
73

  
74
			return verifyIdentify(d);
75
		} catch (Exception e) {
76
			LOGGER.debug("Error verifying identify response", e);
77
			throw e;
78
		}
79
	}
80

  
81
	private static boolean verifyIdentify(Document doc) throws XPathExpressionException {
82
		NamespaceContext ctx = new NamespaceContext() {
83
			public String getNamespaceURI(String prefix) {
84
				String uri;
85
				if (prefix.equals("oai"))
86
					uri = "http://www.openarchives.org/OAI/2.0/";
87
				else
88
					uri = null;
89
				return uri;
90
			}
91

  
92
			// Dummy implementation - not used!
93
			public Iterator<String> getPrefixes(String val) {
94
				return null;
95
			}
96

  
97
			// Dummy implemenation - not used!
98
			public String getPrefix(String uri) {
99
				return null;
100
			}
101
		};
102

  
103
		// Now the XPath expression
104

  
105
		String xpathStr = "//oai:OAI-PMH/oai:Identify";
106
		XPathFactory xpathFact = XPathFactory.newInstance();
107
		XPath xpath = xpathFact.newXPath();
108
		xpath.setNamespaceContext(ctx);
109
		String result = xpath.evaluate(xpathStr, doc);
110

  
111
		return (result != null && !result.equals(""));
112
	}
113

  
114
	private static void disableSslVerification() {
115
		try
116
		{
117
			LOGGER.debug("disabling ssl verification");
118
			// Create a trust manager that does not validate certificate chains
119
			TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
120
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
121
					return null;
122
				}
123
				public void checkClientTrusted(X509Certificate[] certs, String authType) {
124
				}
125
				public void checkServerTrusted(X509Certificate[] certs, String authType) {
126
				}
127
			}
128
			};
129

  
130
			// Install the all-trusting trust manager
131
			SSLContext sc = SSLContext.getInstance("SSL");
132
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
133
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
134

  
135
			// Create all-trusting host name verifier
136
			HostnameVerifier allHostsValid = new HostnameVerifier() {
137
				public boolean verify(String hostname, SSLSession session) {
138
					return true;
139
				}
140
			};
141

  
142
			// Install the all-trusting host verifier
143
			HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
144
		} catch (NoSuchAlgorithmException e) {
145
			LOGGER.error("disabling ssl verification", e);
146
		} catch (KeyManagementException e) {
147
			LOGGER.error("error while disabling ssl verification", e);
148
		}
149
	}
150
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/utils/EmailUtilsImpl.java
1
package eu.dnetlib.repo.manager.server.utils;
2

  
3
import eu.dnetlib.domain.functionality.UserProfile;
4
import eu.dnetlib.repo.manager.server.config.CascadingPropertyLoader;
5
import eu.dnetlib.utils.MailLibrary;
6
import org.apache.log4j.Logger;
7
import org.springframework.beans.factory.annotation.Autowired;
8
import org.springframework.beans.factory.annotation.Value;
9
import org.springframework.stereotype.Component;
10

  
11
import java.io.PrintWriter;
12
import java.io.StringWriter;
13
import java.io.Writer;
14
import java.util.ArrayList;
15
import java.util.List;
16

  
17
/**
18
 * Created by nikonas on 11/12/15.
19
 */
20

  
21
@Component
22
public class EmailUtilsImpl implements EmailUtils {
23

  
24
    private static Logger LOGGER = Logger.getLogger(EmailUtilsImpl.class);
25

  
26
    private List<String> specialRecipients = new ArrayList<String>();
27
    private boolean override = false, logonly = false;
28
    private String overrideEmail = null, from = null;
29

  
30
    @Autowired
31
    private MailLibrary mailLibrary;
32

  
33
    @Autowired
34
    private CascadingPropertyLoader pLoader;
35

  
36
    @Value("${services.repo-manager.baseUrl}")
37
    private String baseUrl;
38

  
39
    @Value("${services.repo-manager.adminEmail}")
40
    private String adminEmail;
41

  
42
    @Override
43
    public void sendActivationEmail(UserProfile user, String activationId) throws Exception {
44
        try {
45

  
46
            this.sendMail(user.getEmail(), getEmailProperty("user.registration.mail.subject"), "Dear " + user.getFirstname() + " " + user.getLastname() + ",\n" + getEmailProperty("user.registration.mail.message") + ": " + this.baseUrl + "?activationId=" + activationId + "#activateAccount", false, null);
47

  
48
        } catch (Exception e) {
49
            LOGGER.error("Error while sending activation email to user: " + user.getEmail(), e);
50
            throw e;
51
        }
52
    }
53

  
54
    @Override
55
    public void sendResetPasswordEmail(String email, String securityCode) throws Exception {
56
        try {
57

  
58
            this.sendMail(email, getEmailProperty("user.forgotPassword.mail.Subject"), getEmailProperty("user.forgotPassword.mail.Body1") + ": " + this.baseUrl + "?securityCode=" + securityCode + "#resetPassword" + "\n\n" + getEmailProperty("user.forgotPassword.mail.Body2") + ": " + securityCode, false, null);
59

  
60
        } catch (Exception e) {
61
            LOGGER.error("Error while sending activation email to user: " + email, e);
62
            throw e;
63
        }
64
    }
65

  
66

  
67
    @Override
68
    public void reportException(Exception exception) {
69
        Writer writer = new StringWriter();
70
        PrintWriter printWriter = new PrintWriter(writer);
71
        exception.printStackTrace(printWriter);
72

  
73
        List<String> recipients = new ArrayList<String>();
74

  
75
        try {
76
            recipients.add(this.adminEmail);
77
            String message = "An exception has occurred:\n"+writer.toString();
78
            String subject = "Automatic Bug Report";
79
            this.sendMail(recipients, subject, message, false, null);
80
        } catch (Exception e) {
81
            LOGGER.error("Error sending error report", e);
82
        }
83
    }
84

  
85
    private void sendMail(String email, String subject, String message, boolean sendToSpecial, List<String> repoAdminMails) throws Exception {
86
        ArrayList<String> to = new ArrayList<String>();
87
        to.add(email);
88
        this.sendMail(to,subject,message,sendToSpecial,repoAdminMails);
89
    }
90

  
91
    private void sendMail(List<String> recipients, String subject, String message, boolean sendToSpecial, List<String> repoAdminMails) throws Exception {
92

  
93
        try {
94
            if (sendToSpecial) {
95
                recipients.addAll(this.specialRecipients);
96
            }
97

  
98
            if (repoAdminMails != null)
99
                recipients.addAll(repoAdminMails);
100

  
101
            if (this.override) {
102
                recipients.clear();
103
                recipients.add(overrideEmail);
104
            }
105
            if (!logonly)
106
                mailLibrary.sendEmail(recipients.toArray(new String[]{}), subject, message);
107
            LOGGER.debug("Sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message);
108
        } catch (Exception e) {
109
            LOGGER.error("Error sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message, e);
110
            throw new Exception(e);
111
        }
112
    }
113

  
114
    private String getEmailProperty(String key) {
115
        return pLoader.getProperties().getProperty(key);
116
    }
117

  
118
    public void setSpecialRecipients(String specialRecipients) {
119
        String[] recps = specialRecipients.split(",");
120

  
121
        for (String recp : recps) {
122
            recp = recp.trim();
123

  
124
            this.specialRecipients.add(recp);
125
        }
126
    }
127

  
128

  
129
    public void setOverride(boolean override) {
130
        this.override = override;
131
    }
132

  
133
    public void setOverrideEmail(String overrideEmail) {
134
        this.overrideEmail = overrideEmail;
135
    }
136

  
137
    public String getFrom() {
138
        return from;
139
    }
140

  
141
    public void setFrom(String from) {
142
        this.from = from;
143
    }
144

  
145
    public boolean isLogonly() {
146
        return logonly;
147
    }
148

  
149
    public void setLogonly(boolean logonly) {
150
        this.logonly = logonly;
151
    }
152

  
153

  
154
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/utils/LocalVocabularies.java
1
package eu.dnetlib.repo.manager.server.utils;
2

  
3
import com.google.gwt.user.client.rpc.IsSerializable;
4
import eu.dnetlib.repo.manager.shared.Timezone;
5
import org.apache.log4j.Logger;
6
import org.springframework.beans.factory.annotation.Configurable;
7

  
8
import java.io.BufferedReader;
9
import java.io.InputStreamReader;
10
import java.util.ArrayList;
11
import java.util.List;
12

  
13
@Configurable
14
public class LocalVocabularies implements IsSerializable {
15
	
16
	private static Logger logger = Logger.getLogger(LocalVocabularies.class);
17

  
18
	public static String loggedInField = "LOGGED_IN_FIELD";
19
	
20
	public static List<String> typologies;
21
	public static List<String> countries;
22
	public static List<Timezone> timezones;
23

  
24
	public static final String MODE_LOCAL = "local";
25
	public static final String MODE_DNET = "dnet";
26
	public static final String MODE_LDAP = "ldap";
27
	
28
	public static final String ENV_LAREFERENCIA = "lareferencia";
29
	public static final String ENV_MINCYT = "mincyt";
30
	public static final String ENV_OPENAIRE_PRODUCTION = "openaire-production";
31
	public static final String ENV_OPENAIRE_BETA = "openaire-beta";
32
	public static final String ENV_DEVELOPMENT = "development";
33

  
34
	static {
35

  
36
		typologies = new ArrayList<String>();
37
		countries = new ArrayList<String>();
38
		timezones = new ArrayList<Timezone>();
39
		
40
		try {
41
			logger.debug("loading typologies, countries, timezones and other constants");
42

  
43
			BufferedReader br = new BufferedReader(new InputStreamReader(LocalVocabularies.class.getResourceAsStream("/eu/dnetlib/repo/manager/server/utils/typologies.txt")));
44
			String line;
45
			while((line = br.readLine()) != null) {
46
				typologies.add(line.trim());
47
			}
48
			br.close();
49

  
50
			br = new BufferedReader(new InputStreamReader(LocalVocabularies.class.getResourceAsStream("/eu/dnetlib/repo/manager/server/utils/countries.txt")));
51
			while((line = br.readLine()) != null) {
52
				countries.add(line.trim());
53
			}
54
			br.close();
55
			
56
			br = new BufferedReader(new InputStreamReader(LocalVocabularies.class.getResourceAsStream("/eu/dnetlib/repo/manager/server/utils/timezones.txt")));
57
			while((line = br.readLine()) != null) {
58
				String parts[] = line.split("\t");
59
				if(parts.length < 2 || parts.length > 2)
60
					continue;
61
				String name = parts[1].trim();
62
				double offset = Double.parseDouble(parts[0].trim());
63
				Timezone timezone = new Timezone(name, offset);
64
				timezones.add(timezone);
65
			}
66
			br.close();
67
			
68
		} catch (Exception e) {
69
			logger.error("Error loading typologies, countries, timezones and other constants", e);
70
		}
71
	}
72

  
73
}
74

  
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/services/UserServiceImpl.java
1
package eu.dnetlib.repo.manager.server.services;
2

  
3
import eu.dnetlib.domain.functionality.UserProfile;
4
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
5
import eu.dnetlib.repo.manager.client.services.UserService;
6
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
7
import eu.dnetlib.repo.manager.shared.Tuple;
8
import eu.dnetlib.repo.manager.shared.UserAccessException;
9
import eu.dnetlib.users.UserApi;
10
import org.apache.log4j.Logger;
11
import org.springframework.beans.factory.annotation.Autowired;
12
import org.springframework.stereotype.Service;
13

  
14
import javax.servlet.ServletConfig;
15
import javax.servlet.ServletException;
16
import java.util.ArrayList;
17
import java.util.Arrays;
18
import java.util.List;
19
import java.util.regex.Pattern;
20

  
21
/**
22
 * Created by nikonas on 12/7/15.
23
 */
24
@Service("userService")
25
public class UserServiceImpl extends SpringGwtRemoteServiceServlet implements UserService {
26

  
27
    private static final Logger LOGGER = Logger
28
            .getLogger(UserServiceImpl.class);
29

  
30
    @Autowired
31
    private UserApi userAPI;
32

  
33
    @Autowired
34
    private EmailUtils emailUtils;
35

  
36

  
37
    public void init(ServletConfig config) throws ServletException {
38

  
39
        LOGGER.info("initializing user service impl ");
40
        super.init(config);
41

  
42
    }
43

  
44
    @Override
45
    public Tuple<UserProfile, String> login(String email_username, String password) throws UserAccessException {
46
        LOGGER.info("Checking credentials for user " + email_username);
47
        try {
48

  
49
            String email = email_username;
50

  
51
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
52
            if (!rfc2822.matcher(email_username.trim().toLowerCase()).matches()) {
53
                LOGGER.debug("user logged in using username");
54
                email = this.userAPI.getEmailFromUsername(email_username);
55
            }
56
            if (email == null) {
57
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
58
            }
59
            if (!this.userAPI.userExists(email)) {
60
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
61
            }
62
            if (!this.userAPI.isUserActivated(email)) {
63
                throw new UserAccessException("login.notActivated", UserAccessException.ErrorCode.NOT_ACTIVATED);
64
            }
65
            if (!this.userAPI.correctCreds(email, password)) {
66
                throw new UserAccessException("login.InvalidPassword", UserAccessException.ErrorCode.INVALID_PASSWORD);
67
            }
68

  
69
            UserProfile userProfile = this.userAPI.getUser(email);
70
            String role = "";
71

  
72
            String[] adminEmails = new String[] {"stefania.martziou@gmail.com" , "antleb@di.uoa.gr", "ant.lebesis@gmail.com", "natalia@di.uoa.gr", "pedroprincipe@sdum.uminho.pt", "dpierrakos@gmail.com", "jochen.schirrwagen@uni-bielefeld.de", "aenne.loehden@uni-bielefeld.de"};
73
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
74
                role = "admin";
75

  
76
            return new Tuple<>(userProfile, role);
77

  
78
        } catch (Exception e) {
79
            LOGGER.error("An error occurred while checking credentials for user " + email_username, e);
80
            emailUtils.reportException(e);
81

  
82
            if (e instanceof UserAccessException) {
83
                throw (UserAccessException) e;
84
            }
85
            else {
86
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
87
            }
88
        }
89

  
90
    }
91

  
92
    @Override
93
    public Tuple<UserProfile, String> getUserByEmail(String email) throws UserAccessException {
94
        LOGGER.info("Getting user with email " + email);
95
        try {
96

  
97
            UserProfile userProfile = this.userAPI.getUser(email);
98
            String role = "";
99

  
100
            String[] adminEmails = new String[] {"stefania.martziou@gmail.com" , "antleb@di.uoa.gr", "ant.lebesis@gmail.com", "natalia@di.uoa.gr", "pedroprincipe@sdum.uminho.pt", "dpierrakos@gmail.com", "jochen.schirrwagen@uni-bielefeld.de", "aenne.loehden@uni-bielefeld.de"};
101
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
102
                role = "admin";
103

  
104
            return new Tuple<>(userProfile, role);
105

  
106
        } catch (Exception e) {
107
            LOGGER.error("An error occurred while getting user with email " + email, e);
108
            emailUtils.reportException(e);
109

  
110
            throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
111
        }
112
    }
113

  
114
    @Override
115
    public void register(UserProfile userProfile) throws UserAccessException {
116

  
117
        try {
118
            LOGGER.info("Registering user " + userProfile.getEmail());
119

  
120
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
121
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
122
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
123
            }
124

  
125
            if (this.userAPI.usernameExists(userProfile.getUsername())) {
126
                throw new UserAccessException("login.usernameAlreadyExists", UserAccessException.ErrorCode.USERNAME_ALREADY_EXISTS);
127
            }
128
            if (this.userAPI.userExists(userProfile.getEmail())) {
129
                throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
130
            }
131

  
132
//            String activationId = "TEST";
133
            String activationId = this.userAPI.addUser(userProfile.getUsername(), userProfile.getEmail(), userProfile.getPassword(), userProfile.getFirstname(), userProfile.getLastname(), userProfile.getInstitution());
134

  
135
            emailUtils.sendActivationEmail(userProfile, activationId);
136

  
137
        } catch (Exception e) {
138
            LOGGER.error("Error while registering user " + userProfile.getEmail(), e);
139
            emailUtils.reportException(e);
140

  
141
            if (e instanceof UserAccessException)
142
                throw (UserAccessException) e;
143
            else
144
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
145
        }
146

  
147
    }
148

  
149
    @Override
150
    public void activateUser(String activationId) throws UserAccessException {
151
        try {
152
            LOGGER.info("Activating user with activation with activation id " + activationId);
153

  
154
            if (!this.userAPI.activateUser(activationId))
155
                throw new UserAccessException("registration.okAccountAlreadyActivation", UserAccessException.ErrorCode.ALREADY_ACTIVATED);
156
        } catch (Exception e) {
157
            LOGGER.error("Error while activating user account with activation id " + activationId, e);
158
            emailUtils.reportException(e);
159

  
160
            if (e instanceof UserAccessException)
161
                throw (UserAccessException) e;
162
            else
163
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
164
        }
165
    }
166

  
167
    @Override
168
    public void updateUser(UserProfile userProfile) throws UserAccessException {
169
        try {
170
            LOGGER.info("Editing user " + userProfile.getUsername());
171
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
172
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
173
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
174
            }
175

  
176
            String currentEmail = this.userAPI.getEmailFromUsername(userProfile.getUsername());
177
            if (!userProfile.getEmail().equalsIgnoreCase(currentEmail)) {
178
                if (this.userAPI.userExists(userProfile.getEmail())) {
179
                    throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
180
                }
181
            }
182

  
183
            this.userAPI.editUser(userProfile);
184

  
185
        } catch (Exception e) {
186
            LOGGER.error("Error while editing user " + userProfile.getUsername(), e);
187
            if (e instanceof UserAccessException)
188
                throw (UserAccessException) e;
189
            else
190
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
191
        }
192
    }
193

  
194
    @Override
195
    public void prepareResetPassword(String email) throws UserAccessException {
196

  
197
        try {
198
            LOGGER.debug("Sending password recovery to user " + email);
199
            if (!this.userAPI.userExists(email)) {
200
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
201
            }
202
            List<String> to = new ArrayList<String>();
203
            to.add(email);
204
            String securityCode = this.userAPI.prepareResetPassword(email);
205

  
206
            emailUtils.sendResetPasswordEmail(email, securityCode);
207

  
208
        } catch (Exception e) {
209
            LOGGER.error("Error while sending password recovery to user " + email, e);
210
            emailUtils.reportException(e);
211

  
212
            if (e instanceof UserAccessException)
213
                throw (UserAccessException) e;
214
            else
215
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
216
        }
217
    }
218

  
219
    @Override
220
    public void resetPassword(String securityCode, String password) throws UserAccessException {
221
        try {
222
            LOGGER.debug("Reseting password with security code " + securityCode);
223

  
224
            if (securityCode.length() == 0) {
225
                throw new UserAccessException("resetPassword.wrongSecurityCode", UserAccessException.ErrorCode.WRONG_SECURITY_CODE);
226
            }
227

  
228
            this.userAPI.resetPassword(securityCode, password);
229

  
230
        } catch (Exception e) {
231
            LOGGER.error("Error while reseting password with security code " + securityCode);
232
            emailUtils.reportException(e);
233

  
234
            if (e instanceof UserAccessException)
235
                throw (UserAccessException) e;
236
            else
237
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
238
        }
239
    }
240

  
241
    @Override
242
    public void resendActivation(String email) throws UserAccessException {
243

  
244
    }
245

  
246
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/services/RepositoryServiceImpl.java
1
package eu.dnetlib.repo.manager.server.services;
2

  
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.unboundid.util.Base64;
5
import eu.dnetlib.domain.data.Repository;
6
import eu.dnetlib.domain.data.RepositoryInterface;
7
import eu.dnetlib.domain.enabling.Vocabulary;
8
import eu.dnetlib.domain.functionality.UserProfile;
9
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
10
import eu.dnetlib.repo.manager.client.services.RepositoryService;
11
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
12
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
13
import eu.dnetlib.repo.manager.shared.*;
14
import eu.dnetlib.repos.RepoApi;
15
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
16
import org.apache.commons.lang.StringEscapeUtils;
17
import org.apache.commons.lang.WordUtils;
18
import org.apache.log4j.Logger;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.beans.factory.annotation.Value;
21
import org.springframework.dao.EmptyResultDataAccessException;
22
import org.springframework.scheduling.annotation.Scheduled;
23
import org.springframework.stereotype.Service;
24

  
25
import javax.annotation.PostConstruct;
26
import java.io.IOException;
27
import java.text.Normalizer;
28
import java.util.*;
29
import java.util.concurrent.ConcurrentHashMap;
30

  
31
/**
32
 * Created by nikonas on 12/8/15.
33
 */
34
@SuppressWarnings("serial")
35
@Service("repositoryService")
36
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
37

  
38
    private static final Logger LOGGER = Logger
39
            .getLogger(RepositoryServiceImpl.class);
40

  
41
    @Autowired
42
    private RepoApi repoAPI;
43

  
44
    @Autowired
45
    private EmailUtils emailUtils;
46

  
47
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
48

  
49
    @Autowired
50
    private VocabularyLoader vocabularyLoader;
51

  
52
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
53

  
54
    @Value("${services.repo-manager.repository.testing.mode}")
55
    private boolean testingMode;
56

  
57
    @Autowired
58
    private PiwikDAO piwikDAO;
59

  
60
    @Value("${services.repomanager.analyticsURL}")
61
    private String analyticsURL;
62

  
63
    private static final String PIWIK_SCRIPT = StringEscapeUtils.escapeHtml("<!-- Piwik -->\n" +
64
            "<script type=\"text/javascript\">\n" +
65
            "\tvar _paq = _paq || [];\n" +
66
            "\t_paq.push(['enableLinkTracking']);\n" +
67
            "\t(function() {\n" +
68
            "\t\tvar u=\"//analytics.openaire.eu/\";\n" +
69
            "\t\t_paq.push(['setTrackerUrl', u+'piwik.php']);\n" +
70
            "\t\t_paq.push(['setSiteId', $$$]);\n" +
71
            "\t\t<% if(handle != null){%>\n" +
72
            "\t\t\t_paq.push(['setCustomVariable', 1, 'oaipmhID',\"oai:<%= baseUrl %>:<%=handle %>\", 'page']);\n" +
73
            "\t\t\t_paq.push(['trackPageView']);\n" +
74
            "\t\t<}>\n" +
75
            "\t\tvar d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n" +
76
            "\t\tg.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);\n" +
77
            "\t})();\n" +
78
            "</script>\n" +
79
            "<noscript>\n" +
80
            "\t<p>\n" +
81
            "\t\t<img src=\"//analytics.openaire.eu/piwik.php?idsite=47\" style=\"border:0;\" alt=\"\" />\n" +
82
            "\t</p>\n" +
83
            "</noscript>\n" +
84
            "<!— End Piwik Code —>");
85

  
86
    @PostConstruct
87
    public void init() {
88
        this.loadVocabularies();
89
    }
90

  
91
    @Override
92
    public Tuple<List<Repository>, List<Repository>> getRepositoriesByCountry(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
93
        try {
94
            if (testingMode)
95
                return this.getRepositoriesByCountryTesting(country, mode, includeUnknownCountries);
96
            LOGGER.debug("Getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
97

  
98
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
99
            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
100
            if (reposList == null) {
101
                retTuple.setFirst(new ArrayList<Repository>());
102
//                if (!includeUnknownCountries) {
103
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
104
//                }
105
            } else {
106
                retTuple.setFirst(reposList);
107
            }
108

  
109
            if (includeUnknownCountries) {
110
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
111
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
112
                List<Repository> totalList = new ArrayList<Repository>();
113
                if (withoutCountryList != null)
114
                    totalList.addAll(withoutCountryList);
115
                if (unknownCountryList != null)
116
                    totalList.addAll(unknownCountryList);
117
                retTuple.setSecond(totalList);
118
            }
119

  
120
            return retTuple;
121

  
122
        } catch (Exception e) {
123
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
124
            if (e instanceof RepositoryServiceException) {
125
                throw (RepositoryServiceException) e;
126
            } else {
127
                emailUtils.reportException(e);
128
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
129
            }
130
        }
131
    }
132

  
133
    @Override
134
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
135
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
136
    }
137

  
138
    @Override
139
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
140
        try {
141
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
142
            DatasourcesCollection retDatasources = new DatasourcesCollection();
143
            retDatasources.setDatasourcesOfUser(this.repoAPI.getRepositoriesOfUser(userEmail, false));
144
            if (includeShared) {
145
                //TODO create dao to save-get shared datasourcesIDs
146
                List<String> sharedDatasourceIds = new ArrayList<String>();
147
                retDatasources.setSharedDatasources(this.repoAPI.getReposByIds(sharedDatasourceIds));
148
            }
149

  
150
            if (includeByOthers)
151
                retDatasources.setDatasourcesOfUser(this.repoAPI.getRepositoriesOfUser(userEmail, true));
152

  
153
            return retDatasources;
154

  
155
        } catch (Exception e) {
156
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
157
            if (e instanceof RepositoryServiceException) {
158
                throw (RepositoryServiceException) e;
159
            } else {
160
                emailUtils.reportException(e);
161
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
162
            }
163
        }
164
    }
165

  
166
    @Override
167
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
168
        try {
169
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
170
            List<String> retRepos = new ArrayList<String>();
171

  
172
            retRepos.addAll(this.repoAPI.getUrlsOfRepos(userEmail, false));
173

  
174
            return retRepos;
175

  
176
        } catch (Exception e) {
177
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
178
            if (e instanceof RepositoryServiceException) {
179
                throw (RepositoryServiceException) e;
180
            } else {
181
                emailUtils.reportException(e);
182
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
183
            }
184
        }
185
    }
186

  
187
    @Override
188
    public Repository getRepository(String repoId) throws RepositoryServiceException {
189
        try {
190
            LOGGER.debug("Getting repository with id: " + repoId);
191

  
192
            Repository repo = this.repoAPI.getRepository(repoId);
193
            if (repo != null) {
194
                for (RepositoryInterface iFace : repo.getInterfaces()) {
195
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
196
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
197
                        if (iFace.getCompliance().equals("notCompatible"))
198
                            iFace.setComplianceName("not compatible");
199
                    }
200
                }
201
            } else
202
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
203
            return repo;
204

  
205
        } catch (Exception e) {
206
            LOGGER.error("Error while getting repository with id: " + repoId, e);
207
            if (e instanceof RepositoryServiceException) {
208
                throw (RepositoryServiceException) e;
209
            } else {
210
                emailUtils.reportException(e);
211
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
212
            }
213
        }
214
    }
215

  
216
    @Override
217
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
218
        try {
219
            LOGGER.debug("Getting countries");
220
            List<String> countries = new ArrayList<String>();
221

  
222
            Map<String, String> countriesMap = new TreeMap<String, String>();
223

  
224
            if (existingOnly) {
225
                LOGGER.debug("using the repositories map");
226
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
227
            } else {
228
                LOGGER.debug("using \"dnet:countries\" vocabulary");
229
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
230
            }
231

  
232
            for (String country : countries) {
233
                countriesMap.put(country, WordUtils.capitalizeFully(country));
234
            }
235

  
236
            return countriesMap;
237

  
238
        } catch (Exception e) {
239
            LOGGER.error("Error while getting getting countries", e);
240
            if (e instanceof RepositoryServiceException) {
241
                throw (RepositoryServiceException) e;
242
            } else {
243
                emailUtils.reportException(e);
244
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
245
            }
246
        }
247
    }
248

  
249
    @Override
250
    public Map<String, String> getCountries() throws RepositoryServiceException {
251
        return this.getCountries(false, null);
252
    }
253

  
254
    @Override
255
    public List<Timezone> getTimezones() throws RepositoryServiceException {
256
        try {
257
            LOGGER.debug("Getting timezones from file");
258
            return LocalVocabularies.timezones;
259
        } catch (Exception e) {
260
            LOGGER.error("Error while getting timezones from file", e);
261
            emailUtils.reportException(e);
262
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
263
        }
264

  
265
    }
266

  
267
    @Override
268
    public List<String> getTypologies() throws RepositoryServiceException {
269
        try {
270
            LOGGER.debug("Getting typologies from file");
271
            return LocalVocabularies.typologies;
272
        } catch (Exception e) {
273
            LOGGER.error("Error while getting typologies from file", e);
274
            emailUtils.reportException(e);
275
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
276
        }
277
    }
278

  
279
    @Override
280
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
281
        try {
282
            LOGGER.debug("Getting datasource classes for mode: " + mode);
283
            Map<String, String> retMap = new HashMap<String, String>();
284

  
285
            for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) {
286
                if (mode.equalsIgnoreCase("aggregator")) {
287
                    if (entry.getKey().contains("aggregator"))
288
                        retMap.put(entry.getKey(), entry.getValue());
289
                } else if (mode.equalsIgnoreCase("journal")) {
290
                    if (entry.getKey().contains("journal"))
291
                        retMap.put(entry.getKey(), entry.getValue());
292
                } else if (mode.equalsIgnoreCase("opendoar")) {
293
                    if (entry.getKey().contains("pubsrepository"))
294
                        retMap.put(entry.getKey(), entry.getValue());
295
                } else if (mode.equalsIgnoreCase("re3data")) {
296
                    if (entry.getKey().contains("datarepository"))
297
                        retMap.put(entry.getKey(), entry.getValue());
298
                }
299
            }
300
            return retMap;
301

  
302
        } catch (Exception e) {
303
            LOGGER.error("Error while getting datasource classes for mode: " + mode, e);
304
            emailUtils.reportException(e);
305
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
306
        }
307
    }
308

  
309
    @Override
310
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
311
        try {
312
            LOGGER.debug("Getting compatibility classes for mode: " + mode);
313
            Map<String, String> retMap = new HashMap<String, String>();
314

  
315
            Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
316
            boolean foundData = false;
317
            for (Map.Entry<String, String> entry : compatibilityClasses.entrySet()) {
318
                if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_ALL))
319
                    return compatibilityClasses;
320
                else if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA)) {
321
                    if (entry.getKey().matches("^openaire[1-9].0_data$")) {
322
                        retMap.put(entry.getKey(), entry.getValue());
323
                        foundData = true;
324
                    }
325
                } else {
326
                    if (entry.getKey().matches("^openaire[1-9].0$") || entry.getKey().equals("driver"))
327
                        retMap.put(entry.getKey(), entry.getValue());
328
                }
329
            }
330

  
331
            //TODO TO BE REMOVED WHEN VOCABULARIES ARE UPDATED
332
            if (mode.equalsIgnoreCase(Constants.REPOSITORY_MODE_RE3DATA) && !foundData)
333
                retMap.put("openaire2.0_data", "OpenAIRE Data (funded, referenced datasets)");
334

  
335
            return retMap;
336

  
337
        } catch (Exception e) {
338
            LOGGER.error("Error while getting compatibility classes for mode: " + mode, e);
339
            emailUtils.reportException(e);
340
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
341
        }
342
    }
343

  
344
    @Override
345
    public void storeRepository(Repository repo, String mode) throws RepositoryServiceException {
346

  
347
        try {
348
            LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
349

  
350
            List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
351

  
352
            //TODO update map
353
            repo.setCountryCode(getCountryCode(repo.getCountryName()));
354

  
355
            repo.setActivationId(UUID.randomUUID().toString());
356
//            repo.setRegisteredBy((String) session.get(LocalVocabularies.loggedInField));
357

  
358
            if (mode.equals("opendoar") || mode.equals("re3data")) {
359
                repo.setProvenanceActionClass("sysimport:crosswalk:entityregistry");
360
            } else if (mode.equals("journal")) {
361
                repo.setProvenanceActionClass("user:insert");
362
                repo.setCollectedFrom("infrastruct_::openaire");
363
                if (repo.getIssn() != null && repo.getIssn().length() == 0)
364
                    repo.setIssn(Base64.encode(repo.getOfficialName()).substring(0, 8));
365
                repo.setId("openaire____::issn" + repo.getIssn());
366
                repo.setNamespacePrefix("issn" + repo.getIssn());
367
            } else if (mode.equals("aggregator")) {
368
                repo.setProvenanceActionClass("user:insert");
369
                repo.setCollectedFrom("infrastruct_::openaire");
370
                repo.setId("openaire____::" + Base64.encode(repo.getOfficialName()));
371
                repo.setNamespacePrefix(Normalizer.normalize(repo.getOfficialName().toLowerCase().replace(" ", "_"), Normalizer.Form.NFD).replaceAll("[^a-zA-Z0-9]", ""));
372
                if (repo.getNamespacePrefix().length() > 12) {
373
                    repo.setNamespacePrefix(repo.getNamespacePrefix().substring(0, 12));
374
                } else {
375
                    while (repo.getNamespacePrefix().length() < 12)
376
                        repo.setNamespacePrefix(repo.getNamespacePrefix().concat("_"));
377
                }
378
            }
379

  
380
            this.repoAPI.storeRepository(repo, mode, interfacesToRegister);
381

  
382
        } catch (Exception e) {
383
            LOGGER.error("Error while Storing repository with name: " + repo.getOfficialName(), e);
384
            if (e instanceof RepositoryServiceException) {
385
                throw (RepositoryServiceException) e;
386
            } else {
387
                emailUtils.reportException(e);
388
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
389
            }
390
        }
391
    }
392

  
393
    @Override
394
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
395
        try {
396
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
397
            this.repoAPI.updateRepositoryInformation(repo);
398

  
399
        } catch (Exception e) {
400
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
401
            if (e instanceof RepositoryServiceException) {
402
                throw (RepositoryServiceException) e;
403
            } else {
404
                emailUtils.reportException(e);
405
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
406
            }
407
        }
408
    }
409

  
410
    @Override
411
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
412
        try {
413
            LOGGER.debug("updating interface with id: " + iFace.getId());
414
            RepositoryInterface retIface = null;
415
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
416
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
417

  
418
            return retIface;
419
        } catch (Exception e) {
420
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
421
            if (e instanceof RepositoryServiceException) {
422
                throw (RepositoryServiceException) e;
423
            } else {
424
                emailUtils.reportException(e);
425
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
426
            }
427
        }
428
    }
429

  
430
    @Override
431
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
432
        try {
433
            LOGGER.debug("inserting interface with id: " + iFace.getId());
434
            RepositoryInterface retIface = null;
435
            retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
436
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
437
            return retIface;
438

  
439
        } catch (Exception e) {
440
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
441
            if (e instanceof RepositoryServiceException) {
442
                throw (RepositoryServiceException) e;
443
            } else {
444
                emailUtils.reportException(e);
445
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
446
            }
447
        }
448
    }
449

  
450
    @Override
451
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
452
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
453
        iFaces.add(iFace);
454
        this.deleteInterfaces(repoId, iFaces, datatype);
455
    }
456

  
457
    @Override
458
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
459
        try {
460
            LOGGER.debug("deleting interfaces of repo: " + repoId);
461
            this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
462

  
463
        } catch (Exception e) {
464
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
465
            if (e instanceof RepositoryServiceException) {
466
                throw (RepositoryServiceException) e;
467
            } else {
468
                emailUtils.reportException(e);
469
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
470
            }
471
        }
472

  
473
    }
474

  
475
    @Override
476
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
477
        try {
478
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
479
            DatasourceVocabularies vocs = new DatasourceVocabularies();
480
            vocs.setCountries(this.getCountries());
481
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
482
            vocs.setTimezones(this.getTimezones());
483
            vocs.setTypologies(this.getTypologies());
484
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
485

  
486
            return vocs;
487

  
488
        } catch (Exception e) {
489
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
490
            emailUtils.reportException(e);
491
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
492
        }
493
    }
494

  
495
    private Tuple<List<Repository>, List<Repository>> getRepositoriesByCountryTesting(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
496
        try {
497
            LOGGER.debug("Getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
498

  
499
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
500
            List<Repository> reposList = new ArrayList<Repository>();
501
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
502
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
503
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
504
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
505
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
506

  
507
            retTuple.setFirst(reposList);
508

  
509
            if (includeUnknownCountries) {
510
                List<Repository> totalList = new ArrayList<Repository>();
511
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
512
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
513
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
514

  
515
                retTuple.setSecond(totalList);
516
            }
517

  
518
            return retTuple;
519

  
520
        } catch (Exception e) {
521
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
522
            if (e instanceof RepositoryServiceException) {
523
                throw (RepositoryServiceException) e;
524
            } else {
525
                emailUtils.reportException(e);
526
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
527
            }
528
        }
529
    }
530

  
531
    @Override
532
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
533
        try {
534
            LOGGER.debug("Getting latest update date of list: " + mode);
535
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
536

  
537
        } catch (Exception e) {
538
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
539
            emailUtils.reportException(e);
540
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
541
        }
542
    }
543

  
544
    @Override
545
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
546
        try {
547
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
548
        } catch (EmptyResultDataAccessException e) {
549
            return null;
550
        }
551
    }
552

  
553
    @Override
554
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
555

  
556
        String URL = analyticsURL + "siteName=" + repository.getOfficialName() + "&url=" + repository.getWebsiteUrl();
557

  
558
        //TODO uncomment when we can communitcate with the piwik (create site)
559
//        try {
560
//            Map<String, Object> map = new ObjectMapper().readValue(URL, Map.class);
561
//
562
//            String siteId = (String) map.get("value");
563

  
564
            String siteId = new Random(new Date().getTime()).nextInt(200) + "";
565
            String authenticationToken = new Random(new Date().getTime()).nextInt(1000000000) + "";
566

  
567
            PiwikInfo piwikInfo = new PiwikInfo();
568
            piwikInfo.setRepositoryId(repository.getId());
569
            piwikInfo.setRepositoryName(repository.getOfficialName());
570
            piwikInfo.setCountry(repository.getCountryName());
571
            piwikInfo.setSiteId(siteId);
572
            piwikInfo.setAuthenticationToken(authenticationToken);
573
            piwikInfo.setRequestorEmail(requestor.getEmail());
574
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
575
            piwikInfo.setApproved(false);
576

  
577
            this.piwikDAO.savePiwikInfo(piwikInfo);
578

  
579
            //TODO send this in an email as well to the usage stats admin list
580

  
581
//        } catch (IOException e) {
582
//            LOGGER.error("Error while creating piwik site", e);
583
//            emailUtils.reportException(e);
584
//            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
585
//        }
586
    }
587

  
588
    @Override
589
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
590
        try {
591
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
592

  
593
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
594
            return piwikScript;
595

  
596
        } catch (EmptyResultDataAccessException e) {
597
            return null;
598
        }
599
    }
600

  
601
    @Override
602
    public List<PiwikInfo> getPiwikSitesForRepositories() throws RepositoryServiceException {
603
        try {
604

  
605
            List<PiwikInfo> piwikInfos = new ArrayList<>();
606
            piwikInfos = this.piwikDAO.getPiwikSitesForRepos();
607

  
608
            return piwikInfos;
609

  
610
        } catch (EmptyResultDataAccessException e) {
611
            LOGGER.error("Error while getting list of piwik sites: ", e);
612
            emailUtils.reportException(e);
613
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
614
        }
615
    }
616

  
617
    @Override
618
    public void approvePiwikSite(String repositoryId) throws RepositoryServiceException {
619
        try {
620

  
621
            this.piwikDAO.approvePiwikSite(repositoryId);
622

  
623
        } catch (EmptyResultDataAccessException e) {
624
            LOGGER.error("Error while approving piwik site: ", e);
625
            emailUtils.reportException(e);
626
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
627
        }
628
    }
629

  
630
    private String getCountryCode(String countryName) {
631
        Vocabulary countries = this.getVocabulary("dnet:countries");
632

  
633
        return countries.getEncoding(countryName);
634
    }
635

  
636
    private String getDatasourceClassCode(String datasourceClassName) {
637
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
638

  
639
        return datasourceClasses.getEncoding(datasourceClassName);
640
    }
641

  
642
    private String getComplianceName(String complianceCode) {
643
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
644

  
645
        return compatibilityLevels.getEnglishName(complianceCode);
646
    }
647

  
648
    private Vocabulary getVocabulary(String vocName) {
649

  
650
        if (!vocabularyMap.containsKey(vocName)) {
651
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
652
        }
653
        return vocabularyMap.get(vocName);
654
    }
655

  
656
    @Scheduled(fixedRate = 3600000)
657
    private void loadVocabularies() {
658
        LOGGER.debug("loading vocabularies");
659
        for (String vocName : vocabularyNames) {
660
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
661
        }
662
    }
663

  
664
}
modules/uoa-repository-manager-gui/branches/newAPI/src/main/java/eu/dnetlib/repo/manager/server/services/BrokerServiceImpl.java
1
package eu.dnetlib.repo.manager.server.services;
2

  
3
import eu.dnetlib.domain.data.Repository;
4
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
5
import eu.dnetlib.repo.manager.client.services.BrokerService;
6
import eu.dnetlib.repo.manager.shared.BrokerException;
7
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
8
import eu.dnetlib.repo.manager.shared.Tuple;
9
import eu.dnetlib.repo.manager.shared.broker.*;
10
import eu.dnetlib.repos.RepoApi;
11
import org.apache.log4j.Logger;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.beans.factory.annotation.Value;
14
import org.springframework.core.ParameterizedTypeReference;
15
import org.springframework.http.HttpEntity;
16
import org.springframework.http.HttpMethod;
17
import org.springframework.http.ResponseEntity;
18
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
19
import org.springframework.stereotype.Service;
20
import org.springframework.util.LinkedMultiValueMap;
21
import org.springframework.util.MultiValueMap;
22
import org.springframework.web.client.RestClientException;
23
import org.springframework.web.client.RestTemplate;
24
import org.springframework.web.util.UriComponentsBuilder;
25

  
26
import javax.servlet.ServletConfig;
27
import javax.servlet.ServletException;
28
import java.util.*;
29

  
30
/**
31
 * Created by stefanos on 10/26/16.
32
 */
33
@SuppressWarnings("serial")
34
@Service("brokerService")
35
public class BrokerServiceImpl extends SpringGwtRemoteServiceServlet implements BrokerService {
36

  
37
    private static final Logger LOGGER = Logger
38
            .getLogger(BrokerServiceImpl.class);
39

  
40
    @Autowired
41
    private RepoApi repoAPI;
42

  
43
    @Override
44
    public void init(ServletConfig config) throws ServletException {
45
        super.init(config);
46
        LOGGER.info("broker service init");
47
    }
48

  
49
    @Value("${services.broker.url}:${services.broker.port}/${services.broker.api}${services.broker.openaire}")
50
    private String openairePath;
51
    @Value("${services.broker.url}:${services.broker.port}/${services.broker.api}")
52
    private String apiPath;
53

  
54
    /**
55
     * @param datasourceName the name of the data source
56
     * @return a list of BrowseEvent entries for that datasource
57
     * @throws BrokerException containing the error code from the server
58
     * @author stefanos
59
     */
60
    @Override
61
    public List<BrowseEntry> getTopicsForDatasource(String datasourceName) throws BrokerException {
62
        final String service = "/topicsForDatasource";
63

  
64
        //build the uri params
65
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service)
66
                .queryParam("ds", datasourceName);
67

  
68
        //create new template engine
69
        RestTemplate template = new RestTemplate();
70
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
71
        ResponseEntity<List<BrowseEntry>> resp;
72
        try {
73
            //communicate with endpoint
74
            resp = template.exchange(
75
                    builder.build().encode().toUri(),
76
                    HttpMethod.GET,
77
                    null,
78
                    new ParameterizedTypeReference<List<BrowseEntry>>() {
79
                    });
80
        } catch (RestClientException e) {
81
            throw new BrokerException(e);
82
        }
83

  
84
        return resp.getBody();
85
    }
86

  
87
    /**
88
     * @param datasourceName the name of the datasource
89
     * @param topic          the name of the topic to filter
90
     * @param page           the page number
91
     * @return an Events page with a constant 50 max number of entires
92
     * @throws BrokerException containing the error code from the server
93
     */
94
    @Override
95
    public EventsPage showEvents(String datasourceName, String topic, long page) throws BrokerException {
96
        final String service = "/showEvents";
97

  
98
        //build the uri params
99
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service)
100
                .queryParam("ds", datasourceName)
101
                .queryParam("topic", topic)
102
                .queryParam("page", page);
103

  
104
        //create new template engine
105
        RestTemplate template = new RestTemplate();
106
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
107
        ResponseEntity<EventsPage> resp;
108
        try {
109
            //communicate with endpoint
110
            resp = template.exchange(
111
                    builder.build().encode().toUri(),
112
                    HttpMethod.GET,
113
                    null,
114
                    new ParameterizedTypeReference<EventsPage>() {
115
                    });
116
        } catch (RestClientException e) {
117
            throw new BrokerException(e);
118
        }
119
        return resp.getBody();
120
    }
121

  
122
    /**
123
     * @param advQueryObject a pojo class containing the filter parameters
124
     * @param page           the number of the page
125
     * @param pageSize       the page size
126
     * @return
127
     * @throws BrokerException
128
     */
129
    @Override
130
    public EventsPage advancedShowEvents(AdvQueryObject advQueryObject, long page, long pageSize) throws BrokerException {
131
        final String service = "/events/{page}/{pageSize}";
132

  
133
        // URI (URL) parameters
134
        Map<String, Long> uriParams = new HashMap<>();
135
        uriParams.put("page", page);
136
        uriParams.put("pageSize", pageSize);
137

  
138
        //build the uri params
139
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service);
140

  
141
        //Header info
142
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
143
        headers.add("Content-Type", "application/json");
144

  
145
        advQueryObject.setPage(page);
146

  
147
        HttpEntity<AdvQueryObject> entity = new HttpEntity<>(advQueryObject, headers);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff