Project

General

Profile

« Previous | Next » 

Revision 50588

New api changes

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/FrontEndLinkURIAuthenticationSuccessHandler.java
1
package eu.dnetlib.repo.manager.server.utils;
2

  
3
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
4
import org.springframework.security.core.Authentication;
5
import org.springframework.security.core.context.SecurityContextHolder;
6
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
7

  
8
import javax.servlet.ServletException;
9
import javax.servlet.http.Cookie;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13

  
14

  
15
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
16

  
17

  
18
    private String frontEndURI;
19

  
20
    @Override
21
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
22
        OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
23
        Cookie sessionCookie = new Cookie("currentUser", authOIDC.getSub());
24
        int expireSec = -1;
25
        sessionCookie.setMaxAge(expireSec);
26
        sessionCookie.setPath("/");
27
        response.addCookie(sessionCookie);
28
        response.sendRedirect(frontEndURI);
29
    }
30

  
31
    public String getFrontEndURI() {
32
        return frontEndURI;
33
    }
34

  
35
    public void setFrontEndURI(String frontEndURI) {
36
        this.frontEndURI = frontEndURI;
37
    }
38
}
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 com.google.gwt.user.client.Cookies;
4
import eu.dnetlib.domain.functionality.UserProfile;
5
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
6
import eu.dnetlib.repo.manager.client.services.UserService;
7
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
8
import eu.dnetlib.repo.manager.shared.Tuple;
9
import eu.dnetlib.repo.manager.shared.UserAccessException;
10
import eu.dnetlib.users.UserApi;
11
import org.apache.log4j.Logger;
12
import org.eclipse.jetty.server.Authentication;
13
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.security.core.context.SecurityContextHolder;
16
import org.springframework.stereotype.Service;
17
import org.springframework.web.context.request.RequestContextHolder;
18

  
19
import javax.servlet.ServletConfig;
20
import javax.servlet.ServletException;
21
import javax.servlet.http.Cookie;
22
import javax.servlet.http.HttpSession;
23
import java.util.ArrayList;
24
import java.util.Arrays;
25
import java.util.List;
26
import java.util.regex.Pattern;
27

  
28
/**
29
 * Created by nikonas on 12/7/15.
30
 */
31
@Service("userService")
32
public class UserServiceImpl extends SpringGwtRemoteServiceServlet implements UserService {
33

  
34
    private static final Logger LOGGER = Logger
35
            .getLogger(UserServiceImpl.class);
36

  
37
    @Autowired
38
    private UserApi userAPI;
39

  
40
    @Autowired
41
    private EmailUtils emailUtils;
42

  
43

  
44
    public void init(ServletConfig config) throws ServletException {
45

  
46
        LOGGER.info("initializing user service impl ");
47
        super.init(config);
48

  
49
    }
50

  
51
    @Override
52
    public Tuple<UserProfile, String> login(String email_username, String password) throws UserAccessException {
53
        LOGGER.info("Checking credentials for user " + email_username);
54
        try {
55

  
56
            String email = email_username;
57

  
58
            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])?$");
59
            if (!rfc2822.matcher(email_username.trim().toLowerCase()).matches()) {
60
                LOGGER.debug("user logged in using username");
61
                email = this.userAPI.getEmailFromUsername(email_username);
62
            }
63
            if (email == null) {
64
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
65
            }
66
            if (!this.userAPI.userExists(email)) {
67
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
68
            }
69
            if (!this.userAPI.isUserActivated(email)) {
70
                throw new UserAccessException("login.notActivated", UserAccessException.ErrorCode.NOT_ACTIVATED);
71
            }
72
            if (!this.userAPI.correctCreds(email, password)) {
73
                throw new UserAccessException("login.InvalidPassword", UserAccessException.ErrorCode.INVALID_PASSWORD);
74
            }
75

  
76
            UserProfile userProfile = this.userAPI.getUser(email);
77
            String role = "";
78

  
79
            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"};
80
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
81
                role = "admin";
82

  
83
            return new Tuple<>(userProfile, role);
84

  
85
        } catch (Exception e) {
86
            LOGGER.error("An error occurred while checking credentials for user " + email_username, e);
87
            emailUtils.reportException(e);
88

  
89
            if (e instanceof UserAccessException) {
90
                throw (UserAccessException) e;
91
            }
92
            else {
93
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
94
            }
95
        }
96

  
97
    }
98

  
99
    @Override
100
    public Tuple<UserProfile, String> getUserByEmail(String email) throws UserAccessException {
101
        LOGGER.info("Getting user with email " + email);
102
        try {
103

  
104
            UserProfile userProfile = this.userAPI.getUser(email);
105
            String role = "";
106

  
107
            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"};
108
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
109
                role = "admin";
110

  
111
            return new Tuple<>(userProfile, role);
112

  
113
        } catch (Exception e) {
114
            LOGGER.error("An error occurred while getting user with email " + email, e);
115
            emailUtils.reportException(e);
116

  
117
            throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
118
        }
119
    }
120

  
121
    @Override
122
    public void register(UserProfile userProfile) throws UserAccessException {
123

  
124
        try {
125
            LOGGER.info("Registering user " + userProfile.getEmail());
126

  
127
            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])?$");
128
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
129
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
130
            }
131

  
132
            if (this.userAPI.usernameExists(userProfile.getUsername())) {
133
                throw new UserAccessException("login.usernameAlreadyExists", UserAccessException.ErrorCode.USERNAME_ALREADY_EXISTS);
134
            }
135
            if (this.userAPI.userExists(userProfile.getEmail())) {
136
                throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
137
            }
138

  
139
//            String activationId = "TEST";
140
            String activationId = this.userAPI.addUser(userProfile.getUsername(), userProfile.getEmail(), userProfile.getPassword(), userProfile.getFirstname(), userProfile.getLastname(), userProfile.getInstitution());
141

  
142
            emailUtils.sendActivationEmail(userProfile, activationId);
143

  
144
        } catch (Exception e) {
145
            LOGGER.error("Error while registering user " + userProfile.getEmail(), e);
146
            emailUtils.reportException(e);
147

  
148
            if (e instanceof UserAccessException)
149
                throw (UserAccessException) e;
150
            else
151
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
152
        }
153

  
154
    }
155

  
156
    @Override
157
    public void activateUser(String activationId) throws UserAccessException {
158
        try {
159
            LOGGER.info("Activating user with activation with activation id " + activationId);
160

  
161
            if (!this.userAPI.activateUser(activationId))
162
                throw new UserAccessException("registration.okAccountAlreadyActivation", UserAccessException.ErrorCode.ALREADY_ACTIVATED);
163
        } catch (Exception e) {
164
            LOGGER.error("Error while activating user account with activation id " + activationId, e);
165
            emailUtils.reportException(e);
166

  
167
            if (e instanceof UserAccessException)
168
                throw (UserAccessException) e;
169
            else
170
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
171
        }
172
    }
173

  
174
    @Override
175
    public void updateUser(UserProfile userProfile) throws UserAccessException {
176
        try {
177
            LOGGER.info("Editing user " + userProfile.getUsername());
178
            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])?$");
179
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
180
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
181
            }
182

  
183
            String currentEmail = this.userAPI.getEmailFromUsername(userProfile.getUsername());
184
            if (!userProfile.getEmail().equalsIgnoreCase(currentEmail)) {
185
                if (this.userAPI.userExists(userProfile.getEmail())) {
186
                    throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
187
                }
188
            }
189

  
190
            this.userAPI.editUser(userProfile);
191

  
192
        } catch (Exception e) {
193
            LOGGER.error("Error while editing user " + userProfile.getUsername(), e);
194
            if (e instanceof UserAccessException)
195
                throw (UserAccessException) e;
196
            else
197
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
198
        }
199
    }
200

  
201
    @Override
202
    public void prepareResetPassword(String email) throws UserAccessException {
203

  
204
        try {
205
            LOGGER.debug("Sending password recovery to user " + email);
206
            if (!this.userAPI.userExists(email)) {
207
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
208
            }
209
            List<String> to = new ArrayList<String>();
210
            to.add(email);
211
            String securityCode = this.userAPI.prepareResetPassword(email);
212

  
213
            emailUtils.sendResetPasswordEmail(email, securityCode);
214

  
215
        } catch (Exception e) {
216
            LOGGER.error("Error while sending password recovery to user " + email, e);
217
            emailUtils.reportException(e);
218

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

  
226
    @Override
227
    public void resetPassword(String securityCode, String password) throws UserAccessException {
228
        try {
229
            LOGGER.debug("Reseting password with security code " + securityCode);
230

  
231
            if (securityCode.length() == 0) {
232
                throw new UserAccessException("resetPassword.wrongSecurityCode", UserAccessException.ErrorCode.WRONG_SECURITY_CODE);
233
            }
234

  
235
            this.userAPI.resetPassword(securityCode, password);
236

  
237
        } catch (Exception e) {
238
            LOGGER.error("Error while reseting password with security code " + securityCode);
239
            emailUtils.reportException(e);
240

  
241
            if (e instanceof UserAccessException)
242
                throw (UserAccessException) e;
243
            else
244
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
245
        }
246
    }
247

  
248
    @Override
249
    public void resendActivation(String email) throws UserAccessException {
250

  
251
    }
252

  
253
    @Override
254
    public Tuple<UserProfile, String> checkCookie() throws Exception {
255
        OIDCAuthenticationToken authentication;
256
        try {
257
            authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
258
            UserProfile userProfile = new UserProfile();
259
            userProfile.setFirstname(authentication.getUserInfo().getGivenName());
260
            userProfile.setLastname(authentication.getUserInfo().getFamilyName());
261
            userProfile.setEmail(authentication.getUserInfo().getEmail());
262

  
263
            LOGGER.debug("User email -> " + userProfile.getEmail());
264

  
265
            String role = "";
266
            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"};
267
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
268
                role = "admin";
269
            return new Tuple<>(userProfile, role);
270
        } catch (Exception e) {
271
            LOGGER.debug("Error on security context holder",e);
272
            LOGGER.debug(Cookies.getCookie("currentUser"));
273
            throw e;
274
        }
275
    }
276

  
277
    @Override
278
    public void clearCookie(){
279
        SecurityContextHolder.clearContext();
280
    }
281

  
282
}
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
            Boolean managed = null;
132
            List<Repository> reposList = repositoryApi.getRepositoriesByCountry(country,mode,managed);
133
            if (reposList == null) {
134
                retTuple.setFirst(new ArrayList<Repository>());
135
//                if (!includeUnknownCountries) {
136
//                    throw new RepositoryServiceException("registration.noReposForThisCountry", RepositoryServiceException.ErrorCode.NO_REPOS_FOR_THIS_COUNTRY);
137
//                }
138
            } else {
139
                retTuple.setFirst(reposList);
140
            }
141

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

  
153
            return retTuple;
154

  
155
        } catch (Exception e) {
156
            LOGGER.error("Error while getting repositories of country: " + country + " with type: " + mode + " and includeUnknownCountries: " + includeUnknownCountries, e);
157
            if (e instanceof RepositoryServiceException) {
158
                throw (RepositoryServiceException) e;
159
            } else {
160
                emailUtils.reportException(e);
161
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
162
            }
163
        }
164
    }
165

  
166
    @Override
167
    public List<Repository> getRepositoriesByCountry(String country, String mode) throws RepositoryServiceException {
168
        return this.getRepositoriesByCountry(country, mode, false).getFirst();
169
    }
170

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
288
            return countriesMap;
289

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

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

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

  
318
    }
319

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

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

  
338
    @Override
339
    public Map<String, String> getCompatibilityClasses(String mode) throws RepositoryServiceException {
340
        return repositoryApi.getCompatibilityClasses(mode);
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
            //List<RepositoryInterface> interfacesToRegister = new ArrayList<RepositoryInterface>();
349
            JSONObject params = new JSONObject();
350
            params.put("datatype", mode);
351
            ObjectMapper mapper = new ObjectMapper();
352
            String json_repo = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(repo);
353
            params.put("repository", json_repo);*/
354

  
355

  
356
            //repositoryApi.addRepository(params.toString());
357
            repositoryApi.addRepository(mode,repo);
358
            LOGGER.debug("Repository with name: " + repo.getOfficialName() + " stored!");
359

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

  
367
    @Override
368
    public void updateRepositoryInformation(Repository repo) throws RepositoryServiceException {
369
        try {
370
            LOGGER.debug("Updating information of repo: " + repo.getOfficialName());
371

  
372
	    //TODO SOS, check old API
373

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

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

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

  
402
            return retIface;
403
        } catch (Exception e) {
404
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
405
            if (e instanceof RepositoryServiceException) {
406
                throw (RepositoryServiceException) e;
407
            } else {
408
                emailUtils.reportException(e);
409
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
410
            }
411
        }
412
    }
413

  
414
    @Override
415
    public RepositoryInterface insertInterface(RepositoryInterface iFace, String repoId, String datatype) throws RepositoryServiceException {
416
        try {
417
            LOGGER.debug("inserting interface with id: " + iFace.getId());
418
            RepositoryInterface retIface = null;
419
            //retIface = this.repoAPI.insertRepositoryInterfaceWithoutChecks(repoId, iFace, datatype);
420

  
421
          /*  JSONObject params = new JSONObject();
422
            params.put("datatype",datatype);
423
            params.put("repoId",repoId);
424
            params.put("iFace",iFace);*/
425
            //retIface = repositoryApi.addRepositoryInterface(params.toString());
426

  
427
            retIface = repositoryApi.addRepositoryInterface(datatype,repoId,iFace);
428
            retIface.setComplianceName(this.getComplianceName(retIface.getCompliance()));
429
            return retIface;
430

  
431
        } catch (Exception e) {
432
            LOGGER.error("error updating interface with id: " + iFace.getId(), e);
433
            if (e instanceof RepositoryServiceException) {
434
                throw (RepositoryServiceException) e;
435
            } else {
436
                emailUtils.reportException(e);
437
                throw new RepositoryServiceException("login.generalError", RepositoryServiceException.ErrorCode.GENERAL_ERROR);
438
            }
439
        }
440
    }
441

  
442
    @Override
443
    public void deleteInterface(String repoId, RepositoryInterface iFace, String datatype) throws RepositoryServiceException {
444
        List<RepositoryInterface> iFaces = new ArrayList<RepositoryInterface>();
445
        iFaces.add(iFace);
446
        this.deleteInterfaces(repoId, iFaces, datatype);
447
    }
448

  
449
    @Override
450
    public void deleteInterfaces(String repoId, List<RepositoryInterface> iFaces, String datatype) throws RepositoryServiceException {
451
        try {
452
            LOGGER.debug("deleting interfaces of repo: " + repoId);
453
            //this.repoAPI.deleteRepositoryInterfacesWithoutChecks(repoId, iFaces, datatype);
454

  
455
            for(RepositoryInterface iFace : iFaces) {
456
                LOGGER.info("deleting repository interface with url/set/id: " + iFace.getBaseUrl() + "/"
457
                        + iFace.getAccessSet() + "/" + iFace.getId());
458
                repositoryApi.deleteRepositoryInterface(iFace.getId());
459
            }
460

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

  
471
    }
472

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

  
484
            return vocs;
485

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

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

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

  
505
            retTuple.setFirst(reposList);
506

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

  
513
                retTuple.setSecond(totalList);
514
            }
515

  
516
            return retTuple;
517

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

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

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

  
542
    @Override
543
    public PiwikInfo getPiwikSiteForRepository(String repoId) throws RepositoryServiceException {
544
        try {
545
            LOGGER.debug("Repo id -> " + repoId);
546
            return this.piwikDAO.getPiwikSiteForRepo(repoId);
547
        } catch (EmptyResultDataAccessException e) {
548
            return null;
549
        }
550
    }
551

  
552
    @Override
553
    public void enableMetricsForRepository(Repository repository, UserProfile requestor) throws RepositoryServiceException {
554
        
555
        try {
556
            String URL = analyticsURL + "siteName=" + URLEncoder.encode(repository.getOfficialName(), "UTF-8") + "&url=" + URLEncoder.encode(repository.getWebsiteUrl(), "UTF-8");
557
            Map<String, Object> map = new ObjectMapper().readValue(new URL(URL), Map.class);
558

  
559
            String siteId = null;
560
            if(map.get("value")!=null) {
561
                siteId = map.get("value").toString();
562
            }
563

  
564
            String authenticationToken = "32846584f571be9b57488bf4088f30ea";
565

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

  
576
            this.piwikDAO.savePiwikInfo(piwikInfo);
577

  
578
            emailUtils.sendAdministratorRequestToEnableMetrics(piwikInfo);
579
            emailUtils.sendUserRequestToEnableMetrics(piwikInfo);
580

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

  
595
    @Override
596
    public String getPiwikScriptForRepository(String repoId) throws RepositoryServiceException {
597
        try {
598
            PiwikInfo piwikInfo = this.piwikDAO.getPiwikSiteForRepo(repoId);
599

  
600
            String piwikScript = PIWIK_SCRIPT.replace("$$$", piwikInfo.getSiteId());
601
            return piwikScript;
602

  
603
        } catch (EmptyResultDataAccessException e) {
604
            return null;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff