-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContributions.java
6340 lines (5799 loc) · 323 KB
/
Contributions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package controllers;
import be.objectify.deadbolt.java.actions.Dynamic;
import be.objectify.deadbolt.java.actions.Group;
import be.objectify.deadbolt.java.actions.Restrict;
import be.objectify.deadbolt.java.actions.SubjectPresent;
import com.amazonaws.services.simpleemail.model.NotificationType;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Model;
import com.avaje.ebean.SqlUpdate;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.user.AuthUser;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.field.RtfPageNumber;
import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter;
import delegates.ContributionsDelegate;
import delegates.NotificationsDelegate;
import delegates.ResourcesDelegate;
import delegates.WorkingGroupsDelegate;
import enums.*;
import exceptions.ConfigurationException;
import exceptions.MembershipCreationException;
import http.Headers;
import io.swagger.annotations.*;
import models.*;
import models.location.Location;
import models.misc.Views;
import models.transfer.*;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import play.Logger;
import play.Play;
import play.data.Form;
import play.i18n.Lang;
import play.i18n.Messages;
import play.libs.F;
import play.libs.F.Promise;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.With;
import play.twirl.api.Content;
import providers.MyUsernamePasswordAuthProvider;
import security.SecurityModelConstants;
import service.PlayAuthenticateLocal;
import utils.GlobalData;
import utils.GlobalDataConfigKeys;
import utils.LogActions;
import utils.Packager;
import utils.security.HashGenerationException;
import utils.services.EtherpadWrapper;
import utils.services.PeerDocWrapper;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.persistence.EntityNotFoundException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
import static play.data.Form.form;
import static security.CoordinatorOrAuthorDynamicResourceHandler.checkIfCoordinator;
@Api(value = "05 contribution: Contribution Making", description = "Contribution Making Service: contributions by citizens to different spaces of civic engagement")
@With(Headers.class)
public class Contributions extends Controller {
public static final Form<Contribution> CONTRIBUTION_FORM = form(Contribution.class);
public static final Form<ContributionFeedback> CONTRIBUTION_FEEDBACK_FORM = form(ContributionFeedback.class);
public static final Form<Resource> ATTACHMENT_FORM = form(Resource.class);
public static final Form<ThemeListTransfer> THEMES_FORM = form(ThemeListTransfer.class);
public static final Form<User> AUTHORS_FORM = form(User.class);
public static final String CONTRIBUTION_ID_PARAM = "{contribution_id}";
public static final String EXTENDED_PAD_NAME = "contribution_doc_"+ CONTRIBUTION_ID_PARAM;
public static final String CONTRIBUTION_FILE_NAME = "contribution_"+ CONTRIBUTION_ID_PARAM;
public static final Form<NonMemberAuthor> NON_MEMBER_AUTHORS_FORM = form(NonMemberAuthor.class);
private static BufferedReader br;
public enum CSVHeaders {
code, source, title, description, category, keywords, date, location, group, authors, phones, emails
}
/**
* GET /api/assembly/:aid/contribution
*
* @param aid
* @param space
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List", produces = "application/json", value = "Get contributions in Assembly")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result findAssemblyContributions(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "space", value = "Resource space name within assembly from which we want to query contributions", allowableValues = "forum,resources", defaultValue = "forum") String space,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note, discussion", defaultValue = "idea") String type) {
Assembly a = Assembly.read(aid);
ResourceSpace rs = null;
if (a != null) {
if (space != null && space.equals("forum"))
rs = a.getForum();
else
rs = a.getResources();
}
List<Contribution> contributions = ContributionsDelegate
.findContributionsInResourceSpace(rs, type, null);
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No resource space for assembly: " + aid)));
}
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List",
produces = "application/json", value = "Get contributions childrens or parent by type")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
public static Result getContributionChildrenOrParent(
@ApiParam(name = "uuid", value = "Contribution UUID") UUID uuid,
@ApiParam(name = "type", value = "Type of contributions",
allowableValues = "FORKS, MERGES, PARENT") String type) {
List<Contribution> contributions = Contribution.findChildrenOrParents(uuid, type);
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No contributions for contribution: " + uuid)));
}
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List",
produces = "application/json", value = "Get contributions childrens or parent by type")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
public static Result getContributionMergeAuthors(
@ApiParam(name = "uuid", value = "Contribution UUID") UUID uuid) {
Set<User> contributions = Contribution.findMergeAuthors(uuid);
return contributions == null || contributions.isEmpty() ? notFound(Json.toJson(new TransferResponseStatus(
"No authors for contribution: " + uuid))) : ok(Json.toJson(contributions));
}
/**
* GET /api/assembly/:aid/campaign/:cid/component/:ciid/contribution
*
* @param aid
* @param cid
* @param ciid
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List",
produces = "application/json", value = "Get contributions in a component of a campaign within an assembly")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result findCampaignComponentContributions(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "ciid", value = "Component ID") Long ciid,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note, discussion", defaultValue = "idea") String type) {
Component c = Component.read(cid, ciid);
ResourceSpace rs = null;
if (c != null) {
rs = c.getResourceSpace();
}
List<Contribution> contributions = ContributionsDelegate
.findContributionsInResourceSpace(rs, type, null);
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No contributions for {assembly, campaign, component}: " + aid + ", " + cid + ", " + ciid)));
}
/**
* GET /api/assembly/:aid/campaign/:cid/contribution
*
* @param aid
* @param cid
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List", produces = "application/json", value = "Get contributions in a Campaign")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result findCampaignContributions(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note, discussion", defaultValue = "idea") String type) {
Campaign c = Campaign.read(cid);
ResourceSpace rs = null;
if (c != null) {
rs = c.getResources();
}
List<Contribution> contributions = ContributionsDelegate
.findContributionsInResourceSpace(rs, type, null);
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No contributions for {assembly, campaign}: " + aid + ", " + cid)));
}
/**
* GET /api/assembly/:aid/group/:gid/contribution
*
* @param aid
* @param gid
* @param space
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List", produces = "application/json", value = "Get contributions in a Working Group")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result findAssemblyGroupContributions(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "gid", value = "Working Group ID") Long gid,
@ApiParam(name = "space", value = "Resource space name within the working group from which we want to query contributions", allowableValues = "forum,resources", defaultValue = "forum") String space,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note, discussion", defaultValue = "idea") String type) {
WorkingGroup wg = WorkingGroup.read(gid);
ResourceSpace rs = null;
if (wg != null) {
if (space != null && space.equals("forum"))
rs = wg.getForum();
else
rs = wg.getResources();
}
List<Contribution> contributions = ContributionsDelegate
.findContributionsInResourceSpace(rs, type, null);
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No resource space for assembly: " + aid)));
}
/**
* GET /api/assembly/:aid/contribution/:cid
*
* @param aid
* @param contributionId
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, produces = "application/json", value = "Get contribution by ID")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result findContribution(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Contribution ID") Long contributionId) {
Contribution contribution = Contribution.read(contributionId);
if(contribution.getExtendedTextPad() != null && contribution.getExtendedTextPad().getResourceType().equals(ResourceTypes.PEERDOC)) {
User user = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session()));
PeerDocWrapper peerDocWrapper = new PeerDocWrapper(user);
try {
contribution.getExtendedTextPad().setUrl(new URL(contribution.getExtendedTextPad()
.getUrlAsString() + "?user=" + peerDocWrapper.encrypt()));
} catch (Exception e) {
contribution.setErrorsInExtendedTextPad("Error reading the pad " + e.getMessage());
return ok(Json.toJson(contribution));
}
}
return ok(Json.toJson(contribution));
}
/**
* GET /api/space/:sid/contribution
*
* @param sid
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List", produces = "application/json",
value = "Get contributions in a specific Resource Space",
notes = "Every entity in AppCivist has a Resource Space to associate itself to other entities")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
// @SubjectPresent
public static Result findResourceSpaceContributions(
@ApiParam(name = "sid", value = "Resource Space ID") Long sid,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note", defaultValue = "") String type,
@ApiParam(name = "by_text", value = "String") String byText,
@ApiParam(name = "by_location", value = "String") String byLocation,
@ApiParam(name = "groups", value = "List") List<Integer> byGroup,
@ApiParam(name = "themes", value = "List") List<Integer> byTheme,
@ApiParam(name = "all", value = "Boolean") String all,
@ApiParam(name = "by_author", value = "Author ID") Integer authorId,
@ApiParam(name = "page", value = "Page", defaultValue = "0") Integer page,
@ApiParam(name = "pageSize", value = "Number of elements per page") Integer pageSize,
@ApiParam(name = "sorting", value = "Ordering of proposals",
allowableValues = "date_asc, date_desc, random, popularity_asc, popularity_desc, most_commented_asc, most_commented_desc, most_commented_public_asc, most_commented_public_desc, most_commented_members_asc, most_commented_members_desc")
String sorting,
@ApiParam(name = "status", value = "String") String status,
@ApiParam(name = "format", value = "Export format", allowableValues = "JSON,CSV,TXT,PDF,RTF,DOC")
String format,
@ApiParam(name = "includeExtendedText", value = "Include or not extended text") String includeExtendedText,
@ApiParam(name = "extendedTextFormat", value = "Include or not extended text", allowableValues =
"JSON,CSV,TXT,PDF,RTF,DOC") String extendedTextFormat,
@ApiParam(name = "collectionFileFormat", value = "Select the format for the file that contains the collection of contributions",
allowableValues = "JSON,CSV") String collectionFileFormat,
@ApiParam(name = "selectedContributions", value = "Array of contribution IDs to get") List<String> selectedContributions,
@ApiParam(name = "statusStartDate", value = "String") String statusStartDate,
@ApiParam(name = "statusEndDate", value = "String") String statusEndDate,
@ApiParam(name = "excludeCreatedByUser", value = "Array of created users to exclude IDs to get") List<Long> excludeCreatedByUser,
@ApiParam(name = "createdByOnly", value = "Include or not only creators authors" , defaultValue = "false") String createdByOnly)
{
User user = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session()));
format = format.toUpperCase();
extendedTextFormat = extendedTextFormat.toUpperCase();
if (pageSize == null) {
pageSize = GlobalData.DEFAULT_PAGE_SIZE;
}
boolean creatorOnly = false;
if(createdByOnly != null && createdByOnly.equals("true")) {
creatorOnly = true;
}
ResourceSpace rs = ResourceSpace.read(sid);
List<Contribution> contributions;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Map<String, Object> conditions = new HashMap<>();
conditions.put("containingSpaces", rs.getResourceSpaceId());
if (type != null && !type.isEmpty()) {
ContributionTypes mappedType = ContributionTypes.valueOf(type.toUpperCase());
conditions.put("type", mappedType);
}
if (byText != null && !byText.isEmpty()) {
conditions.put("by_text", byText);
}
if (byLocation != null && !byLocation.isEmpty()) {
conditions.put("by_location", byLocation);
}
if (authorId != null && authorId != 0) {
conditions.put("by_author", authorId);
}
if (byGroup != null && !byGroup.isEmpty()) {
conditions.put("group", byGroup);
}
if (excludeCreatedByUser != null && !excludeCreatedByUser.isEmpty()) {
conditions.put("excludeCreatedByUser", excludeCreatedByUser);
}
if (byTheme != null && !byTheme.isEmpty()) {
conditions.put("theme", byTheme);
}
if (sorting != null && !sorting.isEmpty()) {
conditions.put("sorting", sorting);
}
if (selectedContributions != null && !selectedContributions.isEmpty()) {
conditions.put("selectedContributions", selectedContributions);
}
if (status != null && !status.isEmpty()) {
conditions.put("status", status);
} else if (!rs.getType().equals(ResourceSpaceTypes.WORKING_GROUP)) {
conditions.put("status", "PUBLISHED,INBALLOT,SELECTED,PUBLIC_DRAFT");
}
try {
if (statusEndDate != null && !statusEndDate.isEmpty()) {
conditions.put("statusEndDate", dateFormat.parse(statusEndDate));
}
if (statusStartDate != null && !statusStartDate.isEmpty()) {
conditions.put("statusStartDate", dateFormat.parse(statusStartDate));
}
} catch (ParseException e) {
return badRequest(Json
.toJson(new TransferResponseStatus(
ResponseStatus.BADREQUEST,
"Error in date formatting: " + e.getMessage())));
}
if (sorting!= null && sorting.contains("feedback_")) {
if (!sorting.contains("need") &&
!sorting.contains("feasibility") && !sorting.contains("benefit") && !sorting.contains("all"))
{
return badRequest(Json
.toJson(new TransferResponseStatus(
ResponseStatus.BADREQUEST, "Error in feedback filter param doesnt exist")));
} else {
if (!sorting.contains("_avg") && !sorting.contains("_sum") && !sorting.contains("_count")) {
return badRequest(Json
.toJson(new TransferResponseStatus(
ResponseStatus.BADREQUEST, "You need to specify the aggregate function: avg,sum or count")));
}
}
}
PaginatedContribution pag = new PaginatedContribution();
List<Contribution> contribs = ContributionsDelegate.findContributions(conditions, null, null, creatorOnly);
contributions = ContributionsDelegate.findContributions(conditions, page, pageSize, creatorOnly);
pag.setPageSize(pageSize);
pag.setTotal(contribs.size());
pag.setPage(page);
if (all != null) {
pag.setPageSize(pag.getTotal());
pag.setPage(0);
pag.setList(contribs);
contributions.clear();
contributions.addAll(contribs);
} else {
pag.setList(contributions);
}
if (contributions == null || contributions.isEmpty()) {
return notFound(Json.toJson(new TransferResponseStatus(
"No contributions for {resource space}: " + sid + ", type=" + type)));
} else {
Boolean sendMail = false;
if (!(format.equals("JSON") || format.equals("CSV")) || includeExtendedText.toUpperCase().equals("TRUE")) {
Logger.info("Format is not json or csv and include extendedtext is true, mail will be send");
sendMail = true;
}
if (!sendMail) {
Logger.info("Mail will not send");
if (format.equals("JSON")) {
return ok(Json.toJson(pag));
}
if (format.equals("CSV")) {
response().setContentType("application/csv");
response().setHeader("Content-disposition", "attachment; filename=proposal.csv");
try {
Logger.info("Preparing CSV file");
File tempFile = File.createTempFile("contributions.csv", ".tmp");
CSVPrinter csvFilePrinter = null;
FileWriter fileWriter = new FileWriter(tempFile);
int first = 0;
for(Contribution contribution: contributions) {
Logger.info("Creating csv row for contribution " + contribution.getContributionId());
LinkedHashMap<String, String> contributionMap = getContributionMapToExport(contribution);
if(first == 0) {
first = 1;
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(contributionMap.keySet().toArray(new String[contributionMap.keySet().size()]));
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
}
for(String key: contributionMap.keySet()) {
csvFilePrinter.print((contributionMap.get(key)));
}
csvFilePrinter.println();
}
fileWriter.flush();
fileWriter.close();
if(csvFilePrinter != null) {
csvFilePrinter.close();
}
return ok(tempFile);
} catch (Exception e) {
Logger.error("Error generating csv file");
e.printStackTrace();
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution stats: " + e.getMessage())));
}
}
//if mail will be send we package the files into a zip and send the download link by mail
} else {
Logger.info("Packing files to send by email");
String finalFormat = format;
String finalExtendedTextFormat = extendedTextFormat;
F.Promise.promise(() -> {
try {
List<File> aRet = new ArrayList<>();
if (finalFormat.toUpperCase().equals("JSON")) {
aRet.add(getExportFileJson(contributions, true, finalFormat));
} else if (collectionFileFormat != null &&
(collectionFileFormat.toUpperCase().equals("JSON"))) {
aRet.add(getExportFileJson(contributions, true, collectionFileFormat));
} else if (collectionFileFormat != null &&
(collectionFileFormat.toUpperCase().equals("CSV"))) {
for(Contribution contribution : contributions) {
aRet.add(getExportFile(contribution, includeExtendedText, finalExtendedTextFormat, collectionFileFormat));
}
} else {
aRet.add(getExportFileJson(contributions, true, "JSON"));
for(Contribution contribution : contributions) {
aRet.add(getExportFile(contribution, includeExtendedText, finalExtendedTextFormat, "CSV"));
}
}
for (Contribution contribution : contributions) {
aRet.add(getExportFile(contribution, includeExtendedText, finalExtendedTextFormat, finalFormat));
if (includeExtendedText.toUpperCase().equals("TRUE")) {
File file = getPadFile(contribution, finalExtendedTextFormat, finalFormat, user);
if (file != null) {
aRet.add(file);
}
}
}
Logger.info("EXPORT: Preparing ZIP file for exported contributions...");
String fileName = "contribution" + new Date().getTime() + ".zip";
String appBasePath = Play.application().path().getAbsolutePath();
String path = Play.application().configuration().getString("application.contributionFilesPath") + fileName;
if (!Play.application().configuration().getBoolean("application.contributionFilesPathIsAbsolute")) {
path = appBasePath + path;
}
File zip = new File(path);
Logger.info("EXPORT: Packing export in "+path + "files " + aRet);
Packager.packZip(zip, aRet);
String url = Play.application().configuration().getString("application.contributionFiles") + fileName;
Logger.info("EXPORT: Preparing email to send "+url);
MyUsernamePasswordAuthProvider provider = MyUsernamePasswordAuthProvider.getProvider();
provider.sendZipContributionFile(url, user.getEmail());
} catch (DocumentException e) {
Logger.info(e.getMessage());
Logger.debug(e.getStackTrace().toString());
}
return Optional.ofNullable(null);
});
}
}
return ok("The file will be sent to your email when it is ready");
}
/**
* GET /api/space/:sid/contribution/:cid
*
* @param sid
* @param cid
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, produces = "application/json",
value = "Get contribution by id in a specific Resource Space",
notes = "Every entity in AppCivist has a Resource Space to associate itself to other entities")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No resource space found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@SubjectPresent
public static Result findResourceSpaceContributionById(
@ApiParam(name = "sid", value = "Resource Space ID") Long sid,
@ApiParam(name = "cid", value = "Contribution ID") Long cid,
@ApiParam(name = "format", value = "Export format", allowableValues = "JSON,CSV,TXT,PDF,RTF,DOC")
String format,
@ApiParam(name = "includeExtendedText", value = "Include or not extended text") String includeExtendedText,
@ApiParam(name = "extendedTextFormat", value = "Include or not extended text", allowableValues =
"JSON,CSV,TXT,PDF,RTF,DOC") String extendedTextFormat,
@ApiParam(name = "flat", value = "Flat version of the campaign") String flat) {
Logger.debug("Finding Contribution "+cid+" in Resource Space "+sid);
ResourceSpace rs = ResourceSpace.findByContribution(sid, cid);
format = format.toUpperCase();
if (rs == null) {
return notFound(Json
.toJson(new TransferResponseStatus("No contribution found with id " + cid + "in space " + sid)));
}
Contribution contribution = Contribution.read(cid);
if(flat.equals("true")) {
try {
DateFormat bdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Map<String, Object> aRet = new HashMap<>();
aRet.put("title", contribution.getTitle());
aRet.put("text", contribution.getText());
aRet.put("creation", bdFormat.format(contribution.getCreation()));
if (contribution.getLastUpdate() != null) {
aRet.put("lastUpdate", bdFormat.format(contribution.getLastUpdate()));
}
return ok(Json.toJson(aRet));
} catch (Exception e) {
e.printStackTrace();
return ok();
}
}
contribution.setCustomFieldValues(CustomFieldValue.findAllByTargetUUID(contribution.getUuidAsString()));
List<Contribution> contributions = new ArrayList<>();
contributions.add(contribution);
Boolean sendMail = false;
if (!(format.equals("JSON") || format.equals("CSV")) || includeExtendedText.toUpperCase().equals("TRUE")) {
sendMail = true;
Logger.debug("Contribution export will be produced in format "+format+" and sent by email");
}
if (!sendMail) {
Logger.debug("Contribution in "+format+" will be sent to client");
if(format.equals("JSON")) {
return ok(Json.toJson(contribution));
}
if(format.equals("CSV")) {
response().setContentType("application/csv");
response().setHeader("Content-disposition", "attachment; filename=proposal.csv");
Logger.debug("Contribution in CSV being produced based on JSON");
try {
Logger.info("Preparing CSV file");
File tempFile = File.createTempFile("contributions.csv", ".tmp");
CSVPrinter csvFilePrinter;
FileWriter fileWriter = new FileWriter(tempFile);
Logger.info("Creating csv row for contribution " + contribution.getContributionId());
LinkedHashMap<String, String> contributionMap = getContributionMapToExport(contribution);
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(contributionMap.keySet().toArray(new String[contributionMap.keySet().size()]));
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
for(String key: contributionMap.keySet()) {
csvFilePrinter.print((contributionMap.get(key)));
}
csvFilePrinter.println();
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
return ok(tempFile);
} catch (Exception e) {
e.printStackTrace();
return internalServerError(Json.toJson(
new TransferResponseStatus("There was an internal error: " + e.getMessage())));
}
}
} else {
Logger.debug("Contribution in "+format+" will be produced in promise to sent by email (includeExtendedText = "+includeExtendedText);
String finalFormat = format;
F.Promise.promise(() -> {
List<File> aRet = new ArrayList<>();
switch (finalFormat.toUpperCase()) {
case "JSON":
aRet.add(getExportFileJson(contributions, false, finalFormat));
break;
default:
try {
aRet.add(getExportFile(contribution, includeExtendedText, extendedTextFormat, finalFormat));
break;
} catch (DocumentException e) {
Logger.info("DocumentException when exporting file");
e.printStackTrace();
return internalServerError(Json.toJson(
new TransferResponseStatus("There was an internal error: " + e.getMessage())));
}
}
try {
User user = User.findByAuthUserIdentity(PlayAuthenticate.getUser(session()));
Logger.info("EXPORT: Preparing ZIP file for export");
if (includeExtendedText.toUpperCase().equals("TRUE")) {
Logger.info("TRying to include extended text file");
File file = getPadFile(contribution, extendedTextFormat, finalFormat, user);
if (file != null) {
aRet.add(file);
Logger.info("Extended text included");
}
}
String fileName = "contribution" + new Date().getTime() + ".zip";
String appBasePath = Play.application().path().getAbsolutePath();
String path = Play.application().configuration().getString("application.contributionFilesPath") + fileName;
if (!Play.application().configuration().getBoolean("application.contributionFilesPathIsAbsolute")) {
path = appBasePath + path;
}
File zip = new File(path);
Logger.info("EXPORT: Packing exported contribution in zip File: "+path);
Packager.packZip(zip, aRet);
String url = Play.application().configuration().getString("application.contributionFiles") + fileName;
MyUsernamePasswordAuthProvider provider = MyUsernamePasswordAuthProvider.getProvider();
provider.sendZipContributionFile(url, user.getEmail());
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
Logger.info("Error in export Promise: "+e.getMessage());
}
return Optional.ofNullable(null);
});
}
return ok("The file will be sent to your email when it is ready");
}
/**
* GET /api/space/:sid/contribution
*
* @param sid
* @param type
* @return
*/
@ApiOperation(httpMethod = "GET", response = Contribution.class, responseContainer = "List", produces = "application/json",
value = "Get contributions in a specific Resource Space",
notes = "Every entity in AppCivist has a Resource Space to associate itself to other entities")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contributions found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@SubjectPresent
public static Result findResourceSpacePinnedContributions(
@ApiParam(name = "sid", value = "Resource Space ID") Long sid,
@ApiParam(name = "type", value = "Type of contributions", allowableValues = "forum_post, comment, idea, question, issue, proposal, note", defaultValue = "") String type) {
ContributionTypes mappedType = null;
if (type != null)
ContributionTypes.valueOf(type.toUpperCase());
List<Contribution> contributions = ContributionsDelegate.findPinnedContributionsInSpace(sid, mappedType);
if (contributions == null) {
contributions = new ArrayList<Contribution>();
}
return contributions != null ? ok(Json.toJson(contributions))
: notFound(Json.toJson(new TransferResponseStatus(
"No pinned contributions for {resource space}: " + sid + ", type=" + type)));
}
/**
* GET /api/assembly/:aid/campaign/:cid/contribution/:coid/stats
*
* @param aid
* @param cid
* @param coid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionStatistics.class, produces = "application/json",
value = "Get contributions statistics")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution stats found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result readContributionStats(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid) {
try {
ContributionStatistics stats = new ContributionStatistics(coid);
return ok(Json.toJson(stats));
} catch (Exception e) {
e.printStackTrace();
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution stats: " + e.getMessage())));
}
}
/**
* GET /api/assembly/:aid/campaign/:cid/group/:gid/contribution/:coid/stats
*
* @param aid
* @param cid
* @param gid
* @param coid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionStatistics.class, produces = "application/json",
value = "Get workgroup contributions statistics")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution stats found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result readWGContributionStats(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "gud", value = "Group ID") Long gid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid) {
try {
ContributionStatistics stats = new ContributionStatistics(gid, coid);
return ok(Json.toJson(stats));
} catch (Exception e) {
e.printStackTrace();
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading workgroup contribution stats: " + e.getMessage())));
}
}
/**
* GET /api/assembly/:aid/campaign/:cid/contribution/:coid/feedback
*
* @param aid
* @param cid
* @param coid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionFeedback.class, responseContainer = "List", produces = "application/json",
value = "Get contributions feedbacks")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution feedbacks found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
// @Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result readContributionFeedbacks(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid) {
try {
String type = ContributionFeedbackTypes.TECHNICAL_ASSESSMENT.name();
List<ContributionFeedback> feedbacks = ContributionFeedback.getPublicFeedbacksByContributionType(coid, type);
User user;
NonMemberAuthor nma;
for (ContributionFeedback contributionFeedback: feedbacks) {
Map<String, Object> info = new HashMap<>();
Long userId = contributionFeedback.getUserId();
if (userId!=null) {
user = User.findByUserId(contributionFeedback.getUserId());
info.put("id", user.getUserId());
info.put("name", user.getName());
if (user.getProfilePic()!=null)
info.put("profilePic", user.getProfilePic().getUrlAsString());
contributionFeedback.setUserId(null);
} else {
nma = contributionFeedback.getNonMemberAuthor();
if (nma==null) {
info.put("id", -1);
info.put("name", "");
} else {
info.put("id", nma.getId());
info.put("name", nma.getName());
contributionFeedback.setNonMemberAuthor(null);
}
}
contributionFeedback.setUser(info);
}
if (feedbacks==null || feedbacks.size() == 0) {
Logger.debug("There are no feedbacks for contribution " + coid + " in assembly " + aid + " and campaign " + cid);
feedbacks = new ArrayList<>();
}
return ok(Json.toJson(feedbacks));
} catch (Exception e) {
Logger.error("Error retrieving feedbacks", e);
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution feedbacks: " + e.getMessage())));
}
}
/**
* GET /api/assembly/:aid/campaign/:cid/contribution/:coid/feedback/:fid
*
* @param aid
* @param cid
* @param coid
* @param fid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionFeedback.class, produces = "application/json",
value = "Get individual ContributionFeedback")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution feedback found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfAssembly", meta = SecurityModelConstants.ASSEMBLY_RESOURCE_PATH)
public static Result readContributionFeedback(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "cid", value = "Campaign ID") Long cid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid,
@ApiParam(name = "fid", value = "Feedback ID") Long fid) {
try {
ContributionFeedback feedback = ContributionFeedback.read(fid);
if (feedback==null) {
Logger.debug("There are no feedbacks for contribution " + coid + " in assembly " + aid + " and campaign " + cid);
feedback = new ContributionFeedback();
}
return ok(Json.toJson(feedback));
} catch (Exception e) {
Logger.error("Error retrieving feedbacks", e);
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution feedbacks: " + e.getMessage())));
}
}
/**
* GET /api/assembly/:aid/group/:gid/contribution/:coid/feedback?type=x
*
* @param aid
* @param gid
* @param coid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionFeedback.class, responseContainer = "List", produces = "application/json",
value = "Get Contribution Feedbacks")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution feedbacks found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
@Dynamic(value = "MemberOfGroup", meta = SecurityModelConstants.GROUP_RESOURCE_PATH)
public static Result readContributionFeedbackPrivate(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "gid", value = "Group ID") Long gid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid,
@ApiParam(name = "type", value = "Type") String type) {
try {
List<ContributionFeedback> feedbacks = ContributionFeedback.getPrivateFeedbacksByContributionTypeAndWGroup(coid, gid, type);
if (feedbacks==null || feedbacks.size() == 0) {
Logger.debug("There are no feedbacks for contribution " + coid + " in assembly " + aid + " and group " + gid);
feedbacks = new ArrayList<>();
}
return ok(Json.toJson(feedbacks));
} catch (Exception e) {
Logger.error("Error retrieving feedbacks", e);
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution feedbacks: " + e.getMessage())));
}
}
/**
* GET /api/assembly/:aid/contribution/:coid/feedback?type=x
*
* @param aid
* @param coid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionFeedback.class, responseContainer = "List", produces = "application/json",
value = "Get Contribution Feedbacks")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution feedbacks found", response = TransferResponseStatus.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "SESSION_KEY", value = "User's session authentication key", dataType = "String", paramType = "header")})
//@Dynamic(value = "CoordinatorOfAssembly", meta = SecurityModelConstants.AUTHOR_OF_CONTRIBUTION_FEEDBACK)
@Restrict({@Group(GlobalData.USER_ROLE)})
public static Result readContributionFeedbackNoGroupId(
@ApiParam(name = "aid", value = "Assembly ID") Long aid,
@ApiParam(name = "coid", value = "Contribution ID") Long coid,
@ApiParam(name = "type", value = "Type") String type) {
try {
// 1. obtaining the user of the requestor
User author = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session()));
List<ContributionFeedback> feedbacks = new ArrayList<>();
feedbacks = ContributionFeedback.getPrivateFeedbacksByContributionType(coid, author.getUserId(), type);
if (feedbacks==null || feedbacks.size() == 0) {
Logger.debug("There are no feedbacks for contribution " + coid + " in assembly " + aid);
feedbacks = new ArrayList<>();
}
return ok(Json.toJson(feedbacks));
} catch (Exception e) {
Logger.error("Error retrieving feedbacks", e);
return internalServerError(Json
.toJson(new TransferResponseStatus(
ResponseStatus.SERVERERROR,
"Error reading contribution feedbacks: " + e.getMessage())));
}
}
/**
* GET /api/contribution/:couuid/feedback?type=x
*
* @param couuid
* @return
*/
@ApiOperation(httpMethod = "GET", response = ContributionFeedback.class, responseContainer = "List", produces = "application/json",
value = "Get Contribution Feedbacks")
@ApiResponses(value = {@ApiResponse(code = 404, message = "No contribution feedbacks found", response = TransferResponseStatus.class)})
public static Result readContributionFeedbackPublic(
@ApiParam(name = "couuid", value = "Contribution UUID") String couuid,
@ApiParam(name = "type", value = "Type") String type) {
try {
Contribution co = Contribution.readByUUID(UUID.fromString(couuid));
type = ContributionFeedbackTypes.TECHNICAL_ASSESSMENT.name();
List<ContributionFeedback> feedbacks = ContributionFeedback.getPublicFeedbacksByContributionType(co.getContributionId(), type);
for (ContributionFeedback contributionFeedback: feedbacks) {
Map<String, Object> info = new HashMap<>();
if(contributionFeedback.getUserId() != null) {