Project

General

Profile

« Previous | Next » 

Revision 50056

Creating new 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.data.PiwikInfo;
4
import eu.dnetlib.domain.functionality.UserProfile;
5

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

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

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

  
15
    void reportException(Exception exception);
16

  
17
    void sendAdministratorRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception;
18

  
19
    void sendUserRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception;
20

  
21
    void sendAdministratorMetricsEnabled(PiwikInfo piwikInfo) throws Exception;
22

  
23
    void sendUserMetricsEnabled(PiwikInfo piwikInfo) throws Exception;
24
}
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.data.PiwikInfo;
4
import eu.dnetlib.domain.functionality.UserProfile;
5
import eu.dnetlib.repo.manager.server.config.CascadingPropertyLoader;
6
import eu.dnetlib.utils.MailLibrary;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.beans.factory.annotation.Value;
10
import org.springframework.stereotype.Component;
11

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

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

  
22
@Component
23
public class EmailUtilsImpl implements EmailUtils {
24

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

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

  
31
    @Autowired
32
    private MailLibrary mailLibrary;
33

  
34
    @Autowired
35
    private CascadingPropertyLoader pLoader;
36

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

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

  
43
    @Value("${services.repomanager.usagestats.adminEmail}")
44
    private String usageStatsAdminEmail;
45

  
46
    @Override
47
    public void sendActivationEmail(UserProfile user, String activationId) throws Exception {
48
        try {
49

  
50
            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);
51

  
52
        } catch (Exception e) {
53
            LOGGER.error("Error while sending activation email to user: " + user.getEmail(), e);
54
            throw e;
55
        }
56
    }
57

  
58
    @Override
59
    public void sendResetPasswordEmail(String email, String securityCode) throws Exception {
60
        try {
61

  
62
            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);
63

  
64
        } catch (Exception e) {
65
            LOGGER.error("Error while sending activation email to user: " + email, e);
66
            throw e;
67
        }
68
    }
69

  
70

  
71
    @Override
72
    public void reportException(Exception exception) {
73
        Writer writer = new StringWriter();
74
        PrintWriter printWriter = new PrintWriter(writer);
75
        exception.printStackTrace(printWriter);
76

  
77
        List<String> recipients = new ArrayList<String>();
78

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

  
89
    @Override
90
    public void sendAdministratorRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception {
91

  
92
        try {
93
            String subject = "[OpenAIRE-Usage Statistics] New request to enable usage statistics";
94

  
95
            String message = "Dear administrator,\n" +
96
                    "\n" +
97
                    "we have received a request to enable the OpenAIRE usage statistics for the following repository \n" +
98
                    "\n" +
99
                    "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" +
100
                    "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" +
101
                    "Piwik ID - " + piwikInfo.getSiteId() + "\n" +
102
                    "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" +
103
                    "\n" +
104
                    "For more information about this request, go here: \n" +
105
                    this.baseUrl + "/#admin/metrics\n" +
106
                    "\n" +
107
                    "Best,\n" +
108
                    "The OpenAIRE team";
109

  
110
            this.sendMail(this.usageStatsAdminEmail, subject, message, false, null);
111

  
112
        } catch (Exception e) {
113
            LOGGER.error("Error while sending request to enable metrics email to administrator: " + this.usageStatsAdminEmail, e);
114
            throw e;
115
        }
116
    }
117

  
118
    @Override
119
    public void sendUserRequestToEnableMetrics(PiwikInfo piwikInfo) throws Exception {
120

  
121
        try {
122
            String subject = "[OpenAIRE-Usage Statistics] Your request to enable usage statistics";
123

  
124
            String message = "Dear " + piwikInfo.getRequestorName() + ",\n" +
125
                    "\n" +
126
                    "we have received your request to enable the OpenAIRE usage statistics for your repository\n" +
127
                    "\n" +
128
                    "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" +
129
                    "Piwik ID - " + piwikInfo.getSiteId() + "\n" +
130
                    "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" +
131
                    "\n" +
132
                    "In order to enable the usage statistics, you must install the OpenAIRE's tracking code in your repository software. " +
133
                    "OpenAIRE's usage statistics service tracking code is maintained on Github as a patch for various versions of DSpace " +
134
                    "(https://github.com/openaire/OpenAIRE-Piwik-DSpace) and as an Eprints plugin for version 3 " +
135
                    "(https://github.com/openaire/EPrints-OAPiwik). In case the platform is different from DSpace or EPrints please contact " +
136
                    "the OpenAIRE team in repositoryusagestats@openaire.eu in order to find a solution.\n" +
137
                    "\n" +
138
                    "For more information about your request and configuration details, go here: \n" +
139
                    this.baseUrl + "/#getImpact/instructions/" + piwikInfo.getRepositoryId() + "\n" +
140
                    "\n" +
141
                    "Once you have finished configuring your repository or if you have any questions, please notify the OpenAIRE team by sending \n" +
142
                    "an email to repositoryusagestats@openaire.eu\n" +
143
                    "\n" +
144
                    "Best,\n" +
145
                    "The OpenAIRE team";
146

  
147
            this.sendMail(piwikInfo.getRequestorEmail(), subject, message, false, null);
148

  
149
        } catch (Exception e) {
150
            LOGGER.error("Error while sending request to enable metrics email to user: " + piwikInfo.getRequestorEmail(), e);
151
            throw e;
152
        }
153
    }
154

  
155
    @Override
156
    public void sendAdministratorMetricsEnabled(PiwikInfo piwikInfo) throws Exception {
157

  
158
        try {
159
            String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled";
160

  
161
            String message = "Dear administrator,\n" +
162
                    "\n" +
163
                    "The installation and configuration of OpenAIRE's tracking code for the following repository " +
164
                    "has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" +
165
                    "\n" +
166
                    "Repository - " + piwikInfo.getRepositoryName() + ", " + piwikInfo.getCountry() + " (" + piwikInfo.getRepositoryId() + ")\n" +
167
                    "Requestor - " + piwikInfo.getRequestorName() + ", " + piwikInfo.getRequestorEmail() + "\n" +
168
                    "Piwik ID - " + piwikInfo.getSiteId() + "\n" +
169
                    "Authentication token - " + piwikInfo.getAuthenticationToken() + "\n" +
170
                    "\n" +
171
                    "Best,\n" +
172
                    "The OpenAIRE team";
173

  
174
            this.sendMail(piwikInfo.getRequestorEmail(), subject, message, false, null);
175

  
176
        } catch (Exception e) {
177
            LOGGER.error("Error while sending metrics enabled notification email to administator: " + this.usageStatsAdminEmail, e);
178
            throw e;
179
        }
180
    }
181

  
182
    @Override
183
    public void sendUserMetricsEnabled(PiwikInfo piwikInfo) throws Exception {
184

  
185
        try {
186
            String subject = "[OpenAIRE-Usage Statistics] Usage statistics have been enabled";
187

  
188
            String message = "Dear " + piwikInfo.getRequestorName() + ",\n" +
189
                    "\n" +
190
                    "The installation and configuration of OpenAIRE's tracking code for your repository \"" + piwikInfo.getRepositoryName() +
191
                    "\" has been completed and validated and the usage statistics have been enabled in OpenAIRE.\n" +
192
                    "\n" +
193
                    "You can preview the statistics in your repository's dashboard: \n" +
194
                    this.baseUrl + "/#getImpact/" + piwikInfo.getRepositoryId() + "\n" +
195
                    "\n" +
196
                    " For more information and questions, you can contact the openaire support team by sending an email to " +
197
                    "repositoryusagestats@openaire.eu\n" +
198
                    "\n" +
199
                    "Best,\n" +
200
                    "The OpenAIRE team";
201

  
202
            this.sendMail(piwikInfo.getRequestorEmail(), subject, message, false, null);
203

  
204
        } catch (Exception e) {
205
            LOGGER.error("Error while sending metrics enabled notification email to user: " + piwikInfo.getRequestorEmail(), e);
206
            throw e;
207
        }
208
    }
209

  
210
    private void sendMail(String email, String subject, String message, boolean sendToSpecial, List<String> repoAdminMails) throws Exception {
211
        ArrayList<String> to = new ArrayList<String>();
212
        to.add(email);
213
        this.sendMail(to,subject,message,sendToSpecial,repoAdminMails);
214
    }
215

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

  
218
       /* try {
219
            if (sendToSpecial) {
220
                recipients.addAll(this.specialRecipients);
221
            }
222

  
223
            if (repoAdminMails != null)
224
                recipients.addAll(repoAdminMails);
225

  
226
            if (this.override) {
227
                recipients.clear();
228
                recipients.add(overrideEmail);
229
            }
230
            if (!logonly)
231
                mailLibrary.sendEmail(recipients.toArray(new String[]{}), subject, message);
232
            LOGGER.debug("Sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message);
233
        } catch (Exception e) {
234
            LOGGER.error("Error sending mail to Recipients: " + recipients + " Subject: " + subject + " Message: " + message, e);
235
            throw new Exception(e);
236
        }*/
237
    }
238

  
239
    private String getEmailProperty(String key) {
240
        return pLoader.getProperties().getProperty(key);
241
    }
242

  
243
    public void setSpecialRecipients(String specialRecipients) {
244
        String[] recps = specialRecipients.split(",");
245

  
246
        for (String recp : recps) {
247
            recp = recp.trim();
248

  
249
            this.specialRecipients.add(recp);
250
        }
251
    }
252

  
253

  
254
    public void setOverride(boolean override) {
255
        this.override = override;
256
    }
257

  
258
    public void setOverrideEmail(String overrideEmail) {
259
        this.overrideEmail = overrideEmail;
260
    }
261

  
262
    public String getFrom() {
263
        return from;
264
    }
265

  
266
    public void setFrom(String from) {
267
        this.from = from;
268
    }
269

  
270
    public boolean isLogonly() {
271
        return logonly;
272
    }
273

  
274
    public void setLogonly(boolean logonly) {
275
        this.logonly = logonly;
276
    }
277

  
278

  
279
}
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.DeserializationConfig;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
6
import com.unboundid.util.Base64;
7
import eu.dnetlib.domain.data.PiwikInfo;
8
import eu.dnetlib.domain.data.Repository;
9
import eu.dnetlib.domain.data.RepositoryInterface;
10
import eu.dnetlib.domain.enabling.Vocabulary;
11
import eu.dnetlib.domain.functionality.UserProfile;
12
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
13
import eu.dnetlib.repo.manager.client.services.RepositoryService;
14
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
15
import eu.dnetlib.repo.manager.server.utils.LocalVocabularies;
16
import eu.dnetlib.domain.data.PiwikInfo;
17
import eu.dnetlib.repo.manager.service.controllers.RepositoryApi;
18
import eu.dnetlib.repo.manager.shared.*;
19
import eu.dnetlib.repos.RepoApi;
20
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
21
import org.apache.commons.codec.digest.DigestUtils;
22
import org.apache.commons.lang.StringEscapeUtils;
23
import org.apache.commons.lang.WordUtils;
24
import org.apache.log4j.Logger;
25
import org.json.JSONException;
26
import org.json.JSONObject;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.beans.factory.annotation.Value;
29
import org.springframework.core.ParameterizedTypeReference;
30
import org.springframework.dao.EmptyResultDataAccessException;
31
import org.springframework.http.HttpMethod;
32
import org.springframework.http.ResponseEntity;
33
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
34
import org.springframework.scheduling.annotation.Scheduled;
35
import org.springframework.stereotype.Service;
36
import org.springframework.web.client.RestClientException;
37
import org.springframework.web.client.RestTemplate;
38
import org.springframework.web.util.UriComponentsBuilder;
39

  
40
import javax.annotation.PostConstruct;
41
import java.io.IOException;
42
import java.io.UnsupportedEncodingException;
43
import java.net.URLEncoder;
44
import java.text.Normalizer;
45
import java.util.*;
46
import java.util.concurrent.ConcurrentHashMap;
47
import java.net.URL;
48

  
49
/**
50
 * Created by nikonas on 12/8/15.
51
 */
52
@SuppressWarnings("serial")
53
@Service("repositoryService")
54
public class RepositoryServiceImpl extends SpringGwtRemoteServiceServlet implements RepositoryService {
55

  
56
    private static final Logger LOGGER = Logger
57
            .getLogger(RepositoryServiceImpl.class);
58

  
59
    @Autowired
60
    private RepoApi repoAPI;
61

  
62
    @Autowired
63
    private EmailUtils emailUtils;
64

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

  
67
    @Autowired
68
    private VocabularyLoader vocabularyLoader;
69

  
70
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<String, Vocabulary>();
71

  
72
    @Value("${services.repo-manager.repository.testing.mode}")
73
    private boolean testingMode;
74

  
75
    @Autowired
76
    private PiwikDAO piwikDAO;
77

  
78
    @Value("${services.repomanager.analyticsURL}")
79
    private String analyticsURL;
80

  
81
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
82
    private String usageStatisticsDiagramsBaseURL;
83

  
84
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
85
    private String usageStatisticsNumbersBaseURL;
86

  
87
    private static final String PIWIK_SCRIPT = StringEscapeUtils.escapeHtml("<!-- Piwik -->\n" +
88
            "<script type=\"text/javascript\">\n" +
89
            "\tvar _paq = _paq || [];\n" +
90
            "\t_paq.push(['enableLinkTracking']);\n" +
91
            "\t(function() {\n" +
92
            "\t\tvar u=\"//analytics.openaire.eu/\";\n" +
93
            "\t\t_paq.push(['setTrackerUrl', u+'piwik.php']);\n" +
94
            "\t\t_paq.push(['setSiteId', $$$]);\n" +
95
            "\t\t<% if(handle != null){%>\n" +
96
            "\t\t\t_paq.push(['setCustomVariable', 1, 'oaipmhID',\"oai:<%= baseUrl %>:<%=handle %>\", 'page']);\n" +
97
            "\t\t\t_paq.push(['trackPageView']);\n" +
98
            "\t\t<}>\n" +
99
            "\t\tvar d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n" +
100
            "\t\tg.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);\n" +
101
            "\t})();\n" +
102
            "</script>\n" +
103
            "<noscript>\n" +
104
            "\t<p>\n" +
105
            "\t\t<img src=\"//analytics.openaire.eu/piwik.php?idsite=47\" style=\"border:0;\" alt=\"\" />\n" +
106
            "\t</p>\n" +
107
            "</noscript>\n" +
108
            "<!— End Piwik Code —>");
109

  
110

  
111
    @Autowired
112
    private RepositoryApi repositoryApi;
113

  
114

  
115

  
116
    @PostConstruct
117
    public void init() {
118
        this.loadVocabularies();
119
    }
120

  
121
    @Override
122
    public Tuple<List<Repository>, List<Repository>> getRepositoriesByCountry(String country, String mode, boolean includeUnknownCountries) throws RepositoryServiceException {
123
        try {
124
            if (testingMode)
125
                return this.getRepositoriesByCountryTesting(country, mode, includeUnknownCountries);
126
            LOGGER.debug("Getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries);
127

  
128
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
129
//            List<Repository> reposList = this.repoAPI.getRepositoriesPerCountry(mode).get(country);
130

  
131
            List<Repository> reposList = repositoryApi.getRepositoriesByCountry(country,mode);
132
            if (reposList == null) {
133
                retTuple.setFirst(new ArrayList<Repository>());
134
//                if (!includeUnknownCountries) {
135
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
136
//                }
137
            } else {
138
                retTuple.setFirst(reposList);
139
            }
140

  
141
            if (includeUnknownCountries) {
142
                List<Repository> withoutCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("Without Country");
143
                List<Repository> unknownCountryList = this.repoAPI.getRepositoriesPerCountry(mode).get("UNKNOWN");
144
                List<Repository> totalList = new ArrayList<Repository>();
145
                if (withoutCountryList != null)
146
                    totalList.addAll(withoutCountryList);
147
                if (unknownCountryList != null)
148
                    totalList.addAll(unknownCountryList);
149
                retTuple.setSecond(totalList);
150
            }
151

  
152
            return retTuple;
153

  
154
        } catch (Exception e) {
155
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, 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<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
167
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
168
    }
169

  
170
    @Override
171
    public DatasourcesCollection getRepositoriesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
172

  
173
        DatasourcesCollection retDatasources = new DatasourcesCollection();
174
        try {
175
            LOGGER.debug("Getting repositories of user: " + userEmail + " . IncludeShared: "
176
                    + includeShared + " . IncludeByOthers: " + includeByOthers);
177
            int page = 0;
178
            String size = "50";
179
            List<Repository> resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
180
            while(resultSet.size() > 0 ){
181
                retDatasources.getDatasourcesOfUser().addAll(resultSet);
182
                page++;
183
                resultSet = repositoryApi.getRepositoriesOfUser(userEmail,String.valueOf(page),size);
184
            }
185

  
186
/*
187
	if (includeShared) {
188
                //TODO create dao to save-get shared datasourcesIDs
189
                List<String> sharedDatasourceIds = new ArrayList<String>();
190
                retDatasources.setSharedDatasources(this.repoAPI.getReposByIds(sharedDatasourceIds));
191
                //geting Piwik Info
192
                for(Repository repository: retDatasources.getSharedDatasources())
193
                    repository.setPiwikInfo(this.getPiwikSiteForRepository(repository.getId()));
194
            }
195

  
196
            if (includeByOthers) {
197
                retDatasources.setDatasourcesOfOthers(this.repoAPI.getRepositoriesOfUser(userEmail, true));
198
                //geting Piwik Info
199
                for(Repository repository: retDatasources.getDatasourcesOfOthers())
200
                    repository.setPiwikInfo(this.getPiwikSiteForRepository(repository.getId()));
201
            }
202
*/
203
        } catch (JSONException e) {
204
            LOGGER.error("Error while getting repositories of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
205
            emailUtils.reportException(e);
206
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
207
        }
208
        return retDatasources;
209
    }
210

  
211
    @Override
212
    public List<String> getRepositoryUrlsOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws RepositoryServiceException {
213
        try {
214
            LOGGER.debug("Getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers);
215
            List<String> retRepos = new ArrayList<String>();
216

  
217
            int page = 0;
218
            String size = "50";
219
            List<String> resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
220
            while(resultSet.size() > 0 ){
221
                retRepos.addAll(resultSet);
222
                page++;
223
                resultSet = repositoryApi.getUrlsOfUserRepos(userEmail,String.valueOf(page),size);
224
            }
225
            return retRepos;
226

  
227
        } catch (Exception e) {
228
            LOGGER.error("Error while getting repositories(urls) of user: " + userEmail + " . IncludeShared: " + includeShared + " . IncludeByOthers: " + includeByOthers, e);
229
            emailUtils.reportException(e);
230
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
231
        }
232
    }
233

  
234
    @Override
235
    public Repository getRepository(String repoId) throws RepositoryServiceException {
236
        try {
237
            LOGGER.debug("Getting repository with id: " + repoId);
238
            Repository repo = repositoryApi.getRepositoryById(repoId);
239

  
240
            if (repo != null) {
241
                for (RepositoryInterface iFace : repo.getInterfaces()) {
242
                    if (!iFace.getContentDescription().equals("file::hybrid") && iFace.getAccessProtocol().equalsIgnoreCase("oai")) {
243
                        iFace.setComplianceName(getComplianceName(iFace.getCompliance()));
244
                        if (iFace.getCompliance().equals("notCompatible"))
245
                            iFace.setComplianceName("not compatible");
246
                    }
247
                }
248

  
249
                //geting Piwik Info
250
                repo.setPiwikInfo(this.getPiwikSiteForRepository(repoId));
251

  
252
            } else
253
                throw new RepositoryServiceException("registration.repositoryNotExists", RepositoryServiceException.ErrorCode.REPOSITORY_NOT_EXISTS);
254
            return repo;
255

  
256
        } catch (Exception e) {
257
            LOGGER.error("Error while getting repository with id: " + repoId, e);
258
            if (e instanceof RepositoryServiceException) {
259
                throw (RepositoryServiceException) e;
260
            } else {
261
                emailUtils.reportException(e);
262
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
263
            }
264
        }
265
    }
266

  
267
    @Override
268
    public Map<String, String> getCountries(Boolean existingOnly, String mode) throws RepositoryServiceException {
269
        try {
270
            LOGGER.debug("Getting countries");
271
            List<String> countries = new ArrayList<String>();
272

  
273
            Map<String, String> countriesMap = new TreeMap<String, String>();
274

  
275
            if (existingOnly) {
276
                LOGGER.debug("using the repositories map");
277
                countries.addAll(this.repoAPI.getRepositoriesByCountry(mode).keySet());
278
            } else {
279
                LOGGER.debug("using \"dnet:countries\" vocabulary");
280
                countries.addAll(this.getVocabulary("dnet:countries").getEnglishNames());
281
            }
282
//            countries.addAll(repositoryApi.getDnetCountries());
283
            for (String country : countries) {
284
                countriesMap.put(country, WordUtils.capitalizeFully(country));
285
            }
286

  
287
            return countriesMap;
288

  
289
        } catch (Exception e) {
290
            LOGGER.error("Error while getting getting countries", e);
291
            if (e instanceof RepositoryServiceException) {
292
                throw (RepositoryServiceException) e;
293
            } else {
294
                emailUtils.reportException(e);
295
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
296
            }
297
        }
298
    }
299

  
300
    @Override
301
    public Map<String, String> getCountries() throws RepositoryServiceException {
302
        return this.getCountries(false, null);
303
    }
304

  
305
    @Override
306
    public List<Timezone> getTimezones() throws RepositoryServiceException {
307
        try {
308
            LOGGER.debug("Getting timezones from file");
309
//            return repositoryApi.getTimezones();
310
            return LocalVocabularies.timezones;
311
        } catch (Exception e) {
312
            LOGGER.error("Error while getting timezones from file", e);
313
            emailUtils.reportException(e);
314
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
315
        }
316

  
317
    }
318

  
319
    @Override
320
    public List<String> getTypologies() throws RepositoryServiceException {
321
        try {
322
            LOGGER.debug("Getting typologies from file");
323
           // return repositoryApi.getTypologies();
324
            return LocalVocabularies.typologies;
325
        } catch (Exception e) {
326
            LOGGER.error("Error while getting typologies from file", e);
327
            emailUtils.reportException(e);
328
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
329
        }
330
    }
331

  
332
    @Override
333
    public Map<String, String> getDatasourceClasses(String mode) throws RepositoryServiceException {
334
        return repositoryApi.getDatasourceClasses(mode);
335
    }
336

  
337
    @Override
338
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
339
        return repositoryApi.getCompatibilityClasses(mode);
340
    }
341

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

  
345
        try {
346
            LOGGER.debug("Storing repository with name: " + repo.getOfficialName());
347
            //List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
348
            JSONObject params = new JSONObject();
349
            params.put("datatype", mode);
350
            ObjectMapper mapper = new ObjectMapper();
351
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repo);
352
            params.put("repository", json_repo);
353
            repositoryApi.addRepository(params.toString());
354
            LOGGER.debug("Repository with name: " + repo.getOfficialName() + " stored!");
355

  
356
        }catch (Exception e) {
357
            emailUtils.reportException(e);
358
            LOGGER.error("Error while storing repository with name: " + repo.getOfficialName(), e);
359
            throw new RepositoryServiceException("Error while storing repository", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
360
        }
361
    }
362

  
363
    @Override
364
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
365
        try {
366
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
367

  
368
	    //TODO SOS, check old API
369

  
370
            //this.repoAPI.updateRepositoryInformation(repo);
371
            repositoryApi.updateEnglishName(repo.getId(),repo.getEnglishName());
372
            repositoryApi.updateLatitude(repo.getId(), String.valueOf(repo.getLatitude()));
373
            repositoryApi.updateLongitude(repo.getId(), String.valueOf(repo.getLongitude()));
374
            repositoryApi.updateOfficialName(repo.getId(),repo.getOfficialName());
375
            repositoryApi.updateLogoUrl(repo.getId(),repo.getLogoUrl());
376
            repositoryApi.updateTimezone(repo.getId(),String.valueOf(repo.getTimezone()));
377
            repositoryApi.updatePlatform(repo.getId(),repo.getTypology());
378

  
379
        } catch (Exception e) {
380
            LOGGER.error("Error while updating information of repo: " + repo.getOfficialName(), e);
381
            if (e instanceof RepositoryServiceException) {
382
                throw (RepositoryServiceException) e;
383
            } else {
384
                emailUtils.reportException(e);
385
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
386
            }
387
        }
388
    }
389

  
390
    @Override
391
    public RepositoryInterface updateInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
392
        try {
393
            LOGGER.debug("updating interface with id: " + iFace.getId());
394
            RepositoryInterface retIface = null;
395
            retIface = this.repoAPI.updateRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
396
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
397

  
398
            return retIface;
399
        } catch (Exception e) {
400
            LOGGER.error("error updating interface with id: " + iFace.getId(), 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 insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
412
        try {
413
            LOGGER.debug("inserting interface with id: " + iFace.getId());
414
            RepositoryInterface retIface = null;
415
            //retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
416

  
417
            JSONObject params = new JSONObject();
418
            params.put("datatype",datatype);
419
            params.put("repoId",repoId);
420
            params.put("iFace",iFace);
421
            retIface = repositoryApi.addRepositoryInterface(params.toString());
422
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
423
            return retIface;
424

  
425
        } catch (Exception e) {
426
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
427
            if (e instanceof RepositoryServiceException) {
428
                throw (RepositoryServiceException) e;
429
            } else {
430
                emailUtils.reportException(e);
431
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
432
            }
433
        }
434
    }
435

  
436
    @Override
437
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
438
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
439
        iFaces.add(iFace);
440
        this.deleteInterfaces(repoId, iFaces, datatype);
441
    }
442

  
443
    @Override
444
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
445
        try {
446
            LOGGER.debug("deleting interfaces of repo: " + repoId);
447
            //this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
448

  
449
            for(RepositoryInterface iFace : iFaces) {
450
                LOGGER.info("deleting repository interface with url/set/id: " + iFace.getBaseUrl() + "/"
451
                        + iFace.getAccessSet() + "/" + iFace.getId());
452
                repositoryApi.deleteRepositoryInterface(iFace.getId());
453
            }
454

  
455
        } catch (Exception e) {
456
            LOGGER.error("deleting interfaces of repo: " + repoId, e);
457
            if (e instanceof RepositoryServiceException) {
458
                throw (RepositoryServiceException) e;
459
            } else {
460
                emailUtils.reportException(e);
461
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
462
            }
463
        }
464

  
465
    }
466

  
467
    @Override
468
    public DatasourceVocabularies getDatasourceVocabularies(String mode) throws RepositoryServiceException {
469
        try {
470
            LOGGER.debug("Getting vocabularies for datasource with type: " + mode);
471
            DatasourceVocabularies vocs = new DatasourceVocabularies();
472
            vocs.setCountries(this.getCountries());
473
            vocs.setDatasourceClasses(this.getDatasourceClasses(mode));
474
            vocs.setTimezones(this.getTimezones());
475
            vocs.setTypologies(this.getTypologies());
476
            vocs.setCompatibilityLevels(this.getCompatibilityClasses(mode));
477

  
478
            return vocs;
479

  
480
        } catch (Exception e) {
481
            LOGGER.error("Error while getting vocabularies for datasource with type: \" + mode", e);
482
            emailUtils.reportException(e);
483
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
484
        }
485
    }
486

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

  
491
            Tuple<List<Repository>, List<Repository>> retTuple = new Tuple<List<Repository>, List<Repository>>();
492
            List<Repository> reposList = new ArrayList<Repository>();
493
            reposList.add(this.repoAPI.getRepository("opendoar____::1356"));
494
            reposList.add(this.repoAPI.getRepository("opendoar____::2678"));
495
            reposList.add(this.repoAPI.getRepository("opendoar____::2980"));
496
            reposList.add(this.repoAPI.getRepository("opendoar____::1347"));
497
            reposList.add(this.repoAPI.getRepository("opendoar____::2984"));
498

  
499
            retTuple.setFirst(reposList);
500

  
501
            if (includeUnknownCountries) {
502
                List<Repository> totalList = new ArrayList<Repository>();
503
                totalList.add(this.repoAPI.getRepository("opendoar____::3000"));
504
                totalList.add(this.repoAPI.getRepository("opendoar____::1027"));
505
                totalList.add(this.repoAPI.getRepository("opendoar____::1096"));
506

  
507
                retTuple.setSecond(totalList);
508
            }
509

  
510
            return retTuple;
511

  
512
        } catch (Exception e) {
513
            LOGGER.error("Error while getting testing repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
514
            if (e instanceof RepositoryServiceException) {
515
                throw (RepositoryServiceException) e;
516
            } else {
517
                emailUtils.reportException(e);
518
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
519
            }
520
        }
521
    }
522

  
523
    @Override
524
    public String getLatestUpdateDateOfList(String mode) throws RepositoryServiceException {
525
        try {
526
            LOGGER.debug("Getting latest update date of list: " + mode);
527
            return this.repoAPI.getListLatestUpdate(mode).split("T")[0];
528

  
529
        } catch (Exception e) {
530
            LOGGER.error("Error while getting latest update date of list: " + mode, e);
531
            emailUtils.reportException(e);
532
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
533
        }
534
    }
535

  
536
    @Override
537
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
538
        try {
539
            LOGGER.debug("Repo id -> " + repoId);
540
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
541
        } catch (EmptyResultDataAccessException e) {
542
            return null;
543
        }
544
    }
545

  
546
    @Override
547
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
548
        
549
        try {
550
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(repository.getOfficialName(), "UTF-8") + "&url=" + URLEncoder.encode(repository.getWebsiteUrl(), "UTF-8");
551
            Map<String, Object> map = new ObjectMapper().readValue(new URL(URL), Map.class);
552

  
553
            String siteId = null;
554
            if(map.get("value")!=null) {
555
                siteId = map.get("value").toString();
556
            }
557

  
558
            String authenticationToken = "32846584f571be9b57488bf4088f30ea";
559

  
560
            PiwikInfo piwikInfo = new PiwikInfo();
561
            piwikInfo.setRepositoryId(repository.getId());
562
            piwikInfo.setRepositoryName(repository.getOfficialName());
563
            piwikInfo.setCountry(repository.getCountryName());
564
            piwikInfo.setSiteId(siteId);
565
            piwikInfo.setAuthenticationToken(authenticationToken);
566
            piwikInfo.setRequestorEmail(requestor.getEmail());
567
            piwikInfo.setRequestorName(requestor.getFirstname() + " " + requestor.getLastname());
568
            piwikInfo.setValidated(false);
569

  
570
            this.piwikDAO.savePiwikInfo(piwikInfo);
571

  
572
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
573
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
574

  
575
        } catch (UnsupportedEncodingException uee) {
576
            LOGGER.error("Error while creating piwikScript URL", uee);
577
            emailUtils.reportException(uee);
578
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
579
        } catch (IOException ioe) {
580
            LOGGER.error("Error while creating piwik site", ioe);
581
            emailUtils.reportException(ioe);
582
            throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
583
        } catch (Exception e) {
584
            LOGGER.error("Error while sending email to administrator or user about the request to enable metrics", e);
585
            emailUtils.reportException(e);
586
        }
587
    }
588

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

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

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

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

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

  
609
            return piwikInfos;
610

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

  
618
    @Override
619
    public void markPiwikSiteAsValidated(String repositoryId) throws RepositoryServiceException {
620
        try {
621
            this.piwikDAO.markPiwikSiteAsValidated(repositoryId);
622

  
623
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repositoryId);
624
            emailUtils.sendAdministratorMetricsEnabled(piwikInfo);
625
            emailUtils.sendUserMetricsEnabled(piwikInfo);
626

  
627
        } catch (EmptyResultDataAccessException e) {
628
            LOGGER.error("Error while approving piwik site: ", e);
629
            emailUtils.reportException(e);
630
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
631
        } catch (Exception e) {
632
            LOGGER.error("Error while sending email to administrator or user about the enabling of metrics", e);
633
            emailUtils.reportException(e);
634
        }
635
    }
636

  
637
    @Override
638
    public MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException {
639
        try {
640

  
641
            MetricsInfo metricsInfo = new MetricsInfo();
642
            metricsInfo.setDiagramsBaseURL(this.usageStatisticsDiagramsBaseURL);
643
            metricsInfo.setMetricsNumbers(getMetricsNumbers(getOpenAIREId(repoId)));
644
            return metricsInfo;
645

  
646
        } catch (Exception e) {
647
            LOGGER.error("Error while getting metrics info for repository: ", e);
648
            emailUtils.reportException(e);
649
            throw new RepositoryServiceException("General error", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
650
        }
651
    }
652

  
653
    private MetricsNumbers getMetricsNumbers(String openAIREID) throws BrokerException {
654

  
655
        //build the uri params
656
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.usageStatisticsNumbersBaseURL + openAIREID + "/clicks");
657

  
658
        //create new template engine
659
        RestTemplate template = new RestTemplate();
660
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
661
        ResponseEntity<MetricsNumbers> resp;
662
        try {
663
            //communicate with endpoint
664
            resp = template.exchange(
665
                    builder.build().encode().toUri(),
666
                    HttpMethod.GET,
667
                    null,
668
                    new ParameterizedTypeReference<MetricsNumbers>() {
669
                    });
670
        } catch (RestClientException e) {
671
            throw e;
672
        }
673

  
674
        return resp.getBody();
675
    }
676

  
677
    private String getCountryCode(String countryName) {
678
        Vocabulary countries = this.getVocabulary("dnet:countries");
679

  
680
        return countries.getEncoding(countryName);
681
    }
682

  
683
    private String getDatasourceClassCode(String datasourceClassName) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff