jira-plugin-intellij /src/test/resources/examples/RenameUserDoNotUse.groovy

Language Groovy Lines 546
MD5 Hash d17f41629b040075e6979a8639019bdc
Repository https://bitbucket.org/sorin/jira-plugin-intellij View Raw File View Project SPDX
  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
package examples

import com.atlassian.core.ofbiz.association.AssociationManager
import com.atlassian.core.ofbiz.util.CoreTransactionUtil
import com.atlassian.event.api.EventPublisher
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.ManagerFactory
import com.atlassian.jira.bc.filter.SearchRequestService
import com.atlassian.jira.bc.portal.PortalPageService
import com.atlassian.jira.event.ClearCacheEvent
import com.atlassian.jira.favourites.FavouritesManager
import com.atlassian.jira.imports.project.parser.UserAssociationParser
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.cache.CacheManager
import com.atlassian.jira.issue.index.IssueIndexManager
import com.atlassian.jira.issue.search.CachingSearchRequestStore
import com.atlassian.jira.issue.search.SearchRequestManager
import com.atlassian.jira.issue.search.SearchRequestStore
import com.atlassian.jira.issue.security.IssueSecuritySchemeManagerImpl
import com.atlassian.jira.notification.DefaultNotificationSchemeManager
import com.atlassian.jira.notification.type.SingleUser
import com.atlassian.jira.permission.DefaultPermissionSchemeManager
import com.atlassian.jira.portal.CachingPortalPageStore
import com.atlassian.jira.portal.PortalPageManager
import com.atlassian.jira.security.roles.CachingProjectRoleAndActorStore
import com.atlassian.jira.security.roles.actor.UserRoleActorFactory
import com.atlassian.jira.sharing.ShareManager
import com.atlassian.jira.util.ImportUtils
import com.opensymphony.user.UserManager
import org.apache.log4j.Category
import org.ofbiz.core.entity.*
import com.opensymphony.user.EntityNotFoundException
import com.atlassian.jira.util.collect.EnclosedIterable
import com.atlassian.jira.issue.search.SearchRequest
import com.atlassian.jira.util.Consumer
import com.atlassian.query.clause.ClauseVisitor
import com.atlassian.query.clause.AndClause
import com.atlassian.query.clause.NotClause
import com.atlassian.query.clause.OrClause
import com.atlassian.query.clause.TerminalClause
import com.atlassian.query.clause.Clause
import com.atlassian.jira.jql.builder.JqlQueryBuilder
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.query.operand.Operand
import com.atlassian.query.operand.OperandVisitor
import com.atlassian.query.operand.EmptyOperand
import com.atlassian.query.operand.FunctionOperand
import com.atlassian.query.operand.MultiValueOperand
import com.atlassian.query.operand.SingleValueOperand
import com.atlassian.query.clause.TerminalClauseImpl
import com.atlassian.query.Query
import com.atlassian.query.QueryImpl
import com.atlassian.jira.bc.JiraServiceContextImpl

Category log = Category.getInstance("com.onresolve.jira.groovy.Scratch")

ComponentManager componentManager = ComponentManager.getInstance()
UserManager userManager = UserManager.getInstance()
FavouritesManager favouritesManager = ComponentManager.getComponentInstanceOfType(FavouritesManager.class) as FavouritesManager
SearchRequestStore searchRequestStore = ComponentManager.getComponentInstanceOfType(SearchRequestStore.class) as SearchRequestStore
CachingSearchRequestStore cachingSearchRequestStore = ComponentManager.getComponentInstanceOfType(CachingSearchRequestStore.class) as CachingSearchRequestStore
CachingPortalPageStore cachingPortalPageStore = ComponentManager.getComponentInstanceOfType(CachingPortalPageStore.class) as CachingPortalPageStore
ShareManager shareManager = ComponentManager.getComponentInstanceOfType(ShareManager.class) as ShareManager
SearchRequestManager searchRequestManager = componentManager.getSearchRequestManager()
SearchRequestService searchRequestService = componentManager.getSearchRequestService()
IssueManager issueManager = componentManager.getIssueManager()
AssociationManager associationManager = ComponentManager.getComponentInstanceOfType(AssociationManager.class) as AssociationManager
CachingProjectRoleAndActorStore cachingProjectRoleAndActorStore = ComponentManager.getComponentInstanceOfType(CachingProjectRoleAndActorStore.class) as CachingProjectRoleAndActorStore
DefaultNotificationSchemeManager notificationSchemeManager = ComponentManager.getComponentInstanceOfType(DefaultNotificationSchemeManager.class) as DefaultNotificationSchemeManager
DefaultPermissionSchemeManager defaultPermissionSchemeManager = ComponentManager.getComponentInstanceOfType(DefaultPermissionSchemeManager.class) as DefaultPermissionSchemeManager
IssueSecuritySchemeManagerImpl securitySchemeManager = ComponentManager.getComponentInstanceOfType(IssueSecuritySchemeManagerImpl.class) as IssueSecuritySchemeManagerImpl

Set<Long> reindexIssueIds = new HashSet()

String sourceUser = 'rchapma4'
String targetUser = 'rchapma5'

DelegatorInterface gd = (DelegatorInterface) componentManager.getComponentInstanceOfType(DelegatorInterface.class)
IssueIndexManager indexManager = ComponentManager.getInstance().getIndexManager()

private def reindexIssue(IssueManager issueManager, Long issueId, Category log, IssueIndexManager indexManager) {
    GenericValue issue = issueManager.getIssue(issueId)
    boolean wasIndexing = ImportUtils.isIndexIssues();
    ImportUtils.setIndexIssues(true);
    ManagerFactory.getCacheManager().flush(CacheManager.ISSUE_CACHE, issue)
    log.debug("Reindex issue ${issue.key}")
    indexManager.reIndex(issue);
    ImportUtils.setIndexIssues(wasIndexing)
}

boolean preview = false
List msgs = []
String msg
boolean began = false

private def getLog() {
    return log
}

EnclosedIterable<SearchRequest> srs = searchRequestManager.getAll()
srs.foreach(new Consumer<SearchRequest>() {
    void consume(SearchRequest sr) {

        if (sr.name != "ReporterIsRenamedUser") {
            return
        }
        log.debug("visiting")
        Query query = sr.getQuery()
        log.debug query

        Clause whereClause = query.getWhereClause()
        Clause newWhereClause = whereClause.accept(new ClauseVisitor() {

            Object visit(AndClause andClause) {
                println("visit")
                getLog().debug("AndClause")
                andClause
            }

            Object visit(NotClause notClause) {
                getLog().debug("NotClause")
                notClause
            }

            Object visit(OrClause orClause) {
                getLog().debug("OrClause")
                orClause
            }

            Object visit(TerminalClause clause) {
                // println("visit TerminalClause")
                getLog().debug "clause.getName(): " + clause.getName()

                if (["reporter", "assignee"].contains (clause.getName())) {
                    Operand operand = clause.getOperand()
                    println operand.getDisplayString()
                    Operand newOp = operand.accept(new OperandVisitor() {
                        Object visit(EmptyOperand empty) {
                            empty
                        }

                        Object visit(FunctionOperand function) {
                            function
                        }

                        Object visit(MultiValueOperand multiValue) {
                            getLog().debug "multiValue: $multiValue"
                            multiValue
                        }

                        Object visit(SingleValueOperand singleValueOperand) {
                            getLog().debug "singleValueOperand: $singleValueOperand"
                            getLog().debug singleValueOperand.getStringValue()
                            getLog().debug "Update admin to anuser"
                            new SingleValueOperand("anuser")
                        }

                    }) as Operand
                    getLog().debug "newOp: $newOp"
                    TerminalClauseImpl newTermClause = new TerminalClauseImpl(clause.name, clause.getOperator(), newOp)
                    getLog().debug("newTermClause: " + newTermClause)
                    return newTermClause

                }

                println clause.getOperator().getDisplayString()
                clause
            }

        }) as Clause
        log.debug "total where clause: " + newWhereClause

        query.whereClause

        if (query.whereClause.toString() != newWhereClause.toString()) {
            // this is stupid but setting a queryString seems to blow away the whereClause, so we do this twice
            log.debug("Update sr name: " + sr.name)

/*
            Query newQuery = new QueryImpl(newWhereClause)
            newQuery = new QueryImpl(newWhereClause, query.orderByClause, newQuery.queryString)
            log.debug("newQuery: $newQuery")
            sr.setQuery(newQuery)
            JiraServiceContextImpl ctx = new JiraServiceContextImpl(userManager.getUser(sr.ownerUserName))
            searchRequestService.validateFilterForUpdate(ctx, sr)
            log.debug("errors: " + ctx.getErrorCollection())
            searchRequestService.updateFilter(ctx, sr)
            log.debug("errors: " + ctx.getErrorCollection())
*/
        }
        else {
            log.debug("No need to update name: " + sr.name)
        }
    }
})

return

if (! preview) {
    log.debug("Begin transaction")
    began = CoreTransactionUtil.begin();
}

try {

    try {
        userManager.getUser("def")
        sourceUser = "def"
        targetUser = "abc"
    }
    catch (EntityNotFoundException e) {
        try {
            log.debug "no user def"
            userManager.getUser("abc")
            sourceUser = "abc"
            targetUser = "def"
        }
        catch (EntityNotFoundException ef) {
            log.error("No abc or def")
            return
        }
    }

    msg = "Beginning rename of $sourceUser to $targetUser"
    log.warn(msg)
    msgs << msg

    //User user = UserUtils.createUser("abc", "x", "abc@blah.com", "Mr ABC", ["jira-users"])
    //return

    // Rename the user record itself
    List gvs = gd.findByAnd("OSUser", [name: sourceUser])
    assert gvs.size() == 1
    if (! preview) {
        GenericValue usergv = gvs.first() as GenericValue
        usergv.set("name", targetUser)
        usergv.store()
    }

    // group memberships
    gvs = gd.findByAnd("OSMembership", [userName: sourceUser])
    msg = "Update ${gvs.size()} OSMembership records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("userName", targetUser)
            gv.store()
        }
    }

    // SearchRequest ownership
    gvs = gd.findByOr("SearchRequest", [user: sourceUser, author: sourceUser])
    msg = "Update ${gvs.size()} SearchRequest records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            if (gv.get("user")) {
                gv.set("user", targetUser)
            }
            if (gv.get("author")) {
                gv.set("author", targetUser)
            }
            cachingSearchRequestStore.removeFromCache(gv.getLong("id"))
            gv.store()
        }
    }

    ["PortalPage", "ColumnLayout", "UserHistoryItem", "FilterSubscription", "FavouriteAssociations"].each {String entityName ->
        gvs = gd.findByAnd(entityName, [username: sourceUser])
        msg = "Update ${gvs.size()} $entityName records"
        log.debug(msg)
        msgs << msg
        if (!preview) {
            gvs.each {GenericValue gv ->
                gv.set("username", targetUser)
                gv.store()
            }
        }
    }
    // note: for versions prior to 4.1 the favouritesStoreCache needs to be flushed

    // Core issue fields
    gvs = gd.findByOr("Issue", [reporter: sourceUser, assignee: sourceUser])
    msg = "Update ${gvs.size()} Issue records"
    log.debug(msg)
    msgs << msg
    gvs.each {GenericValue gv ->
        if (!preview) {
            if (gv.get("reporter") == sourceUser) {
                gv.set("reporter", targetUser)
            }
            if (gv.get("assignee") == sourceUser) {
                gv.set("assignee", targetUser)
            }
            gv.store()
        }
        reindexIssueIds.add(gv.getLong("id"))
    }

    // issue transition history
    gvs = gd.findByOr("Action", [author: sourceUser, updateauthor: sourceUser])
    msg = "Update ${gvs.size()} Action records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            if (gv.get("author") == sourceUser) {
                gv.set("author", targetUser)
            }
            if (gv.get("updateauthor") == sourceUser) {
                gv.set("updateauthor", targetUser)
            }
            gv.store()
        }
    }

    // change groups
    gvs = gd.findByAnd("ChangeGroup", [author: sourceUser])
    msg = "Update ${gvs.size()} ChangeGroup records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("author", targetUser)
            gv.store()
        }
    }

    // Change items
    EntityConditionList conditionList = new EntityConditionList(
        [new EntityConditionList(
            [
                new EntityExpr("oldvalue", EntityOperator.EQUALS, sourceUser),
                new EntityExpr("newvalue", EntityOperator.EQUALS, sourceUser),
            ], EntityOperator.OR),
            new EntityConditionList([new EntityExpr("field", EntityOperator.IN, ["reporter", "assignee"])], EntityOperator.AND)
        ], EntityOperator.AND
    )
    gvs = gd.findByCondition("ChangeItem", conditionList, ["id", "field", "oldvalue", "newvalue"], Collections.<String> emptyList())
    msg = "Update ${gvs.size()} ChangeItem records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            if (gv.get("oldvalue") == sourceUser) {
                gv.set("oldvalue", targetUser)
            }
            if (gv.get("newvalue") == sourceUser) {
                gv.set("newvalue", targetUser)
            }
            gv.store()
        }
    }

    // Watchers and voters
    List userAssocCList = [
            new EntityExpr("sourceName", EntityOperator.EQUALS, sourceUser),
            new EntityExpr("associationType", EntityOperator.IN,
                [UserAssociationParser.ASSOCIATION_TYPE_WATCH_ISSUE, UserAssociationParser.ASSOCIATION_TYPE_VOTE_ISSUE]),
        ]
    gvs = gd.findByAnd("UserAssociation", userAssocCList)
    msg = "Update ${gvs.size()} UserAssociation records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gd.removeValue(gv)

            gv.set("sourceName", targetUser)
            gd.create(gv)
            // gv.store() doesn't work because we're changing the primary key
        }
    }

    // roles
    gvs = gd.findByAnd("ProjectRoleActor", [roletype: UserRoleActorFactory.TYPE, roletypeparameter: sourceUser])
    msg = "Update ${gvs.size()} ProjectRoleActor records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("roletypeparameter", targetUser)
            gv.store()
        }
        cachingProjectRoleAndActorStore.clearCaches()
    }

    // SharePermissions not required as cannot share with a user

    // worklogs
    gvs = gd.findByOr("Worklog", [author: sourceUser, updateauthor: sourceUser])
    msg = "Update ${gvs.size()} Worklog records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            if (gv.get("author") == sourceUser) {
                gv.set("author", targetUser)
            }
            if (gv.get("updateauthor") == sourceUser) {
                gv.set("updateauthor", targetUser)
            }
            gv.store()
        }
    }

    // project and comp leads
    gvs = gd.findByAnd("Project", [lead: sourceUser])
    msg = "Update ${gvs.size()} Project records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("lead", targetUser)
            gv.store()
        }
    }
    gvs = gd.findByAnd("Component", [lead: sourceUser])
    msg = "Update ${gvs.size()} Component records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("lead", targetUser)
            gv.store()
        }
    }

    // notification schemes
    gvs = gd.findByAnd("Notification", [type: SingleUser.DESC, parameter: sourceUser])
    msg = "Update ${gvs.size()} Notification records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("parameter", targetUser)
            gv.store()
        }
        notificationSchemeManager.flushProjectSchemes()
    }

    // permission schemes
    gvs = gd.findByAnd("SchemePermissions", [type: "user", parameter: sourceUser])
    msg = "Update ${gvs.size()} SchemePermissions records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("parameter", targetUser)
            gv.store()
        }
        defaultPermissionSchemeManager.flushProjectSchemes()
        defaultPermissionSchemeManager.flushSchemeEntities()
    }

    // issue security schemes
    gvs = gd.findByAnd("SchemeIssueSecurities", [type: "user", parameter: sourceUser])
    msg = "Update ${gvs.size()} SchemeIssueSecurities records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("parameter", targetUser)
            gv.store()
        }
        securitySchemeManager.flushProjectSchemes()
    }

    // user and multi-user custom fields
    gvs = gd.findByCondition("CustomField",
        new EntityExpr("customfieldtypekey", EntityOperator.IN,
            [
                "com.atlassian.jira.plugin.system.customfieldtypes:userpicker",
                "com.atlassian.jira.plugin.system.customfieldtypes:multiuserpicker"
            ])
        ,
        ["id"], Collections.<String> emptyList())
    Long cfValueKount = 0
    gvs.each {GenericValue gv ->
        gv.getRelatedByAnd("ChildCustomFieldValue", [stringvalue: sourceUser]).each {GenericValue cfGv ->
            cfValueKount++
            if (!preview) {
                cfGv.set("stringvalue", targetUser)
                cfGv.store()
            }
            reindexIssueIds.add(cfGv.getLong("issue"))
        }
    }
    msg = "Update ${gvs.size()} CustomFieldValue records" // not strictly true
    log.debug(msg)
    msgs << msg

    // possibly todo: update search parameters that refer to user custom fields
    // make sure they're not logged on?

    // todo: OS_CURRENTSTEP owner, caller, OS_HISTORYSTEP, jiraworkflows

    // fileattachments
    gvs = gd.findByAnd("FileAttachment", [author: sourceUser])
    msg = "Update ${gvs.size()} FileAttachment records"
    log.debug(msg)
    msgs << msg
    if (!preview) {
        gvs.each {GenericValue gv ->
            gv.set("author", targetUser)
            gv.store()
        }
    }

    // -------------------------------------- Finalise --------------------------------------
    if (! preview) {
        log.debug("Commit transaction")
        CoreTransactionUtil.commit(began);

        // Only for 4.1 and above - clearing the other caches are not necessary above but kept there if
        // I decide to backport this
        log.debug("Publish clear cache event")
        ComponentManager.getComponentInstanceOfType(EventPublisher.class).publish(ClearCacheEvent.INSTANCE);

        // reindex issues
        reindexIssueIds.each {Long issueId ->
            reindexIssue(issueManager, issueId, log, indexManager);
        }

        UserManager.getInstance().flushCaches()
        user = userManager.getUser(targetUser)
        user.getAccessProvider().flushCaches()
        user.getProfileProvider().flushCaches()
    }

    msg = "Reindex ${reindexIssueIds.size()} issues"
    log.debug(msg)
    msgs << msg
}
catch (Exception e) {
    log.error("Problem renaming user, rolling back")
    CoreTransactionUtil.rollback(began)
}
finally {
    // not sure if we need anything here
}

msgs.join("\n")
Back to Top