-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathIssueManager.java
More file actions
1664 lines (1431 loc) · 66.5 KB
/
IssueManager.java
File metadata and controls
1664 lines (1431 loc) · 66.5 KB
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
/*
* Copyright (c) 2005-2018 Fred Hutchinson Cancer Research Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.issue.model;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.labkey.api.attachments.AttachmentParent;
import org.labkey.api.attachments.AttachmentService;
import org.labkey.api.cache.BlockingCache;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerFilter;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.CoreSchema;
import org.labkey.api.data.DatabaseCache;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.DbScope;
import org.labkey.api.data.Entity;
import org.labkey.api.data.ObjectFactory;
import org.labkey.api.data.PropertyManager;
import org.labkey.api.data.PropertyManager.WritablePropertyMap;
import org.labkey.api.data.Results;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.Sort;
import org.labkey.api.data.SqlExecutor;
import org.labkey.api.data.SqlSelector;
import org.labkey.api.data.Table;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.issues.Issue;
import org.labkey.api.issues.IssuesListDefProvider;
import org.labkey.api.issues.IssuesListDefService;
import org.labkey.api.issues.IssuesSchema;
import org.labkey.api.issues.RestrictedIssueProvider;
import org.labkey.api.module.Module;
import org.labkey.api.module.ModuleLoader;
import org.labkey.api.query.BatchValidationException;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.QueryUpdateService;
import org.labkey.api.query.UserSchema;
import org.labkey.api.query.ValidationError;
import org.labkey.api.search.SearchService;
import org.labkey.api.search.SearchService.IndexTask;
import org.labkey.api.security.Group;
import org.labkey.api.security.LimitedUser;
import org.labkey.api.security.MemberType;
import org.labkey.api.security.SecurityManager;
import org.labkey.api.security.User;
import org.labkey.api.security.UserManager;
import org.labkey.api.security.ValidEmail;
import org.labkey.api.security.permissions.AdminPermission;
import org.labkey.api.security.permissions.ReadPermission;
import org.labkey.api.security.permissions.UpdatePermission;
import org.labkey.api.security.roles.ReaderRole;
import org.labkey.api.util.ContainerUtil;
import org.labkey.api.util.FileStream;
import org.labkey.api.util.GUID;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.JunitUtil;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.Path;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.TestContext;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.AjaxCompletion;
import org.labkey.api.view.HttpView;
import org.labkey.api.view.JspView;
import org.labkey.api.view.UnauthorizedException;
import org.labkey.api.view.ViewContext;
import org.labkey.api.view.ViewServlet;
import org.labkey.api.webdav.AbstractDocumentResource;
import org.labkey.api.webdav.WebdavResource;
import org.labkey.issue.IssuesController;
import org.labkey.issue.IssuesModule;
import org.labkey.issue.query.IssueDefDomainKind;
import org.labkey.issue.query.IssuesListDefTable;
import org.labkey.issue.query.IssuesQuerySchema;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static org.labkey.api.search.SearchService.PROPERTY.categories;
import static org.labkey.api.security.UserManager.USER_DISPLAY_NAME_COMPARATOR;
public class IssueManager
{
private static final Logger _log = LogManager.getLogger(IssueManager.class);
public static final SearchService.SearchCategory searchCategory = new SearchService.SearchCategory("issue", "Issues");
// UNDONE: Keywords, Summary, etc.
private static final IssuesSchema _issuesSchema = IssuesSchema.getInstance();
public static final int NOTIFY_ASSIGNEDTO_OPEN = 1; // if a bug is assigned to me
public static final int NOTIFY_ASSIGNEDTO_UPDATE = 2; // if a bug assigned to me is modified
public static final int NOTIFY_CREATED_UPDATE = 4; // if a bug I created is modified
public static final int NOTIFY_SUBSCRIBE = 16; // send email on all changes
public static final int NOTIFY_SELF_SPAM = 8; // spam me when I enter/edit a bug
public static final int DEFAULT_EMAIL_PREFS = NOTIFY_ASSIGNEDTO_OPEN | NOTIFY_ASSIGNEDTO_UPDATE | NOTIFY_CREATED_UPDATE;
private static final String CAT_ISSUE_DEF_PROPERTIES = "IssueDefProperties-";
private static final String PROP_ENTRY_TYPE_NAME_SINGULAR = "issueEntryTypeNameSingular";
private static final String PROP_ENTRY_TYPE_NAME_PLURAL = "issueEntryTypeNamePlural";
private static final String PROP_ASSIGNED_TO_GROUP = "issueAssignedToGroup";
private static final String PROP_DEFAULT_ASSIGNED_TO_USER = "issueDefaultAssignedToUser";
private static final String PROP_DEFAULT_RELATED_FOLDER = "issueDefaultsRelatedFolder";
private static final String CAT_COMMENT_SORT = "issueCommentSort";
public static final String DEFAULT_REQUIRED_FIELDS = "title;assignedto";
private IssueManager()
{
}
private static IssueObject _getRawIssue(@Nullable Container c, int issueId)
{
SimpleFilter filter = null;
if (null != c)
filter = new SimpleFilter(FieldKey.fromParts("Container"), c);
IssueObject issue = new TableSelector(_issuesSchema.getTableInfoIssues(), filter, null).getObject(issueId, IssueObject.class);
if (issue == null)
return null;
List<IssueObject.CommentObject> comments = new TableSelector(_issuesSchema.getTableInfoComments(),
new SimpleFilter(FieldKey.fromParts("issueId"), issue.getIssueId()),
new Sort("CommentId")).getArrayList(IssueObject.CommentObject.class);
issue.setComments(comments);
Collection<Integer> dups = new TableSelector(_issuesSchema.getTableInfoIssues().getColumn("IssueId"),
new SimpleFilter(FieldKey.fromParts("Duplicate"), issueId),
new Sort("IssueId")).getCollection(Integer.class);
issue.setDuplicates(dups);
Collection<Integer> rels = new TableSelector(_issuesSchema.getTableInfoRelatedIssues().getColumn("RelatedIssueId"),
new SimpleFilter(FieldKey.fromParts("IssueId"), issueId),
new Sort("IssueId")).getCollection(Integer.class);
issue.setRelatedIssues(rels);
// the related string is only used when rendering the update form
issue.setRelated(StringUtils.join(rels, ", "));
return issue;
}
@Nullable
public static IssueObject getIssue(@Nullable Container c, User user, int issueId)
{
return getIssue(c, user, issueId, true);
}
@Nullable
public static IssueObject getIssue(
@Nullable Container c,
User user,
int issueId,
boolean throwOnRestrictedFailure // controls whether we throw on a RestrictedIssueProvider failure
// or just return null
)
{
IssueObject issue = _getIssue(c, user, issueId);
// check permissions for a restricted issue list
RestrictedIssueProvider provider = IssuesListDefService.get().getRestrictedIssueProvider();
if (issue != null && provider != null)
{
List<Issue> relatedIssues = new ArrayList<>();
List<ValidationError> errors = new ArrayList<>();
// need to check all related issues
for (Integer relatedIssue : issue.getRelatedIssues())
{
IssueObject related = _getIssue(c, user, relatedIssue);
if (related != null)
relatedIssues.add(related);
}
if (!provider.hasPermission(user, issue, relatedIssues, errors))
{
if (throwOnRestrictedFailure)
{
StringBuilder msg = new StringBuilder(errors.isEmpty() ? "Access denied" : "");
for (ValidationError ve : errors)
{
msg.append(ve.getMessage()).append("\n");
}
throw new UnauthorizedException(msg.toString());
}
else
return null;
}
}
return issue;
}
@Nullable
private static IssueObject _getIssue(@Nullable Container c, User user, int issueId)
{
IssueObject issue = _getRawIssue(c, issueId);
if (issue != null && issue.getIssueDefId() != null)
{
// container may initially be null if we don't care about a specific folder, but we need the
// correct domain for the provisioned table properties associated with the issue
if (c == null)
c = ContainerManager.getForId(issue.getContainerId());
IssueListDef issueListDef = getIssueListDef(issue.getContainerFromId(), issue.getIssueDefId());
UserSchema userSchema = QueryService.get().getUserSchema(user, c, IssuesQuerySchema.SCHEMA_NAME);
TableInfo table = userSchema.getTable(issueListDef.getName());
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("IssueId"), issueId);
if (table != null)
{
var select = QueryService.get().getSelectBuilder(table).filter(filter);
try (Results rs = select.select(Map.of(), false))
{
Map<String, Object> rowMap = new CaseInsensitiveHashMap<>();
if (rs.next())
{
for (String colName : table.getColumnNameSet())
{
Object value = rs.getObject(FieldKey.fromParts(colName));
if (value != null)
rowMap.put(colName, value);
}
}
issue.setProperties(rowMap);
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
else
return null;
}
return issue;
}
/**
* Returns a linked list of all comments for the argument Issue together with comments
* of all related issues sorted by creation date.
*
* @param issue an issue to retrieve comments from
* @return the sorted linked list of all related comments
*/
public static List<IssueObject.CommentObject> getCommentsForRelatedIssues(IssueObject issue, User user)
{
// Get related issues for optional display
Set<Integer> relatedIssues = issue.getRelatedIssues();
List<IssueObject.CommentObject> commentLinkedList = new LinkedList<>();
// Add related issue comments
for (Integer relatedIssueInt : relatedIssues)
{
// only add related issues that the user has permission to see
IssueObject relatedIssue = IssueManager.getIssue(null, user, relatedIssueInt, false);
if (relatedIssue != null)
{
boolean hasReadPermission = ContainerManager.getForId(relatedIssue.getContainerId()).hasPermission(user, ReadPermission.class);
if (hasReadPermission)
commentLinkedList.addAll(relatedIssue.getCommentObjects());
}
}
// Add all current issue comments
commentLinkedList.addAll(issue.getCommentObjects());
Comparator<IssueObject.CommentObject> comparator = Comparator.comparing(Entity::getCreated);
// Respect the configuration's sorting order - issue 23524
Container issueContainer = issue.lookupContainer();
IssueListDef issueListDef = IssueManager.getIssueListDef(issue);
if (Sort.SortDirection.DESC == getCommentSortDirection(issueContainer, issueListDef.getName()))
{
comparator = comparator.reversed();
}
commentLinkedList.sort(comparator);
return commentLinkedList;
}
/**
* Determine if the parameter issue has related issues. Returns true if the issue has related
* issues and false otherwise.
*
* @param issue The issue to query
* @return boolean return value
*/
public static boolean hasRelatedIssues(IssueObject issue, User user)
{
for (Integer relatedIssueInt : issue.getRelatedIssues())
{
IssueObject relatedIssue = IssueManager.getIssue(null, user, relatedIssueInt, false);
if (relatedIssue != null && !relatedIssue.getCommentObjects().isEmpty())
{
boolean hasReadPermission = ContainerManager.getForId(relatedIssue.getContainerId()).hasPermission(user, ReadPermission.class);
if (hasReadPermission)
return true;
}
}
return false;
}
public static void saveIssue(User user, Container container, IssueObject issue)
{
if (issue.getAssignedTo() == null)
issue.setAssignedTo(0);
IssueListDef issueDef = getIssueListDef(issue);
if (issueDef != null)
{
try (DbScope.Transaction transaction = IssuesSchema.getInstance().getSchema().getScope().ensureTransaction())
{
// if this is an existing issue, we want the container the issue is associated with, otherwise use the
// passed in container
Container c = ContainerManager.getForId(issue.getContainerId());
if (c != null)
container = c;
UserSchema userSchema = QueryService.get().getUserSchema(user, container, IssuesQuerySchema.SCHEMA_NAME);
TableInfo table = userSchema.getTable(issueDef.getName());
QueryUpdateService qus = table.getUpdateService();
Map<String, Object> row = new CaseInsensitiveHashMap<>();
ObjectFactory factory = ObjectFactory.Registry.getFactory(IssueObject.class);
String related = issue.getRelated();
issue.setRelated(null);
factory.toMap(issue, row);
row.putAll(issue.getProperties());
row.remove("Related");
BatchValidationException batchErrors = new BatchValidationException();
List<Map<String, Object>> results;
if (issue.issueId == 0)
{
issue.beforeInsert(user, container.getId());
results = qus.insertRows(user, container, Collections.singletonList(row), batchErrors, null, null);
if (!batchErrors.hasErrors())
{
assert results.size() == 1;
issue.setIssueId((int) results.get(0).get("IssueId"));
issue.setIssueDefId((Integer) results.get(0).get("issueDefId"));
}
else
throw batchErrors;
}
else
{
issue.beforeUpdate(user);
qus.updateRows(user, container, Collections.singletonList(row), Collections.singletonList(row), batchErrors, null, null);
if (batchErrors.hasErrors())
throw batchErrors;
}
issue.setRelated(related);
saveComments(user, issue);
saveRelatedIssues(user, issue);
indexIssue(container, user, null, issue);
transaction.commit();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
protected static void saveComments(User user, IssueObject issue)
{
Collection<IssueObject.CommentObject> comments = issue._added;
if (null == comments)
return;
for (IssueObject.CommentObject comment : comments)
{
// NOTE: form has already validated comment text, but let's be extra paranoid.
if (!ViewServlet.validChars(comment.getHtmlComment().toString()))
throw new ConversionException("comment has invalid characters");
Map<String, Object> m = new HashMap<>();
m.put("issueId", issue.getIssueId());
m.put("comment", comment.getHtmlComment().toString());
m.put("entityId", comment.getEntityId());
Table.insert(user, _issuesSchema.getTableInfoComments(), m);
}
issue._added = null;
}
protected static void saveRelatedIssues(User user, IssueObject issue)
{
Collection<Integer> rels = issue.getRelatedIssues();
int issueId = issue.getIssueId();
Table.delete(_issuesSchema.getTableInfoRelatedIssues(), new SimpleFilter(FieldKey.fromParts("IssueId"), issueId));
for (Integer rel : rels)
{
Map<String, Object> m = new HashMap<>();
m.put("issueId", issueId);
m.put("relatedIssueId", rel);
Table.insert(user, _issuesSchema.getTableInfoRelatedIssues(), m);
}
}
public static Collection<Map<String, Object>> getSummary(Container c, User user, @Nullable IssueListDef issueListDef)
{
if (issueListDef != null)
{
TableInfo tableInfo = issueListDef.createTable(user);
Collection<Object> params = new ArrayList<>();
SQLFragment sql = new SQLFragment("SELECT DisplayName, SUM(CASE WHEN Status='open' THEN 1 ELSE 0 END) AS " +
_issuesSchema.getSqlDialect().makeLegalIdentifier("Open") + ", SUM(CASE WHEN Status='resolved' THEN 1 ELSE 0 END) AS " +
_issuesSchema.getSqlDialect().makeLegalIdentifier("Resolved") + "\n" +
"FROM " + tableInfo + " LEFT OUTER JOIN " + CoreSchema.getInstance().getTableInfoUsers() +
" ON AssignedTo = UserId\n" +
"WHERE Status in ('open', 'resolved') AND Container = ? ");
params.add(c);
sql.append("GROUP BY DisplayName");
sql.addAll(params);
return new SqlSelector(_issuesSchema.getSchema(), sql).getMapCollection();
}
else
return Collections.emptyList();
}
public static @NotNull Collection<User> getAssignedToList(Container c, @Nullable String issueDefName, @Nullable IssueObject issue)
{
Collection<User> initialAssignedTo = getInitialAssignedToList(c, issueDefName);
// If this is an existing issue, add the user who opened the issue, unless they are a guest, inactive, already in the list, or don't have permissions.
if (issue != null && 0 != issue.getIssueId())
{
User createdByUser = UserManager.getUser(issue.getCreatedBy());
if (createdByUser != null && !createdByUser.isGuest() && !initialAssignedTo.contains(createdByUser) && canAssignTo(c, createdByUser))
{
Set<User> modifiedAssignedTo = new TreeSet<>(USER_DISPLAY_NAME_COMPARATOR);
modifiedAssignedTo.addAll(initialAssignedTo);
modifiedAssignedTo.add(createdByUser);
return Collections.unmodifiableSet(modifiedAssignedTo);
}
}
return initialAssignedTo;
}
private static final BlockingCache<String, Set<User>> ASSIGNED_TO_CACHE = DatabaseCache.get(IssuesSchema.getInstance().getSchema().getScope(), 1000, "Issues assigned-to lists", (key, argument) ->
{
assert argument != null;
Pair<Container, String> pair = (Pair<Container, String>)argument;
Container c = pair.getKey();
String issueDefName = pair.getValue();
Group group = getAssignedToGroup(c, issueDefName);
if (null != group)
return createAssignedToList(c, SecurityManager.getAllGroupMembers(group, MemberType.ACTIVE_USERS, true));
else
return createAssignedToList(c, SecurityManager.getProjectUsers(c.getProject()));
});
// Returns the assigned to list that is used for every new issue in this container. We can cache it and share it
// across requests. The collection is unmodifiable.
private static @NotNull Collection<User> getInitialAssignedToList(final Container c, @Nullable String issueDefName)
{
issueDefName = issueDefName != null ? issueDefName : IssueListDef.DEFAULT_ISSUE_LIST_NAME;
String cacheKey = getCacheKey(c, issueDefName);
return ASSIGNED_TO_CACHE.get(cacheKey, Pair.of(c, issueDefName));
}
public static String getCacheKey(@Nullable Container c, String issueDefName)
{
String key = "AssignedTo-" + issueDefName;
return null != c ? key + c.getId() : key;
}
private static Set<User> createAssignedToList(Container c, Collection<User> candidates)
{
Set<User> assignedTo = new TreeSet<>(USER_DISPLAY_NAME_COMPARATOR);
for (User candidate : candidates)
if (canAssignTo(c, candidate))
assignedTo.add(candidate);
// Cache an unmodifiable version
return Collections.unmodifiableSet(assignedTo);
}
private static boolean canAssignTo(Container c, @NotNull User user)
{
return user.isActive() && c.hasPermission(user, UpdatePermission.class);
}
static @Nullable Integer validateAssignedTo(Container c, Integer candidate)
{
if (null != candidate)
{
User user = UserManager.getUser(candidate);
if (null != user && canAssignTo(c, user))
return candidate;
}
return null;
}
public static int getUserEmailPreferences(Container c, Integer userId)
{
if (userId != null)
{
Integer[] emailPreference;
//if the user is inactive, don't send email
User user = UserManager.getUser(userId);
if (null != user && !user.isActive())
return 0;
emailPreference = new SqlSelector(
_issuesSchema.getSchema(),
"SELECT EmailOption FROM " + _issuesSchema.getTableInfoEmailPrefs() + " WHERE Container=? AND UserId=?",
c, userId).getArray(Integer.class);
if (emailPreference.length == 0)
{
if (userId == UserManager.getGuestUser().getUserId())
{
return 0;
}
return DEFAULT_EMAIL_PREFS;
}
return emailPreference[0];
}
else
return 0;
}
public static class EntryTypeNames
{
public String singularName = IssueDefDomainKind.DEFAULT_ENTRY_TYPE_SINGULAR;
public String pluralName = IssueDefDomainKind.DEFAULT_ENTRY_TYPE_PLURAL;
public String getIndefiniteSingularArticle()
{
if (singularName.isEmpty())
return "";
char first = Character.toLowerCase(singularName.charAt(0));
if (first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u')
return "an";
else
return "a";
}
}
@NotNull
public static EntryTypeNames getEntryTypeNames(Container container, String issueDefName)
{
Map<String, String> props = PropertyManager.getProperties(container, getPropMapName(issueDefName));
EntryTypeNames ret = new EntryTypeNames();
if (props.containsKey(PROP_ENTRY_TYPE_NAME_SINGULAR))
ret.singularName = props.get(PROP_ENTRY_TYPE_NAME_SINGULAR);
if (props.containsKey(PROP_ENTRY_TYPE_NAME_PLURAL))
ret.pluralName = props.get(PROP_ENTRY_TYPE_NAME_PLURAL);
return ret;
}
private static String getPropMapName(String issueDefName)
{
if (issueDefName == null)
throw new IllegalArgumentException("Issue def name must be specified");
return CAT_ISSUE_DEF_PROPERTIES + issueDefName;
}
private static void deleteProperties(Container container, String issueDefName)
{
WritablePropertyMap properties = PropertyManager.getWritableProperties(container, getPropMapName(issueDefName), false);
if (properties != null)
{
properties.delete();
}
// if there is a restricted issue list, give it a chance to clean up saved settings
RestrictedIssueProvider provider = IssuesListDefService.get().getRestrictedIssueProvider();
if (provider != null)
{
provider.deleteProperties(container, issueDefName);
}
}
public static void saveEntryTypeNames(Container container, String issueDefName, EntryTypeNames names)
{
saveEntryTypeNames(container, issueDefName, names.singularName, names.pluralName);
}
public static void saveEntryTypeNames(Container container, String issueDefName, String singularName, String pluralName)
{
WritablePropertyMap props = PropertyManager.getWritableProperties(container, getPropMapName(issueDefName), true);
props.put(PROP_ENTRY_TYPE_NAME_SINGULAR, singularName);
props.put(PROP_ENTRY_TYPE_NAME_PLURAL, pluralName);
props.save();
}
private static String getPropertyValue(Container c, String issueDefName, String key)
{
return PropertyManager.getProperties(c, getPropMapName(issueDefName)).get(key);
}
private static void setPropertyValue(Container c, String issueDefName, String key, String value)
{
WritablePropertyMap props = PropertyManager.getWritableProperties(c, getPropMapName(issueDefName), true);
props.put(key, value);
props.save();
}
public static @Nullable Group getAssignedToGroup(Container c, String issueDefName)
{
String groupId = getPropertyValue(c, issueDefName, PROP_ASSIGNED_TO_GROUP);
if (null == groupId)
return null;
return SecurityManager.getGroup(Integer.valueOf(groupId));
}
public static void saveAssignedToGroup(Container c, String issueDefName, @Nullable Group group)
{
setPropertyValue(c, issueDefName, PROP_ASSIGNED_TO_GROUP, null != group ? String.valueOf(group.getUserId()) : "0");
uncache(); // uncache the assigned to list
}
public static @Nullable User getDefaultAssignedToUser(Container c, String issueDefName)
{
String userId = getPropertyValue(c, issueDefName, PROP_DEFAULT_ASSIGNED_TO_USER);
if (null == userId)
return null;
User user = UserManager.getUser(Integer.parseInt(userId));
if (user == null)
return null;
if (!canAssignTo(c, user))
return null;
return user;
}
public static void saveDefaultAssignedToUser(Container c, String issueDefName, @Nullable User user)
{
setPropertyValue(c, issueDefName, PROP_DEFAULT_ASSIGNED_TO_USER, null != user ? String.valueOf(user.getUserId()) : null);
}
public static String getDefaultRelatedFolder(Container c, String issueDefName)
{
return getPropertyValue(c, issueDefName, PROP_DEFAULT_RELATED_FOLDER);
}
public static void setPropDefaultRelatedFolder(Container c, String issueDefName, String relatedFolder)
{
setPropertyValue(c, issueDefName, PROP_DEFAULT_RELATED_FOLDER, relatedFolder);
}
public static Collection<Container> getMoveDestinationContainers(Container c, User user, String issueDefName)
{
List<Container> containers = new ArrayList<>();
if (issueDefName != null)
{
IssueListDef issueListDef = IssueManager.getIssueListDef(c, issueDefName);
if (issueListDef != null)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("name"), issueDefName);
SimpleFilter.FilterClause filterClause = IssueListDef.createFilterClause(issueListDef, user);
if (filterClause != null)
filter.addClause(filterClause);
else
filter.addCondition(FieldKey.fromParts("container"), c);
for (IssueListDef def : new TableSelector(IssuesSchema.getInstance().getTableInfoIssueListDef(), filter, null).getArrayList(IssueListDef.class))
{
// exclude current container
if (!def.getContainerId().equals(c.getId()))
containers.add(ContainerManager.getForId(def.getContainerId()));
}
}
}
return containers;
}
public static void moveIssues(User user, List<Integer> issueIds, Container dest) throws IOException
{
DbSchema schema = IssuesSchema.getInstance().getSchema();
try (DbScope.Transaction transaction = schema.getScope().ensureTransaction())
{
List<AttachmentParent> attachmentParents = new ArrayList<>();
Integer issueDefId = null;
Container issueDefContainer = null;
List<String> entityIds = new ArrayList<>();
for (int issueId : issueIds)
{
IssueObject issue = IssueManager.getIssue(null, user, issueId);
if (issue != null)
{
if (issue.getIssueDefId() != null && issueDefId == null)
{
issueDefId = issue.getIssueDefId();
issueDefContainer = issue.getContainerFromId();
}
entityIds.add(issue.getEntityId());
issue.getCommentObjects().forEach(comment -> attachmentParents.add(new CommentAttachmentParent(comment)));
}
}
if (issueDefId != null)
{
// these should all be within the same domain so we don't care which issuedef we get, they
// should all be the same provisioned table
IssueListDef issueDef = getIssueListDef(issueDefContainer, issueDefId);
if (issueDef != null)
{
// get the destination issue definition
IssueListDef destIssueDef = getIssueListDef(dest, issueDef.getName());
if (destIssueDef != null)
{
SQLFragment update = new SQLFragment("UPDATE issues.issues SET Container = ?, IssueDefId = ? ", dest, destIssueDef.getRowId());
update.append("WHERE issueId ");
schema.getSqlDialect().appendInClauseSql(update, issueIds);
new SqlExecutor(schema).execute(update);
// change the container for the provisioned table provided all issues are moving within
// the same domain
TableInfo table = issueDef.createTable(user);
SQLFragment sql = new SQLFragment("UPDATE ").append(table, "").
append("SET container = ? WHERE entityId ");
sql.add(dest);
schema.getSqlDialect().appendInClauseSql(sql, entityIds);
new SqlExecutor(schema).execute(sql);
AttachmentService.get().moveAttachments(dest, attachmentParents, user);
transaction.commit();
}
else
_log.warn("Unable to locate the destination issue list definition");
}
else
_log.warn("Attempting to move an issue not associated with a domain");
}
else
{
_log.warn("Attempting to move an issue not all within the same domain");
}
}
}
public static Sort.SortDirection getCommentSortDirection(Container c, String issueDefName)
{
String direction = getPropertyValue(c, issueDefName, CAT_COMMENT_SORT);
if (direction != null)
{
try
{
return Sort.SortDirection.valueOf(direction);
}
catch (IllegalArgumentException e) {}
}
return Sort.SortDirection.ASC;
}
public static void saveCommentSortDirection(Container c, String issueDefName, @NotNull Sort.SortDirection direction)
{
setPropertyValue(c, issueDefName, CAT_COMMENT_SORT, direction.toString());
uncache(); // uncache the assigned to list
}
public static void setUserEmailPreferences(Container c, int userId, int emailPrefs, int currentUser)
{
int ret = new SqlExecutor(_issuesSchema.getSchema()).execute(
"UPDATE " + _issuesSchema.getTableInfoEmailPrefs() + " SET EmailOption=? WHERE Container=? AND UserId=?",
emailPrefs, c, userId);
if (ret == 0)
{
// record doesn't exist yet...
new SqlExecutor(_issuesSchema.getSchema()).execute(
"INSERT INTO " + _issuesSchema.getTableInfoEmailPrefs() + " (Container, UserId, EmailOption ) VALUES (?, ?, ?)",
c, userId, emailPrefs);
}
}
public static List<ValidEmail> getSubscribedUserEmails(Container c)
{
List<ValidEmail> emails = new ArrayList<>();
SqlSelector ss = new SqlSelector(_issuesSchema.getSchema().getScope(), new SQLFragment("SELECT UserId FROM " + _issuesSchema.getTableInfoEmailPrefs() + " WHERE Container = ? and (EmailOption & ?) = ?", c.getId(), NOTIFY_SUBSCRIBE, NOTIFY_SUBSCRIBE));
Integer[] userIds = ss.getArray(Integer.class);
for (Integer userId : userIds)
{
String email = UserManager.getEmailForId(userId);
if (email != null)
{
try
{
ValidEmail ve = new ValidEmail(email);
emails.add(ve);
}
catch (ValidEmail.InvalidEmailException e)
{
//ignore
}
}
}
return emails;
}
public static void deleteUserEmailPreferences(User user)
{
Table.delete(_issuesSchema.getTableInfoEmailPrefs(), new SimpleFilter(FieldKey.fromParts("UserId"), user.getUserId()));
}
public static long getIssueCount(Container c)
{
return new TableSelector(_issuesSchema.getTableInfoIssues(), SimpleFilter.createContainerFilter(c), null).getRowCount();
}
public static void uncache()
{
ASSIGNED_TO_CACHE.clear(); //Lazy uncache: uncache ALL the containers for updated values in case any folder is inheriting its Admin settings.
}
public static void purgeContainer(Container c, User user)
{
try (DbScope.Transaction transaction = _issuesSchema.getSchema().getScope().ensureTransaction())
{
for (IssueListDef issueListDef : getIssueListDefs(c))
{
deleteIssueListDef(issueListDef.getRowId(), c, user);
}
ContainerUtil.purgeTable(_issuesSchema.getTableInfoEmailPrefs(), c, null);
transaction.commit();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
*
* @return combined Required fields of "current" and "inherited from" container if admin settings are inherited
*/
public static String getRequiredIssueFields(Container container)
{
return DEFAULT_REQUIRED_FIELDS;
}
public static void setLastIndexed(String containerId, int issueId, long ms)
{
new SqlExecutor(_issuesSchema.getSchema()).execute(
"UPDATE issues.issues SET lastIndexed=? WHERE container=? AND issueId=?",
new Timestamp(ms), containerId, issueId);
}
public static void indexIssues(IndexTask task, @NotNull Container c, Date modifiedSince)
{
SearchService ss = SearchService.get();
if (null == ss)
return;
SimpleFilter f = SimpleFilter.createContainerFilter(c);
SearchService.LastIndexedClause incremental = new SearchService.LastIndexedClause(_issuesSchema.getTableInfoIssues(), modifiedSince, null);
if (!incremental.isEmpty())
f.addClause(incremental);
if (f.getClauses().isEmpty())
f = null;
// Index issues in batches of 100
new TableSelector(_issuesSchema.getTableInfoIssues(), PageFlowUtil.set("issueid"), f, null)
.forEachBatch(Integer.class, 100, batch -> task.addRunnable(new IndexGroup(task, batch), SearchService.PRIORITY.group));
}
private static class IndexGroup implements Runnable
{
private final List<Integer> _ids;
private final IndexTask _task;
IndexGroup(IndexTask task, List<Integer> ids)
{
_ids = ids;
_task = task;
}
@Override
public void run()
{
User user = new LimitedUser(UserManager.getGuestUser(), ReaderRole.class);
indexIssues(null, user, _task, _ids);
}
}
/* CONSIDER: some sort of generator interface instead */
public static void indexIssues(@Nullable Container container, User user, IndexTask task, Collection<Integer> ids)
{
if (ids.isEmpty())
return;
SQLFragment f = new SQLFragment();
f.append("SELECT I.issueId, I.container, I.entityid, I.duplicate, ")
.append("C.comment\n");
f.append("FROM issues.issues I \n")
.append("LEFT OUTER JOIN issues.comments C ON I.issueid = C.issueid\n");
for (Integer id : ids)
{
try
{
IssueObject issue = IssueManager.getIssue(container, user, id);
if (issue != null)
queueIssue(task, id, issue.getProperties(), issue.getCommentObjects());
}
catch (UnauthorizedException e)
{
// Issue 51607 ignore restricted issue failures
}
}
}
static void indexIssue(Container container, User user, @Nullable IndexTask task, IssueObject issue)
{
if (task == null)
{
SearchService ss = SearchService.get();
if (null == ss)
return;
task = ss.defaultTask();
}
// UNDONE: broken ??
// task.addResource(new IssueResource(issue), SearchService.PRIORITY.item);