Subversion Repositories linshare

[/] [branches/] [0.7/] [linshare/] [src/] [main/] [java/] [org/] [linagora/] [linShare/] [view/] [tapestry/] [rest/] [impl/] [UserRestServiceImpl.java] - Blame information for rev 167

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1 sbahloul
/*
2
 *    This file is part of Linshare.
3
 *
4
 *   Linshare is free software: you can redistribute it and/or modify
5
 *   it under the terms of the GNU Affero General Public License as
6
 *   published by the Free Software Foundation, either version 3 of
7
 *   the License, or (at your option) any later version.
8
 *
9
 *   Linshare is distributed in the hope that it will be useful,
10
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *   GNU Affero General Public License for more details.
13
 *
14
 *   You should have received a copy of the GNU Affero General Public
15
 *   License along with Foobar.  If not, see
16
 *                                    <http://www.gnu.org/licenses/>.
17
 *
18
 *   (c) 2008 Groupe Linagora - http://linagora.org
19
 *
20
*/
21
package org.linagora.linShare.view.tapestry.rest.impl;
22
 
23
import java.io.IOException;
24
import java.io.PrintWriter;
25
import java.net.URLDecoder;
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.Set;
32
import java.util.StringTokenizer;
33
 
34
import org.apache.commons.httpclient.HttpStatus;
35
import org.apache.tapestry5.Asset;
36
import org.apache.tapestry5.ioc.Messages;
37
import org.apache.tapestry5.ioc.services.ThreadLocale;
38
import org.apache.tapestry5.services.ApplicationStateManager;
39
import org.apache.tapestry5.services.Request;
40
import org.apache.tapestry5.services.Response;
41
import org.apache.tapestry5.services.ValidationMessagesSource;
42
import org.linagora.linShare.core.Facade.UserFacade;
43
import org.linagora.linShare.core.domain.vo.UserVo;
44
import org.linagora.linShare.core.exception.BusinessException;
45
import org.linagora.linShare.core.exception.TechnicalErrorCode;
46
import org.linagora.linShare.core.exception.TechnicalException;
47
import org.linagora.linShare.view.tapestry.rest.UserRestService;
48
import org.linagora.linShare.view.tapestry.services.Templating;
49
import org.linagora.linShare.view.tapestry.services.impl.PropertiesSymbolProvider;
50
import org.linagora.restmarshaller.Marshaller;
51
import org.slf4j.Logger;
52
import org.slf4j.LoggerFactory;
53
 
54
import us.antera.t5restfulws.RestfulWebMethod;
55
 
56
 
57
 
58
public class UserRestServiceImpl implements UserRestService {
59
 
60
        private final ApplicationStateManager applicationStateManager;
61
 
62
        private final UserFacade userFacade;
63
 
64
    private final Asset guestMailTemplate;
65
 
66
    private final Asset guestMailTemplateTxt;
67
 
68
        private final PropertiesSymbolProvider propertiesSymbolProvider;
69
 
70
        private final Templating templating;
71
 
72
 
73
        private final ValidationMessagesSource validationMessagesSource;
74
 
75
        private final Marshaller xstreamMarshaller;
76
 
77
        private final ThreadLocale threadLocale;
78
 
79
        private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class);
80
 
81
        public UserRestServiceImpl(final ApplicationStateManager applicationStateManager,
82
                        final UserFacade userFacade, final Asset guestMailTemplate, final Asset guestMailTemplateTxt,
83
                        final PropertiesSymbolProvider propertiesSymbolProvider,
84
                        final Templating templating,  final ValidationMessagesSource validationMessagesSource,
85
                        final ThreadLocale threadLocale,
86
                        final Marshaller xstreamMarshaller) {
87
                super();
88
                this.applicationStateManager = applicationStateManager;
89
                this.userFacade = userFacade;
90
                this.guestMailTemplate = guestMailTemplate;
91
                this.guestMailTemplateTxt = guestMailTemplateTxt;
92
                this.propertiesSymbolProvider = propertiesSymbolProvider;
93
                this.templating = templating;
94
                this.validationMessagesSource = validationMessagesSource;
95
                this.threadLocale = threadLocale;
96
                this.xstreamMarshaller = xstreamMarshaller;
97
        }
98
 
99
        @RestfulWebMethod
100
        public void createuser(Request request, Response response)
101
                        throws IOException {
102
 
103
                UserVo actor = applicationStateManager.getIfExists(UserVo.class);
104
 
105
                if (actor== null) {
106
                        response.sendError(HttpStatus.SC_UNAUTHORIZED, "You are not authorized to use this service");
107
                        return;
108
                }
109
 
110
                if (actor.isGuest()) {
111
                        response.sendError(HttpStatus.SC_FORBIDDEN, "You are not authorized to use this service");
112
                        return;
113
                }
114
 
115
                if (!"POST".equals(request.getMethod())) {
116
                        response.sendError(HttpStatus.SC_METHOD_NOT_ALLOWED, "Method not allowed");
117
                        response.setHeader("Allow", "POST");
118
                        return;
119
                }
120
 
121
                if (request.getParameterNames().size()<4) {
122
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Not enough parameters");
123
                        return;
124
                }
125
 
126
                if (!request.getParameterNames().contains("firstName")) {
127
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Missing parameter firstName");
128
                        return;
129
 
130
                }
131
                String firstName =request.getParameter("firstName") ;
132
 
133
                if (!request.getParameterNames().contains("lastName")) {
134
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Missing parameter lastName");
135
                        return;
136
 
137
                }
138
                String lastName =request.getParameter("lastName") ;
139
 
140
                if (!request.getParameterNames().contains("mail")) {
141
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Missing parameter mail");
142
                        return;
143
 
144
                }
145
                String mail =request.getParameter("mail") ;
146
 
147
                // must validate the mail format
148
                if (!mail.matches("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?")) {
149
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Wrong mail type");
150
                        return;
151
                }
152
 
153
                if (!request.getParameterNames().contains("canUpload")) {
154
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Missing parameter canUpload");
155
                        return;
156
 
157
                }
158
                String canUpload =request.getParameter("canUpload") ;
159
                String canCreateGuest =request.getParameter("canCreateGuest") ;
160
 
161
                // Get the messages service to localize the mail sent
162
                Messages messages = validationMessagesSource.getValidationMessages(threadLocale.getLocale());
163
 
164 167 sduprey
                String url=propertiesSymbolProvider.valueForSymbol("linshare.info.url.base");
165 1 sbahloul
 
166
        String ownerCN = actor.getFirstName() + " " + actor.getLastName();
167
 
168
                Map<String,String> hash=new HashMap<String, String>();
169
 
170
                // Create the template
171
                hash.put("${message}", "");
172
                hash.put("${ownerCN}", ownerCN);
173
                hash.put("${firstName}", firstName);
174
                hash.put("${lastName}", lastName);
175
        hash.put("${mail}", mail);
176
                hash.put("${url}", url);
177
 
178
                String mailContent; // in html
179
                String mailContentTxt;
180
 
181
                try {
182
                        mailContent = templating.getMessage(guestMailTemplate.getResource().openStream(), hash);
183
                        mailContentTxt = templating.getMessage(guestMailTemplateTxt.getResource().openStream(), hash);
184
                } catch (IOException e) {
185
                        logger.error("Bad mail template", e);
186
                        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION,"Bad template",e);
187
                }
188
 
189
                boolean uploadGranted = ((canUpload != null) && ("true".equals(canUpload)));
190
                boolean createGuestGranted = ((canCreateGuest != null) && ("true".equals(canCreateGuest)));
191
 
192
        try {
193
            userFacade.createGuest(mail, firstName, lastName, uploadGranted, createGuestGranted, "",
194
                messages.get("mail.user.guest.create.subject"), mailContent, mailContentTxt, actor);
195
            logger.info("User " + mail + " successfully created");
196
        } catch (BusinessException e) {
197
                logger.error(e.toString());
198
                response.setHeader("BusinessError", e.getErrorCode().getCode()+"");
199
                response.sendError(HttpStatus.SC_METHOD_FAILURE, "Couldn't create the user " + e.getMessage());
200
                return;
201
        }
202
 
203
        UserVo user = userFacade.findUser(mail);
204
 
205
        String xml = xstreamMarshaller.toXml(user);
206
 
207
                PrintWriter writer = response.getPrintWriter("text/xml");
208
                response.setStatus(HttpStatus.SC_CREATED);
209
 
210
                // Write the location of the new ressource
211
                response.setHeader("Location", url +"userrestservice/getuser/" + user.getMail());
212
                writer.append(xml);
213
                writer.flush();
214
                writer.close();
215
 
216
        }
217
 
218
 
219
        @RestfulWebMethod
220
        public void getuser(Request request, Response response, String mail)
221
                        throws IOException {
222
 
223
                UserVo actor = applicationStateManager.getIfExists(UserVo.class);
224
 
225
                if (actor== null) {
226
                        response.sendError(HttpStatus.SC_UNAUTHORIZED, "You are not authorized to use this service");
227
                        return;
228
                }
229
 
230
                if ( (actor.isGuest() && (!actor.isUpload()))) {
231
                        response.sendError(HttpStatus.SC_FORBIDDEN, "You are not authorized to use this service");
232
                        return;
233
                }
234
 
235
                // fetch the target             
236
                UserVo user = userFacade.findUser(mail);
237
 
238
                if (user == null) {
239
                        response.sendError(HttpStatus.SC_NOT_FOUND, "User not found");
240
                        return;
241
                }
242
                String xml = xstreamMarshaller.toXml(user);
243
 
244
                PrintWriter writer = response.getPrintWriter("text/xml");
245
                response.setStatus(HttpStatus.SC_OK);
246
                writer.append(xml);
247
                writer.flush();
248
                writer.close();
249
        }
250
 
251
        @RestfulWebMethod
252
        public void autoCompleteUser(Request request, Response response, String mail) throws IOException {
253
                UserVo actor = applicationStateManager.getIfExists(UserVo.class);
254
 
255
                if (actor== null) {
256
                        response.sendError(HttpStatus.SC_UNAUTHORIZED, "You are not authorized to use this service");
257
                        return;
258
                }
259
 
260
                if ( (actor.isGuest() && (!actor.isUpload()))) {
261
                        response.sendError(HttpStatus.SC_FORBIDDEN, "You are not authorized to use this service");
262
                        return;
263
                }
264
 
265
                if (mail == null || mail.length() == 0) {
266
                        response.sendError(HttpStatus.SC_BAD_REQUEST, "Missing parameter mail");
267
                        return;
268
 
269
                }
270
                mail = URLDecoder.decode(mail, "utf-8");
271
                String firstName = null;
272
                String lastName = null;
273
 
274
                StringTokenizer stringTokenizer = new StringTokenizer(mail, " ");
275
                if (stringTokenizer.hasMoreTokens()) {
276
                        firstName = stringTokenizer.nextToken();
277
                        if (stringTokenizer.hasMoreTokens()) {
278
                                lastName = stringTokenizer.nextToken();
279
                        }
280
                }
281
 
282
                Set<UserVo> userSet = new HashSet<UserVo>();
283
        userSet.addAll(userFacade.searchUser(mail.trim(), null, null, actor));
284
                userSet.addAll(userFacade.searchUser(null, firstName, lastName, actor));
285
                userSet.addAll(userFacade.searchUser(null, lastName, firstName, actor));
286
 
287
 
288
                List<UserVo> listUser =  new ArrayList<UserVo>(userSet);
289
 
290
                if (listUser.size()==0) {
291
                        response.sendError(HttpStatus.SC_NOT_FOUND, "User not found");
292
                        return;
293
                }
294
                String xml = xstreamMarshaller.toXml(listUser);
295
 
296
                PrintWriter writer = response.getPrintWriter("text/xml");
297
                response.setStatus(HttpStatus.SC_OK);
298
                writer.append(xml);
299
                writer.flush();
300
                writer.close();
301
 
302
        }
303
 
304
}