private LuceneSearchProvider getSearchProvider() {
   return new LuceneSearchProvider(
       ComponentAccessor.getIssueFactory(),
       new SearchProviderFactoryImpl(),
       ComponentManager.getComponentInstanceOfType(PermissionsFilterGeneratorImpl.class),
       ComponentManager.getComponentInstanceOfType(SearchHandlerManager.class),
       ComponentManager.getComponentInstanceOfType(SearchSortUtil.class),
       ComponentManager.getComponentInstanceOfType(LuceneQueryBuilder.class));
 }
 public DeleteUser(
     CrowdService crowdService,
     CrowdDirectoryService crowdDirectoryService,
     final UserPropertyManager userPropertyManager,
     final UserManager userManager) {
   super(crowdService, crowdDirectoryService, userPropertyManager, userManager);
   this.searchRequestService =
       ComponentManager.getComponentInstanceOfType(SearchRequestService.class);
   this.portalPageService = ComponentManager.getInstance().getPortalPageService();
   this.userService = ComponentManager.getComponentInstanceOfType(UserService.class);
   this.userUtil = ComponentAccessor.getUserUtil();
 }
 public EditDefaultDashboard(
     final PortalPageService portalPageService,
     final DashboardPermissionService permissionService,
     final ApplicationProperties applicationProperties) {
   this.applicationProperties = applicationProperties;
   this.dashboardTabViewFactory =
       ComponentManager.getOSGiComponentInstanceOfType(DashboardTabViewFactory.class);
   this.dashboardService = ComponentManager.getOSGiComponentInstanceOfType(DashboardService.class);
   this.gadgetRequestContextFactory =
       ComponentManager.getOSGiComponentInstanceOfType(GadgetRequestContextFactory.class);
   this.portalPageService = portalPageService;
   this.permissionService = permissionService;
 }
  @Override
  public void validateFromParams(
      CustomFieldParams cfParams, ErrorCollection errorCollection, FieldConfig fieldConfig) {
    @SuppressWarnings("unchecked")
    final Collection<String> params = cfParams.getAllValues();
    CustomField cf = fieldConfig.getCustomField();
    JiraAuthenticationContext authCtx =
        ComponentManager.getInstance().getJiraAuthenticationContext();
    I18nHelper i18n = authCtx.getI18nHelper();
    UserProjectHistoryManager userProjectHistoryManager =
        ComponentManager.getComponentInstanceOfType(UserProjectHistoryManager.class);
    Project currentProject =
        userProjectHistoryManager.getCurrentProject(Permissions.BROWSE, authCtx.getLoggedInUser());

    boolean isAutocompleteView;
    if (cf.isAllProjects()) {
      isAutocompleteView =
          qfMgr.isAutocompleteView(cf.getIdAsLong(), Consts.PROJECT_ID_FOR_GLOBAL_CF);
    } else {
      isAutocompleteView = qfMgr.isAutocompleteView(cf.getIdAsLong(), currentProject.getId());
    }

    if (isAutocompleteView) {
      if ((params == null) || params.isEmpty()) {
        boolean addNull;
        if (cf.isAllProjects()) {
          addNull = qfMgr.getAddNull(cf.getIdAsLong(), Consts.PROJECT_ID_FOR_GLOBAL_CF);
        } else {
          addNull = qfMgr.getAddNull(cf.getIdAsLong(), currentProject.getId());
        }

        if (!addNull) {
          errorCollection.addError(
              fieldConfig.getFieldId(), i18n.getText("queryfields.error.isnotnull"));
        }
      } else {
        if (params.size() > 1) {
          errorCollection.addError(
              fieldConfig.getFieldId(), i18n.getText("queryfields.error.invalid.params"));
        } else {
          for (String param : params) {
            Issue issue = issueMgr.getIssueObject(param);
            if (issue == null) {
              errorCollection.addError(
                  fieldConfig.getFieldId(), i18n.getText("queryfields.error.notissue", param));
            }
          }
        }
      }
    }
  }
  public void doMock() {
    // Ensure that the multitenantfactory is not null
    MultiTenantContext.setFactory(
        new MockMultiTenantComponentFactory(new MockTenantReference(new MockTenant("tenant"))));
    // Initialise the ComponentAccessor
    ComponentAccessor.initialiseWorker(new ComponentAccessorWorker());

    // Set up Mocks
    PowerMock.mockStaticPartial(ComponentManager.class, "getInstance");
    expect(ComponentManager.getInstance()).andReturn(new MockComponentManager()).anyTimes();
    PowerMock.replay(ComponentManager.class);
  }
  public static List<Issue> executeJQLQuery(String jqlQuery) {
    List<Issue> result = null;

    User user = ComponentManager.getInstance().getJiraAuthenticationContext().getLoggedInUser();
    SearchService.ParseResult parseResult = searchService.parseQuery(user, jqlQuery);

    if (parseResult.isValid()) {
      Query query = parseResult.getQuery();
      try {
        SearchResults results = searchService.search(user, query, PagerFilter.getUnlimitedFilter());
        result = results.getIssues();
      } catch (SearchException e) {
        log.error("Utils::search exception during executing JQL", e);
      }
    }

    return result;
  }
  public void testStandardHitCollectorSearch() throws SearchException {
    final LuceneSearchProvider luceneSearchProvider = getSearchProvider();

    // Create a search request
    final QueryImpl query =
        new QueryImpl(
            new TerminalClauseImpl(
                "resolution", Operator.EQUALS, new SingleValueOperand(resolutionId)));

    final Set<String> results = new LinkedHashSet<String>();
    // create a PrefixFieldableHitCollector that searches for summaries starting with "Summ"
    luceneSearchProvider.search(
        query,
        bob,
        new PrefixFieldableHitCollector(
            ComponentManager.getComponentInstanceOfType(IssueIndexManager.class).getIssueSearcher(),
            "summary",
            "Summ",
            results));
    assertEquals(1, results.size());
    assertEquals(SUMMARY_BODY, results.iterator().next());
  }
  public static Document getDocument(final Issue issueObject) {
    final FieldIndexerManager fieldIndexerManager =
        ComponentManager.getComponentInstanceOfType(FieldIndexerManager.class);

    if (log.isDebugEnabled()) {
      log.debug("Indexing issue: " + issueObject.getKey());
    }

    final List<String> visibleDocumentFieldIds = new ArrayList<String>();
    final Document doc = new Document();
    final Collection<FieldIndexer> allIssueIndexers = fieldIndexerManager.getAllIssueIndexers();
    for (final FieldIndexer indexer : allIssueIndexers) {
      indexer.addIndex(doc, issueObject);
      // We need to build up the list of visible Document field ids
      if (indexer.isFieldVisibleAndInScope(issueObject)) {
        visibleDocumentFieldIds.add(indexer.getDocumentFieldId());
      }
    }

    // Get all the fields in the document and add a new fields who's value is the name of all the
    // included fields
    for (final Fieldable val : getNonEmptyFields(doc)) {
      doc.add(val);
    }

    // Use all the visible field ids and add a new field who's value is name of all the visible
    // field ids
    for (final String visibleDocumentFieldId : visibleDocumentFieldIds) {
      doc.add(
          new Field(
              DocumentConstants.ISSUE_VISIBLE_FIELD_IDS,
              visibleDocumentFieldId,
              Field.Store.NO,
              Field.Index.NOT_ANALYZED_NO_NORMS));
    }

    return doc;
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    final FieldVisibilityManager visibilityBean = EasyMock.createMock(FieldVisibilityManager.class);
    EasyMock.expect(
            visibilityBean.isFieldHidden(
                (String) EasyMock.anyObject(), (Issue) EasyMock.anyObject()))
        .andReturn(false)
        .anyTimes();
    EasyMock.replay(visibilityBean);
    ManagerFactory.addService(FieldVisibilityManager.class, visibilityBean);

    originalFactory =
        ComponentManager.getComponentInstanceOfType(FieldClausePermissionChecker.Factory.class);
    ManagerFactory.addService(
        FieldClausePermissionChecker.Factory.class, new MockFieldClausePermissionFactory());
    bob = createMockUser("bob");

    final Group group = addUserToNewGroup(bob, "group");
    carl = createMockUser("carl");

    final GenericValue project =
        UtilsForTests.getTestEntity("Project", EasyMap.build("key", "TST"));

    final PermissionSchemeManager permissionSchemeManager =
        ManagerFactory.getPermissionSchemeManager();
    final GenericValue defaultScheme = permissionSchemeManager.createDefaultScheme();
    final SchemeEntity schemeEntity =
        new SchemeEntity(GroupDropdown.DESC, null, Permissions.BROWSE);
    permissionSchemeManager.createSchemeEntity(defaultScheme, schemeEntity);

    permissionSchemeManager.addSchemeToProject(project, defaultScheme);

    UtilsForTests.getTestEntity("Resolution", EasyMap.build("id", resolutionId));
    // Create two Issues with same comment but different level
    final GenericValue issue1 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-1",
                "resolution",
                resolutionId,
                "summary",
                SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue1.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            COMMENT_BODY));

    final GenericValue issue2 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-2",
                "resolution",
                resolutionId,
                "summary",
                SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue2.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            COMMENT_BODY,
            "level",
            group.getName()));

    final GenericValue issue3 =
        UtilsForTests.getTestEntity(
            "Issue",
            EasyMap.build(
                "project",
                project.getLong("id"),
                "key",
                "TST-3",
                "resolution",
                resolutionId,
                "summary",
                ANOTHER_SUMMARY_BODY));
    UtilsForTests.getTestEntity(
        "Action",
        EasyMap.build(
            "issue",
            issue3.getLong("id"),
            "type",
            ActionConstants.TYPE_COMMENT,
            "body",
            ANOTHER_COMMENT_BODY,
            "level",
            group.getName()));

    ManagerFactory.getIndexManager().reIndexAll();
  }
  @EventListener
  public void onIssueEvent(IssueEvent issueEvent) {
    if (!issueEvent.getEventTypeId().equals(EventType.ISSUE_CREATED_ID)) {
      return;
    }

    Issue issue = issueEvent.getIssue();
    Collection<ProjectComponent> comps = issue.getComponentObjects();
    if (comps == null || comps.size() < 2) {
      return;
    }

    Project project = issue.getProjectObject();
    if (project == null || !isApplyPlugin(project.getId())) {
      return;
    }

    List<Issue> newIssues = new ArrayList<Issue>();
    ProjectComponent gv = null;
    Iterator<ProjectComponent> iter = comps.iterator();
    while (iter.hasNext()) {
      gv = iter.next();

      MutableIssue nissue = ComponentManager.getInstance().getIssueFactory().getIssue();
      // --> summary
      nissue.setSummary(String.format("[%s] %s", gv.getName(), issue.getSummary()));
      // --> project
      if (issue.getProjectObject() != null) {
        nissue.setProjectId(issue.getProjectObject().getId());
      }
      // --> issue type
      if (issue.getIssueTypeObject() != null) {
        nissue.setIssueTypeId(issue.getIssueTypeObject().getId());
      }
      // --> components
      Collection<ProjectComponent> nComps = new LinkedList<ProjectComponent>();
      nComps.add(gv);
      nissue.setComponentObjects(nComps);
      // --> assignee
      String compLead = gv.getLead();
      nissue.setAssigneeId(compLead);
      // --> reporter
      nissue.setReporter(issueEvent.getUser());
      // --> priority
      nissue.setPriorityObject(issue.getPriorityObject());
      // --> description
      nissue.setDescription(issue.getDescription());
      // --> env
      nissue.setEnvironment(issue.getEnvironment());
      // --> due date
      nissue.setDueDate(issue.getDueDate());
      // --> estimate
      nissue.setEstimate(issue.getEstimate());
      // --> labels
      nissue.setLabels(issue.getLabels());
      nissue.setAffectedVersions(issue.getAffectedVersions());
      nissue.setWorkflowId(issue.getWorkflowId());
      nissue.setParentId(issue.getParentId());

      // --> status
      if (issue.getStatusObject() != null) {
        nissue.setStatusId(issue.getStatusObject().getId());
      }

      // --> resolution
      if (issue.getResolutionObject() != null) {
        nissue.setResolutionId(issue.getResolutionObject().getId());
      }

      nissue.setFixVersions(issue.getFixVersions());
      nissue.setResolutionDate(issue.getResolutionDate());
      nissue.setTimeSpent(issue.getTimeSpent());
      nissue.setVotes(issue.getVotes());
      nissue.setCreated(issue.getCreated());
      nissue.setSecurityLevelId(issue.getSecurityLevelId());
      nissue.setOriginalEstimate(issue.getOriginalEstimate());

      List<CustomField> cfs =
          ComponentManager.getInstance().getCustomFieldManager().getCustomFieldObjects(issue);
      if (cfs != null) {
        for (CustomField cf : cfs) {
          Object cfVal = issue.getCustomFieldValue(cf);
          if (cfVal != null) {
            nissue.setCustomFieldValue(cf, cfVal);
          }
        }
      }

      // --> create issue
      try {
        Issue newIssueObj =
            ComponentManager.getInstance()
                .getIssueManager()
                .createIssueObject(issueEvent.getUser(), nissue);
        newIssues.add(newIssueObj);
      } catch (CreateException crex) {
        log.error("IssueClonerByComponents::onIssueEvent - Cannot create dependent issues", crex);
      }
    }

    Collection<Attachment> atts = issue.getAttachments();
    if (atts != null) {
      AttachmentManager am = ComponentManager.getInstance().getAttachmentManager();
      for (Attachment att : atts) {
        File attFile = AttachmentUtils.getAttachmentFile(att);
        String filename = att.getFilename();
        String contentType = att.getMimetype();
        for (Issue nissue : newIssues) {
          File newFile = new File(attFile.getAbsolutePath() + nissue.getKey());
          try {
            FileUtils.copyFile(attFile, newFile);
            am.createAttachment(newFile, filename, contentType, issueEvent.getUser(), nissue);
          } catch (Exception ex) {
            log.error("IssueClonerByComponents::onIssueEvent - Cannot copy attachment", ex);
          }
        }
      }
    }

    IssueLinkTypeManager issueLinkTypeManager =
        ComponentManager.getComponentInstanceOfType(IssueLinkTypeManager.class);
    Collection<IssueLinkType> types = issueLinkTypeManager.getIssueLinkTypesByName(LINK_TYPE);
    if (types == null || types.isEmpty()) {
      return;
    }

    IssueLinkType ilt = types.iterator().next();
    if (ilt != null) {
      IssueLinkManager ilm = ComponentManager.getInstance().getIssueLinkManager();
      for (Issue nissue : newIssues) {
        try {
          ilm.createIssueLink(
              issue.getId(), nissue.getId(), ilt.getId(), null, issueEvent.getUser());
        } catch (CreateException crex) {
          log.error("IssueClonerByComponents::onIssueEvent - Cannot create link", crex);
        }
      }
    }
  }
  @Override
  public Map<String, Object> getVelocityParameters(
      Issue issue, CustomField field, FieldLayoutItem fieldLayoutItem) {
    Map<String, Object> params = super.getVelocityParameters(issue, field, fieldLayoutItem);
    params.put("i18n", getI18nBean());
    params.put("baseUrl", applicationProperties.getBaseUrl());

    Long prId;
    if (field.isAllProjects()) {
      prId = Consts.PROJECT_ID_FOR_GLOBAL_CF;
    } else {
      if (issue == null) {
        return params;
      }
      prId = issue.getProjectObject().getId();
    }

    String jqlData = qfMgr.getQueryFieldData(field.getIdAsLong(), prId);
    boolean addNull = qfMgr.getAddNull(field.getIdAsLong(), prId);
    boolean isAutocompleteView = qfMgr.isAutocompleteView(field.getIdAsLong(), prId);
    List<String> options = qfMgr.getLinkeFieldsOptions(field.getIdAsLong(), prId);

    params.put("isAutocompleteView", isAutocompleteView);
    params.put("prId", prId.toString());

    String cfValue = field.getValueFromIssue(issue);
    if (Utils.isValidStr(cfValue)) {
      MutableIssue mi = issueMgr.getIssueObject(cfValue);
      if (mi != null && Utils.isValidStr(mi.getSummary())) {
        StringBuilder sb = new StringBuilder();
        if (options.contains("status")) {
          sb.append(getI18nBean().getText("queryfields.opt.status"))
              .append(": ")
              .append(mi.getStatusObject().getName());
        }
        if (options.contains("assignee") && mi.getAssigneeUser() != null) {
          if (sb.length() > 0) {
            sb.append(", ");
          }
          User aUser = mi.getAssigneeUser();
          String encodedUser;
          try {
            encodedUser = URLEncoder.encode(aUser.getName(), "UTF-8");
          } catch (UnsupportedEncodingException e) {
            // --> impossible
            encodedUser = aUser.getName();
          }

          sb.append(getI18nBean().getText("queryfields.opt.assignee"))
              .append(": ")
              .append("<a class='user-hover' rel='")
              .append(aUser.getName())
              .append("' id='issue_summary_assignee_'")
              .append(aUser.getName())
              .append("' href='/secure/ViewProfile.jspa?name='")
              .append(encodedUser)
              .append("'>")
              .append(aUser.getDisplayName())
              .append("</a>");
        }
        if (options.contains("priority") && mi.getPriorityObject() != null) {
          if (sb.length() > 0) {
            sb.append(", ");
          }
          sb.append(getI18nBean().getText("queryfields.opt.priority"))
              .append(": ")
              .append(mi.getPriorityObject().getName());
        }
        if (options.contains("due") && mi.getDueDate() != null) {
          if (sb.length() > 0) {
            sb.append(", ");
          }
          sb.append(getI18nBean().getText("queryfields.opt.due"))
              .append(": ")
              .append(
                  ComponentAccessor.getJiraAuthenticationContext()
                      .getOutlookDate()
                      .format(mi.getDueDate()));
        }

        if (sb.length() > 0) {
          sb.insert(0, " (");
          sb.append(")");
        }

        IssueData issueData;
        if (options.contains("justDesc")) {
          String descr = mi.getDescription();
          if (Utils.isValidStr(descr)) {
            issueData = new IssueData(descr, sb.toString());
          } else {
            issueData = new IssueData(mi.getSummary(), sb.toString());
          }
        } else if (options.contains("key")) {
          issueData = new IssueData(mi.getKey().concat(":").concat(mi.getSummary()), sb.toString());
        } else {
          issueData = new IssueData(mi.getSummary(), sb.toString());
        }
        params.put("fullValue", issueData);
      }
    }

    if (!Utils.isValidStr(jqlData)) {
      params.put("jqlNotSet", Boolean.TRUE);
      return params;
    }
    params.put("jqlNotSet", Boolean.FALSE);
    params.put("options", options);

    if (options.contains("editKey")) {
      params.put("hasKey", Boolean.TRUE);
    }

    User user = ComponentManager.getInstance().getJiraAuthenticationContext().getLoggedInUser();
    SearchService.ParseResult parseResult = searchService.parseQuery(user, jqlData);
    if (parseResult.isValid()) {
      params.put("jqlNotValid", Boolean.FALSE);
      Query query = parseResult.getQuery();
      try {
        Map<String, String> cfVals = new LinkedHashMap<String, String>();
        SearchResults results = searchService.search(user, query, PagerFilter.getUnlimitedFilter());
        List<Issue> issues = results.getIssues();
        for (Issue i : issues) {
          String summary;
          if (options.contains("justDesc")) {
            String descr = i.getDescription();
            if (Utils.isValidStr(descr)) {
              summary = descr;
            } else {
              summary = i.getSummary();
            }
          } else if (options.contains("editKey")) {
            summary = i.getKey().concat(":").concat(i.getSummary());
          } else {
            summary = i.getSummary();
          }
          cfVals.put(i.getKey(), summary);
        }

        if (addNull) {
          cfVals.put("Empty", Consts.EMPTY_VALUE);
        }

        String selected = Consts.EMPTY_VALUE;
        String value = (String) issue.getCustomFieldValue(field);
        for (Map.Entry<String, String> cf : cfVals.entrySet()) {
          if (value != null && cf.getKey().equals(value)) {
            selected = value;
            break;
          }
        }

        if (isAutocompleteView) {
          Issue selectedIssue = issueMgr.getIssueObject(selected);
          if (selectedIssue != null) {
            params.put("selIssue", selectedIssue);
          }
        } else {
          if (selected.equals("")) {
            String defaultValue = (String) field.getDefaultValue(issue);
            if (defaultValue != null
                && defaultValue.length() > 0
                && cfVals.keySet().contains(defaultValue)) {
              selected = defaultValue;
            }
          }

          if (cfVals != null && !cfVals.isEmpty() && selected.equals("")) {
            selected = cfVals.keySet().iterator().next();
          }
        }

        params.put("selected", selected);
        params.put("isError", Boolean.FALSE);
        params.put("cfVals", cfVals);
      } catch (SearchException e) {
        params.put("isError", Boolean.TRUE);
      }
    } else {
      params.put("jqlNotValid", Boolean.TRUE);
      return params;
    }

    return params;
  }
 private MockPicoContainer getMockContainer() {
   return (MockPicoContainer) ComponentManager.getInstance().getContainer();
 }
 DashboardPermissionService getPermissionService() {
   return ComponentManager.getComponentInstanceOfType(DashboardPermissionService.class);
 }
/**
 * PlugIn utility methods.
 *
 * @author Andrey Markelov
 */
public class Utils {
  private static final Logger log = LoggerFactory.getLogger(Utils.class);

  private static final SearchService searchService =
      ComponentManager.getComponentInstanceOfType(SearchService.class);

  /** Get base URL from HTTP request. */
  public static String getBaseUrl(HttpServletRequest req) {
    return (req.getScheme()
        + "://"
        + req.getServerName()
        + ":"
        + req.getServerPort()
        + req.getContextPath());
  }

  /** Check that string is not empty and not null. */
  public static boolean isValidStr(String str) {
    return (str != null && str.length() > 0);
  }

  /** Convert string list to string. */
  public static String listToString(List<String> list) {
    StringBuilder sb = new StringBuilder();

    if (list != null) {
      for (String item : list) {
        sb.append(item).append("&");
      }
    }

    return sb.toString();
  }

  /** Convert string to string list. */
  public static List<String> stringToList(String str) {
    List<String> list = new ArrayList<String>();

    if (str != null) {
      StringTokenizer st = new StringTokenizer(str, "&");
      while (st.hasMoreTokens()) {
        list.add(st.nextToken());
      }
    }

    return list;
  }

  public static List<Issue> executeJQLQuery(String jqlQuery) {
    List<Issue> result = null;

    User user = ComponentManager.getInstance().getJiraAuthenticationContext().getLoggedInUser();
    SearchService.ParseResult parseResult = searchService.parseQuery(user, jqlQuery);

    if (parseResult.isValid()) {
      Query query = parseResult.getQuery();
      try {
        SearchResults results = searchService.search(user, query, PagerFilter.getUnlimitedFilter());
        result = results.getIssues();
      } catch (SearchException e) {
        log.error("Utils::search exception during executing JQL", e);
      }
    }

    return result;
  }

  public static boolean isOfQueryMultiSelectType(String cfType) {
    return Consts.CF_KEY_QUERY_LINKER_MULTI_FIELD.equals(cfType);
  }

  /** Private constructor. */
  private Utils() {}
}