Project

General

Profile

« Previous | Next » 

Revision 49521

Copying to move to dnet45

View differences:

modules/uoa-repository-manager-gui/trunk/deploy.info
1
{
2
"type_source": "SVN",
3
"goal": "package -U source:jar",
4
"url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-repository-manager-gui/trunk/",
5
"deploy_repository": "dnet4-snapshots",
6
"version": "4",
7
"mail": "antleb@di.uoa.gr, kiatrop@di.uoa.gr,alessia.bardi@isti.cnr.it",
8
"deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots",
9
"name": "uoa-repository-manager-gui"
10
}
modules/uoa-repository-manager-gui/trunk/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/trunk/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/trunk/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/trunk/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/trunk/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.UserAccessException;
8
import eu.dnetlib.users.UserApi;
9
import org.apache.log4j.Logger;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.stereotype.Service;
12

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

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

  
25
    private static final Logger LOGGER = Logger
26
            .getLogger(UserServiceImpl.class);
27

  
28
    @Autowired
29
    private UserApi userAPI;
30

  
31
    @Autowired
32
    private EmailUtils emailUtils;
33

  
34

  
35
    public void init(ServletConfig config) throws ServletException {
36

  
37
        LOGGER.info("initializing user service impl ");
38
        super.init(config);
39

  
40
    }
41

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

  
47
            String email = email_username;
48

  
49
            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])?$");
50
            if (!rfc2822.matcher(email_username.trim().toLowerCase()).matches()) {
51
                LOGGER.debug("user logged in using username");
52
                email = this.userAPI.getEmailFromUsername(email_username);
53
            }
54
            if (email == null) {
55
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
56
            }
57
            if (!this.userAPI.userExists(email)) {
58
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
59
            }
60
            if (!this.userAPI.isUserActivated(email)) {
61
                throw new UserAccessException("login.notActivated", UserAccessException.ErrorCode.NOT_ACTIVATED);
62
            }
63
            if (!this.userAPI.correctCreds(email, password)) {
64
                throw new UserAccessException("login.InvalidPassword", UserAccessException.ErrorCode.INVALID_PASSWORD);
65
            }
66

  
67
            return this.userAPI.getUser(email);
68

  
69
        } catch (Exception e) {
70
            LOGGER.error("An error occurred while checking credentials for user " + email_username, e);
71
            emailUtils.reportException(e);
72

  
73
            if (e instanceof UserAccessException) {
74
                throw (UserAccessException) e;
75
            }
76
            else {
77
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
78
            }
79
        }
80

  
81
    }
82

  
83
    @Override
84
    public UserProfile getUserByEmail(String email) throws UserAccessException {
85
        LOGGER.info("Getting user with email " + email);
86
        try {
87

  
88
            return this.userAPI.getUser(email);
89

  
90
        } catch (Exception e) {
91
            LOGGER.error("An error occurred while getting user with email " + email, e);
92
            emailUtils.reportException(e);
93

  
94
            throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
95
        }
96
    }
97

  
98
    @Override
99
    public void register(UserProfile userProfile) throws UserAccessException {
100

  
101
        try {
102
            LOGGER.info("Registering user " + userProfile.getEmail());
103

  
104
            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])?$");
105
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
106
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
107
            }
108

  
109
            if (this.userAPI.usernameExists(userProfile.getUsername())) {
110
                throw new UserAccessException("login.usernameAlreadyExists", UserAccessException.ErrorCode.USERNAME_ALREADY_EXISTS);
111
            }
112
            if (this.userAPI.userExists(userProfile.getEmail())) {
113
                throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
114
            }
115

  
116
//            String activationId = "TEST";
117
            String activationId = this.userAPI.addUser(userProfile.getUsername(), userProfile.getEmail(), userProfile.getPassword(), userProfile.getFirstname(), userProfile.getLastname(), userProfile.getInstitution());
118

  
119
            emailUtils.sendActivationEmail(userProfile, activationId);
120

  
121
        } catch (Exception e) {
122
            LOGGER.error("Error while registering user " + userProfile.getEmail(), e);
123
            emailUtils.reportException(e);
124

  
125
            if (e instanceof UserAccessException)
126
                throw (UserAccessException) e;
127
            else
128
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
129
        }
130

  
131
    }
132

  
133
    @Override
134
    public void activateUser(String activationId) throws UserAccessException {
135
        try {
136
            LOGGER.info("Activating user with activation with activation id " + activationId);
137

  
138
            if (!this.userAPI.activateUser(activationId))
139
                throw new UserAccessException("registration.okAccountAlreadyActivation", UserAccessException.ErrorCode.ALREADY_ACTIVATED);
140
        } catch (Exception e) {
141
            LOGGER.error("Error while activating user account with activation id " + activationId, e);
142
            emailUtils.reportException(e);
143

  
144
            if (e instanceof UserAccessException)
145
                throw (UserAccessException) e;
146
            else
147
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
148
        }
149
    }
150

  
151
    @Override
152
    public void updateUser(UserProfile userProfile) throws UserAccessException {
153
        try {
154
            LOGGER.info("Editing user " + userProfile.getUsername());
155
            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])?$");
156
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
157
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
158
            }
159

  
160
            String currentEmail = this.userAPI.getEmailFromUsername(userProfile.getUsername());
161
            if (!userProfile.getEmail().equalsIgnoreCase(currentEmail)) {
162
                if (this.userAPI.userExists(userProfile.getEmail())) {
163
                    throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
164
                }
165
            }
166

  
167
            this.userAPI.editUser(userProfile);
168

  
169
        } catch (Exception e) {
170
            LOGGER.error("Error while editing user " + userProfile.getUsername(), e);
171
            if (e instanceof UserAccessException)
172
                throw (UserAccessException) e;
173
            else
174
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
175
        }
176
    }
177

  
178
    @Override
179
    public void prepareResetPassword(String email) throws UserAccessException {
180

  
181
        try {
182
            LOGGER.debug("Sending password recovery to user " + email);
183
            if (!this.userAPI.userExists(email)) {
184
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
185
            }
186
            List<String> to = new ArrayList<String>();
187
            to.add(email);
188
            String securityCode = this.userAPI.prepareResetPassword(email);
189

  
190
            emailUtils.sendResetPasswordEmail(email, securityCode);
191

  
192
        } catch (Exception e) {
193
            LOGGER.error("Error while sending password recovery to user " + email, e);
194
            emailUtils.reportException(e);
195

  
196
            if (e instanceof UserAccessException)
197
                throw (UserAccessException) e;
198
            else
199
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
200
        }
201
    }
202

  
203
    @Override
204
    public void resetPassword(String securityCode, String password) throws UserAccessException {
205
        try {
206
            LOGGER.debug("Reseting password with security code " + securityCode);
207

  
208
            if (securityCode.length() == 0) {
209
                throw new UserAccessException("resetPassword.wrongSecurityCode", UserAccessException.ErrorCode.WRONG_SECURITY_CODE);
210
            }
211

  
212
            this.userAPI.resetPassword(securityCode, password);
213

  
214
        } catch (Exception e) {
215
            LOGGER.error("Error while reseting password with security code " + securityCode);
216
            emailUtils.reportException(e);
217

  
218
            if (e instanceof UserAccessException)
219
                throw (UserAccessException) e;
220
            else
221
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
222
        }
223
    }
224

  
225
    @Override
226
    public void resendActivation(String email) throws UserAccessException {
227

  
228
    }
229

  
230
}
modules/uoa-repository-manager-gui/trunk/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.gwt.server.service.SpringGwtRemoteServiceServlet;
9
import eu.dnetlib.repo.manager.client.services.RepositoryService;
10
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
11
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
12
import eu.dnetlib.repo.manager.shared.*;
13
import eu.dnetlib.repos.RepoApi;
14
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
15
import org.apache.commons.lang.StringEscapeUtils;
16
import org.apache.commons.lang.WordUtils;
17
import org.apache.log4j.Logger;
18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.beans.factory.annotation.Value;
20
import org.springframework.dao.EmptyResultDataAccessException;
21
import org.springframework.scheduling.annotation.Scheduled;
22
import org.springframework.stereotype.Service;
23

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

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

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

  
40
    @Autowired
41
    private RepoApi repoAPI;
42

  
43
    @Autowired
44
    private EmailUtils emailUtils;
45

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

  
48
    @Autowired
49
    private VocabularyLoader vocabularyLoader;
50

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

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

  
56
    @Autowired
57
    private PiwikDAO piwikDAO;
58

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

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

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

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

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

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

  
119
            return retTuple;
120

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

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

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

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

  
152
            return retDatasources;
153

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

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

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

  
173
            return retRepos;
174

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

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

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

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

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

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

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

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

  
235
            return countriesMap;
236

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

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

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

  
264
    }
265

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

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

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

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

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

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

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

  
334
            return retMap;
335

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
472
    }
473

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

  
485
            return vocs;
486

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

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

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

  
506
            retTuple.setFirst(reposList);
507

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

  
514
                retTuple.setSecond(totalList);
515
            }
516

  
517
            return retTuple;
518

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

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

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

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

  
552
    @Override
553
    public void enableMetricsForRepository(Repository repository) throws RepositoryServiceException {
554

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

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

  
563
            String siteId = "49";
564
            PiwikInfo piwikInfo = new PiwikInfo();
565
            piwikInfo.setRepositoryId(repository.getId());
566
            piwikInfo.setSiteId(siteId);
567

  
568
            this.piwikDAO.savePiwikInfo(piwikInfo);
569

  
570
//        } catch (IOException e) {
571
//            LOGGER.error("Error while creating piwik site", e);
572
//            emailUtils.reportException(e);
573
//            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
574
//        }
575
    }
576

  
577
    @Override
578
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
579
        try {
580
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
581

  
582
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
583
            return piwikScript;
584

  
585
        } catch (EmptyResultDataAccessException e) {
586
            return null;
587
        }
588
    }
589

  
590
    private String getCountryCode(String countryName) {
591
        Vocabulary countries = this.getVocabulary("dnet:countries");
592

  
593
        return countries.getEncoding(countryName);
594
    }
595

  
596
    private String getDatasourceClassCode(String datasourceClassName) {
597
        Vocabulary datasourceClasses = this.getVocabulary("dnet:datasource_typologies");
598

  
599
        return datasourceClasses.getEncoding(datasourceClassName);
600
    }
601

  
602
    private String getComplianceName(String complianceCode) {
603
        Vocabulary compatibilityLevels = this.getVocabulary("dnet:compatibilityLevel");
604

  
605
        return compatibilityLevels.getEnglishName(complianceCode);
606
    }
607

  
608
    private Vocabulary getVocabulary(String vocName) {
609

  
610
        if (!vocabularyMap.containsKey(vocName)) {
611
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
612
        }
613
        return vocabularyMap.get(vocName);
614
    }
615

  
616
    @Scheduled(fixedRate = 3600000)
617
    private void loadVocabularies() {
618
        LOGGER.debug("loading vocabularies");
619
        for (String vocName : vocabularyNames) {
620
            vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT));
621
        }
622
    }
623

  
624
}
modules/uoa-repository-manager-gui/trunk/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);
148

  
149
        //create new template engine
150
        RestTemplate template = new RestTemplate();
151
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
152
        ResponseEntity<EventsPage> resp;
153
        try {
154
            //communicate with endpoint
155
            resp = template.exchange(
156
                    builder.buildAndExpand(uriParams).encode().toUri(),
157
                    HttpMethod.POST,
158
                    entity,
159
                    new ParameterizedTypeReference<EventsPage>() {
160
                    }
161
            );
162
        } catch (RestClientException e) {
163
            throw new BrokerException(e);
164
        }
165
        return resp.getBody();
166
    }
167

  
168
    @Override
169
    public DatasourcesBroker getDatasourcesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws BrokerException {
170
        DatasourcesBroker ret = new DatasourcesBroker();
171
        try {
172
            LOGGER.debug("In getDatasourcesOfUser");
173

  
174
            //set for user
175
            ret.setDatasourcesOfUser(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, false)));
176

  
177
            //set for shared
178
            if (includeShared) {
179
                //TODO whatever nikonas was saying
180
                List<String> sharedDatasourceIds = new ArrayList<String>();
181
                ret.setSharedDatasources(getDatasourcesOfUserType(this.repoAPI.getReposByIds(sharedDatasourceIds)));
182
            }
183

  
184
            //set others
185
            if (includeByOthers) {
186
                ret.setDatasourcesOfOthers(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, true)));
187
            }
188

  
189
        } catch (RepositoryServiceException e) {
190
            e.printStackTrace();
191
            throw new BrokerException(e);
192
        } catch (Exception e) {
193
            e.printStackTrace();
194
        }
195
        return ret;
196
    }
197

  
198
    @Override
199
    public Map<String, List<SimpleSubscriptionDesc>> getSubscriptionsOfUser(String userEmail) throws BrokerException {
200
        final String service = "/subscriptions";
201

  
202
        //build the uri params
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff