예제 #1
0
 public void doValidation(
     String key, Map<String, String> parameters, JiraServiceContext jiraServiceContext) {
   // JRA-13808: Need to check whether or not the user CF has a searcher set.
   String customFieldOption = parameters.get(getType());
   if (StringUtils.isEmpty(customFieldOption)) {
     String localisedMessage =
         jiraServiceContext
             .getI18nBean()
             .getText("admin.permissions.errors.please.select.user.customfield");
     jiraServiceContext.getErrorCollection().addErrorMessage(localisedMessage);
   } else {
     // passed in parameters names a Custom Field - lets investigate.
     CustomField customField = customFieldManager.getCustomFieldObject(customFieldOption);
     if (customField != null && customField.getCustomFieldSearcher() == null) {
       // In order to use a Custom Field it must be indexed in Lucene Index. Currently we only
       // index custom fields if they have a Searcher.
       // Message: "Custom field '{0}' is not indexed for searching - please add a searcher to this
       // Custom Field."
       String localisedMessage =
           jiraServiceContext
               .getI18nBean()
               .getText("admin.permissions.errors.customfieldnotindexed", customField.getName());
       jiraServiceContext.getErrorCollection().addErrorMessage(localisedMessage);
     }
   }
 }
 public Collection getCustomFieldObjectsByName(final String customFieldName) {
   Collection objectsByName = new ArrayList();
   for (Iterator iterator = customFields.iterator(); iterator.hasNext(); ) {
     CustomField customField = (CustomField) iterator.next();
     if (customField.getName().equals(customFieldName)) {
       objectsByName.add(customField);
     }
   }
   return objectsByName;
 }
예제 #3
0
 /**
  * Method to determine if a field must try to retain the values already set in issues. In the case
  * of Components, Versions and Version custom fields, we must retain where possible since if we
  * select issues that don't need moving, then no mapping options will be presented, but we don't
  * want other values to be chosen for those issues. Hence, their values must be retained.
  *
  * @param field the field to check for
  * @return true if retaining should be mandatory; false otherwise.
  */
 public boolean isRetainMandatory(OrderableField field) {
   if (field instanceof CustomField) {
     final CustomField customField = (CustomField) field;
     return customField.getCustomFieldType() instanceof VersionCFType;
   } else {
     final String id = field.getId();
     return (IssueFieldConstants.FIX_FOR_VERSIONS.equals(id)
         || IssueFieldConstants.AFFECTED_VERSIONS.equals(id)
         || IssueFieldConstants.COMPONENTS.equals(id));
   }
 }
  @Test
  public void testGetClauseFromParamsValuesGetFiltered() throws Exception {
    final String clauseName = "clauseName";

    final CustomField customField = mockController.getMock(CustomField.class);
    EasyMock.expect(customField.getName()).andStubReturn("ABC");
    EasyMock.expect(customFieldInputHelper.getUniqueClauseName(theUser, clauseName, "ABC"))
        .andStubReturn(clauseName);

    final CustomFieldParamsImpl customFieldParams = new CustomFieldParamsImpl();
    customFieldParams.addValue(CollectionBuilder.newBuilder("55", "-1", "").asMutableSet());

    final Set<String> expectedFilteredValues = CollectionBuilder.newBuilder("55").asMutableSet();

    final Clause expectedClause = mockController.getMock(Clause.class);

    final IndexedInputHelper indexedInputHelper = mockController.getMock(IndexedInputHelper.class);
    indexedInputHelper.getClauseForNavigatorValues(clauseName, expectedFilteredValues);
    mockController.setReturnValue(expectedClause);

    transformer =
        new VersionCustomFieldSearchInputTransformer(
            clauseName,
            new ClauseNames(clauseName),
            customField,
            indexInfoResolver,
            operandResolver,
            fieldFlagOperandRegistry,
            searchContextVisibilityChecker,
            versionResolver,
            customFieldInputHelper,
            versionManager) {
          @Override
          IndexedInputHelper getIndexedInputHelper() {
            return indexedInputHelper;
          }

          @Override
          boolean isVersionsNotRelatedToProjects(
              final Set<String> versionIdsFromHolder, final FieldValuesHolder fieldValuesHolder) {
            return false;
          }
        };

    mockController.replay();

    FieldValuesHolder holderValues =
        new FieldValuesHolderImpl(MapBuilder.singletonMap(urlParameterName, customFieldParams));
    assertEquals(
        expectedClause, transformer.getClauseFromParams(theUser, customFieldParams, holderValues));

    mockController.verify();
  }
  /** Get custom fields by type. */
  private Map<String, String> getFieldsByType(String type) {
    Map<String, String> params = new TreeMap<String, String>();

    List<CustomField> fields = ComponentAccessor.getCustomFieldManager().getCustomFieldObjects();
    if (fields != null) {
      for (CustomField cf : fields) {
        if (cf.getCustomFieldType().getKey().equals(type)) {
          params.put(cf.getId(), cf.getName());
        }
      }
    }

    return params;
  }
  @Test
  public void testGlobalSchemeConfig() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.LIKE, "fine");
    final ClauseContext context3 = createContextForProjects(64);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);

    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme, scheme));
    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context3);
    when(scheme.isGlobal()).thenReturn(false, true);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator);

    assertEquals(
        ClauseContextImpl.createGlobalClauseContext(),
        factory.getClauseContext(theUser, testClause));
  }
 @EventListener
 public void issueEvent(IssueEvent issueEvent) {
   if (priorityCustomField == null) priorityCustomField = getSortingCustomField();
   if (priorityCustomField == null) return;
   Issue issue = issueEvent.getIssue();
   User initiator = issueEvent.getUser();
   // if priority not changed stringNewPriority is null
   if (issueEvent.getEventTypeId().equals(EventType.ISSUE_CREATED_ID)) {
     Object priorityObject = issue.getCustomFieldValue(priorityCustomField);
     if (priorityObject == null) return;
     Double priority = (Double) priorityObject;
     User assignee = issue.getAssignee();
     updatePriorities(initiator, assignee, issue, priority);
   } else {
     String stringNewPriority =
         getChangedField(issueEvent.getChangeLog(), priorityCustomField.getName(), false);
     String stringNewAssignee = getChangedField(issueEvent.getChangeLog(), "Assignee", false);
     if (stringNewAssignee != null || stringNewPriority != null) {
       Double priority = (Double) issue.getCustomFieldValue(priorityCustomField);
       if (priority == null) return;
       User assignee = issue.getAssignee();
       if (assignee == null) return;
       updatePriorities(initiator, assignee, issue, priority);
     }
   }
 }
 public boolean isFieldLocked() {
   CustomField customField = getCustomField();
   ManagedConfigurationItem managedConfigurationItem =
       managedConfigurationItemService.getManagedCustomField(customField);
   boolean locked =
       !managedConfigurationItemService.doesUserHavePermission(
           getLoggedInUser(), managedConfigurationItem);
   if (locked) {
     addErrorMessage(
         getText(
             "admin.managed.configuration.items.customfield.error.cannot.alter.context.locked",
             customField.getName()),
         Reason.FORBIDDEN);
   }
   return locked;
 }
  public CustomField getCustomFieldObject(Long id) {
    if (id == null) {
      return null;
    }
    String idString = id.toString();

    for (Iterator iterator = customFields.iterator(); iterator.hasNext(); ) {
      CustomField customField = (CustomField) iterator.next();
      if (idString.equals(customField.getId())
          || ("customfield_" + idString).equals(customField.getId())) {
        return customField;
      }
    }

    return null;
  }
  @Test
  public void testBadOperatorUsage() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");
    final ClauseContext context1 = createContextForProjects(1, 2);
    final ClauseContext context2 = createContextForProjects(5);
    final ClauseContext context3 = createContextForProjects(1292);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);
    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));

    operatorUsageValidator = mock(OperatorUsageValidator.class);
    when(operatorUsageValidator.check(theUser, testClause)).thenReturn(false);
    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context1, context2);
    when(contextSetUtil.union(CollectionBuilder.newBuilder(context1, context2).asSet()))
        .thenReturn(context3);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator);

    assertEquals(context3, factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void testNegativeQueryWithPositiveAndNegativeOptions() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.NOT_EQUALS, "fine");
    final MockOption option1 = new MockOption(null, null, null, null, null, 25L);
    final MockOption option2 = new MockOption(null, null, null, null, null, 26L);
    final MockOption option2child2 = new MockOption(option2, null, null, null, null, 28L);
    final MockOption option2child1 = new MockOption(option2, null, null, null, null, 27L);
    option2.setChildOptions(Arrays.asList(option2child1, option2child2));

    final ClauseContext context1 = createContextForProjects(1, 2);
    final ClauseContext context2 = createContextForProjects(3);
    final ClauseContext context3 = createContextForProjects(3);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);
    when(scheme.isGlobal()).thenReturn(false);

    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));

    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context1, context2);

    // The second scheme should not be included because it only has options that we are to exclude.
    when(jqlSelectOptionsUtil.getOptionsForScheme(scheme))
        .thenReturn(Arrays.<Option>asList(option1, option2))
        .thenReturn(Arrays.<Option>asList(option2, option2child1, option2child2));

    when(contextSetUtil.union(CollectionBuilder.newBuilder(context1, context2).asSet()))
        .thenReturn(context3);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {

            assertEquals(theUser, user);
            assertEquals(testClause, clause);

            positiveOption.add(option2);
            negativeOption.add(option2child1);
          }
        };

    assertEquals(context3, factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void shouldAddCustomFieldParamsOnDelete() throws Exception {
    final CustomField customField1 = createMock(CustomField.class);
    expect(customField1.getId()).andReturn("customfield_10000");
    expect(customField1.getValue(issue)).andReturn("Value1");
    final CustomField customField2 = createMock(CustomField.class);
    expect(customField2.getId()).andReturn("customfield_10001");
    expect(customField2.getValue(issue)).andReturn("Value2");
    replay(customField1, customField2);

    expect(customFieldManager.getCustomFieldObjects(issue))
        .andReturn(ImmutableList.of(customField1, customField2));
    IssueDeleteHelper tested = getIssueDeleteHelper();
    setUpEmptyWatchers();
    expect(mockSubTaskManager.isSubTask(issueGenericValue)).andReturn(false);
    replayMocks();

    tested.deleteIssue((User) null, issue, EventDispatchOption.ISSUE_DELETED, true);
    makeAssertions();
    verify(customField1, customField2);
    final Map<String, Object> expected =
        ImmutableMap.<String, Object>of(
            "customfield_10000", "Value1", "customfield_10001", "Value2");
    assertEquals(expected, capturedEventParams.get(IssueEvent.CUSTOM_FIELDS_PARAM_NAME));
    assertTrue(capturedSendMailFlag);
  }
  @Override
  protected void getVelocityParamsForView(
      Map<String, Object> velocityParams, AbstractDescriptor descriptor) {
    String lCf = getParam(descriptor, Consts.LATEST_START_FIELD);
    String cCf = getParam(descriptor, Consts.CALCULATED_FIELD);
    CustomFieldManager cfMgr = ComponentAccessor.getCustomFieldManager();

    if (lCf != null && lCf.length() > 0) {
      velocityParams.put("nolCf", Boolean.FALSE);

      CustomField lCfObj = cfMgr.getCustomFieldObject(lCf);
      if (lCfObj != null) {
        velocityParams.put("nolCfObj", Boolean.FALSE);
        velocityParams.put("lCfName", lCfObj.getName());
      } else {
        velocityParams.put("nolCfObj", Boolean.TRUE);
      }
    } else {
      velocityParams.put("nolCf", Boolean.TRUE);
    }

    if (cCf != null && cCf.length() > 0) {
      velocityParams.put("nocCf", Boolean.FALSE);

      CustomField cCfObj = cfMgr.getCustomFieldObject(cCf);
      if (cCfObj != null) {
        velocityParams.put("nocCfObj", Boolean.FALSE);
        velocityParams.put("cCfName", cCfObj.getName());
      } else {
        velocityParams.put("nocCfObj", Boolean.TRUE);
      }
    } else {
      velocityParams.put("nocCf", Boolean.TRUE);
    }

    velocityParams.put(Consts.LATEST_START_FIELD, getParam(descriptor, Consts.LATEST_START_FIELD));
    velocityParams.put(Consts.CALCULATED_FIELD, getParam(descriptor, Consts.CALCULATED_FIELD));
  }
  public void testHeadingMarkupForCustomFields() {

    CustomField cf = createMock(CustomField.class);
    CustomFieldSearcher cfs = createMock(CustomFieldSearcher.class);
    CustomFieldSearcherModuleDescriptor cfmd =
        createMock(CustomFieldSearcherModuleDescriptor.class);

    expect(cfm.getCustomFieldObject("customfield_nick")).andReturn(cf);
    replay(cfm);

    expect(cf.getCustomFieldSearcher()).andReturn(cfs);
    replay(cf);

    expect(cfs.getDescriptor()).andReturn(cfmd);
    replay(cfs);

    expect(cfmd.getStatHtml(cf, "nick", FULL_URL)).andReturn("CustomField Markup");
    replay(cfmd);

    final StatsMarkup statsMarkup =
        ObjectToFieldValueMapper.transform("customfield_nick", "nick", FULL_URL, transformer);

    assertEquals("CustomField Markup", statsMarkup.getHtml());
  }
  @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));
            }
          }
        }
      }
    }
  }
  @Test
  public void testPositiveQueryWithPositiveAndNegativeOptions() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");
    final MockOption option1 = new MockOption(null, null, null, null, null, 25L);
    final MockOption option2 = new MockOption(null, null, null, null, null, 26L);
    final MockOption option2child2 = new MockOption(option2, null, null, null, null, 28L);
    final MockOption option2child1 = new MockOption(option2, null, null, null, null, 27L);
    option2.setChildOptions(Arrays.asList(option2child1, option2child2));

    final ClauseContext context1 = createContextForProjects(1, 56);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);
    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));

    // The second scheme has no options in the scheme not in the exclude list.
    when(jqlSelectOptionsUtil.getOptionsForScheme(scheme))
        .thenReturn(Arrays.<Option>asList(option1, option2))
        .thenReturn(Arrays.<Option>asList(option2, option2child1, option2child2));
    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context1);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {
            assertEquals(theUser, user);
            assertEquals(testClause, clause);

            positiveOption.add(option1);
            negativeOption.add(option2);
          }
        };

    assertEquals(context1, factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void testNegativeQueryWithNoOptions() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.NOT_IN, "fine");
    final MockOption option2 = new MockOption(null, null, null, null, null, 26L);
    final MockOption option2child2 = new MockOption(option2, null, null, null, null, 28L);
    final MockOption option2child1 = new MockOption(option2, null, null, null, null, 27L);
    option2.setChildOptions(Arrays.asList(option2child1, option2child2));

    final ClauseContext context2 = createContextForProjects(3);
    final ClauseContext context3 = createContextForProjects(64);
    final ClauseContext context4 = createContextForProjects(34938);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);
    when(scheme.isGlobal()).thenReturn(false);

    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));

    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context3, context2);
    when(contextSetUtil.union(CollectionBuilder.newBuilder(context2, context3).asSet()))
        .thenReturn(context4);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {
            assertEquals(theUser, user);
            assertEquals(testClause, clause);
          }
        };

    assertEquals(context4, factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void testNoGeneratedContext() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");
    final MockOption option1 = new MockOption(null, null, null, null, null, 25L);
    final MockOption option2 = new MockOption(null, null, null, null, null, 26L);
    final ClauseContext context1 = createContextForProjects(1, 2);
    final ClauseContext context2 = createContextForProjects(5);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);
    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));
    when(jqlSelectOptionsUtil.getOptionsForScheme(scheme))
        .thenReturn(Arrays.<Option>asList(option1, option2));
    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context1, context2);
    when(contextSetUtil.union(CollectionBuilder.newBuilder(context1, context2).asSet()))
        .thenReturn(new ClauseContextImpl());

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {

            assertEquals(theUser, user);
            assertEquals(testClause, clause);

            positiveOption.add(option1);
          }
        };

    assertEquals(
        ClauseContextImpl.createGlobalClauseContext(),
        factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void testNullSchemes() throws Exception {
    final TerminalClause clause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");

    when(customField.getConfigurationSchemes()).thenReturn(null);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator);
    final ClauseContext clauseContext = factory.getClauseContext(theUser, clause);

    assertEquals(ClauseContextImpl.createGlobalClauseContext(), clauseContext);
  }
  @Test
  public void testPositiveQueryWithNoPositive() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");
    final MockOption option1 = new MockOption(null, null, null, null, null, 25L);
    final MockOption option2 = new MockOption(null, null, null, null, null, 26L);
    final MockOption option2child2 = new MockOption(option2, null, null, null, null, 28L);
    final MockOption option2child1 = new MockOption(option2, null, null, null, null, 27L);
    option2.setChildOptions(Arrays.asList(option2child1, option2child2));

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);

    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));
    when(scheme.isGlobal()).thenReturn(true);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {
            assertEquals(theUser, user);
            assertEquals(testClause, clause);

            negativeOption.add(option2);
            negativeOption.add(option1);
          }
        };

    assertEquals(
        ClauseContextImpl.createGlobalClauseContext(),
        factory.getClauseContext(theUser, testClause));
  }
  @Test
  public void testPositiveQueryWithPositiveAndEmpty() throws Exception {
    final TerminalClause testClause = new TerminalClauseImpl("one", Operator.EQUALS, "fine");
    final ClauseContext context1 = createContextForProjects(1, 56);

    final FieldConfigScheme scheme = mock(FieldConfigScheme.class);

    when(customField.getConfigurationSchemes()).thenReturn(Arrays.asList(scheme, scheme));
    when(scheme.isGlobal()).thenReturn(false, true);
    when(fieldConfigSchemeClauseContextUtil.getContextForConfigScheme(theUser, scheme))
        .thenReturn(context1);

    final CascadingSelectCustomFieldClauseContextFactory factory =
        new CascadingSelectCustomFieldClauseContextFactory(
            customField,
            contextSetUtil,
            jqlSelectOptionsUtil,
            fieldConfigSchemeClauseContextUtil,
            jqlOperandResolver,
            jqlCascadingSelectLiteralUtil,
            operatorUsageValidator) {
          @Override
          void fillOptions(
              final User user,
              final TerminalClause clause,
              final Set<Option> positiveOption,
              final Set<Option> negativeOption) {
            assertEquals(theUser, user);
            assertEquals(testClause, clause);

            positiveOption.add(null);
          }
        };

    assertEquals(
        ClauseContextImpl.createGlobalClauseContext(),
        factory.getClauseContext(theUser, testClause));
  }
 @Override
 public String getIndexedValue(CustomField indexedObject) {
   notNull("indexedObject", indexedObject);
   return indexedObject.toString().toLowerCase();
 }
 private JsonType getJsonType(CustomField field) {
   return JsonTypeBuilder.customArray(
       JsonType.STRING_TYPE, field.getCustomFieldType().getKey(), field.getIdAsLong());
 }
예제 #24
0
 /**
  * @param field the custom field to get the values of
  * @param issue the issue to get the value from
  * @return either a single user value or a {@link java.util.Collection} of values.
  */
 Object getValuesFromIssue(final CustomField field, final Issue issue) {
   return field.getCustomFieldType().getValueFromIssue(field, issue);
 }
예제 #25
0
 @Override
 public JsonType getJsonSchema(CustomField customField) {
   return JsonTypeBuilder.custom(JsonType.NUMBER_TYPE, getKey(), customField.getIdAsLong());
 }
  @Override
  public boolean handleMessage(Message message, MessageHandlerContext context)
      throws MessagingException {
    log.debug("CreateIssueHandler.handleMessage");

    if (!canHandleMessage(message, context.getMonitor())) {
      return deleteEmail;
    }

    try {
      // get either the sender of the message, or the default reporter
      User reporter = getReporter(message, context);

      // no reporter - so reject the message
      if (reporter == null) {
        final String error = getI18nBean().getText("admin.mail.no.default.reporter");
        context.getMonitor().warning(error);
        context.getMonitor().messageRejected(message, error);
        return false;
      }

      final Project project = getProject(message);

      log.debug("Project = " + project);
      if (project == null) {
        final String text = getI18nBean().getText("admin.mail.no.project.configured");
        context.getMonitor().warning(text);
        context.getMonitor().messageRejected(message, text);
        return false;
      }

      // Check that the license is valid before allowing issues to be created
      // This checks for: evaluation licenses expired, user limit licenses where limit has been
      // exceeded
      ErrorCollection errorCollection = new SimpleErrorCollection();
      // Note: want English locale here for logging purposes
      I18nHelper i18nHelper = new I18nBean(Locale.ENGLISH);

      getIssueCreationHelperBean().validateLicense(errorCollection, i18nHelper);
      if (errorCollection.hasAnyErrors()) {
        context
            .getMonitor()
            .warning(
                getI18nBean()
                    .getText(
                        "admin.mail.bad.license", errorCollection.getErrorMessages().toString()));
        return false;
      }

      // If user does not have create permissions, there's no point proceeding. Error out here to
      // avoid a stack
      // trace blow up from the WorkflowManager later on.
      if (!getPermissionManager().hasPermission(Permissions.CREATE_ISSUE, project, reporter, true)
          && reporter.getDirectoryId() != -1) {
        final String error =
            getI18nBean().getText("admin.mail.no.create.permission", reporter.getName());
        context.getMonitor().warning(error);
        context.getMonitor().messageRejected(message, error);
        return false;
      }

      log.debug("Issue Type Key = = " + issueType);

      if (!hasValidIssueType()) {
        context.getMonitor().warning(getI18nBean().getText("admin.mail.invalid.issue.type"));
        return false;
      }
      String summary = message.getSubject();
      if (!TextUtils.stringSet(summary)) {
        context.getMonitor().error(getI18nBean().getText("admin.mail.no.subject"));
        return false;
      }
      if (summary.length() > SummarySystemField.MAX_LEN.intValue()) {
        context.getMonitor().info("Truncating summary field because it is too long: " + summary);
        summary = summary.substring(0, SummarySystemField.MAX_LEN.intValue() - 3) + "...";
      }

      // JRA-7646 - check if priority/description is hidden - if so, do not set
      String priority = null;
      String description = null;

      if (!getFieldVisibilityManager()
          .isFieldHiddenInAllSchemes(
              project.getId(),
              IssueFieldConstants.PRIORITY,
              Collections.singletonList(issueType))) {
        priority = getPriority(message);
      }

      if (!getFieldVisibilityManager()
          .isFieldHiddenInAllSchemes(
              project.getId(),
              IssueFieldConstants.DESCRIPTION,
              Collections.singletonList(issueType))) {
        description = getDescription(reporter, message);
      }

      MutableIssue issueObject = getIssueFactory().getIssue();
      issueObject.setProjectObject(project);
      issueObject.setSummary(summary);
      issueObject.setDescription(description);
      issueObject.setIssueTypeId(issueType);
      issueObject.setReporter(reporter);

      // if no valid assignee found, attempt to assign to default assignee
      User assignee = null;
      if (ccAssignee) {
        assignee = getFirstValidAssignee(message.getAllRecipients(), project);
      }
      if (assignee == null) {
        assignee = getAssigneeResolver().getDefaultAssignee(issueObject, Collections.EMPTY_MAP);
      }

      if (assignee != null) {
        issueObject.setAssignee(assignee);
      }

      issueObject.setPriorityId(priority);

      // Ensure issue level security is correct
      setDefaultSecurityLevel(issueObject);

      /*
       * + FIXME -- set cf defaults @todo +
       */
      // set default custom field values
      // CustomFieldValuesHolder cfvh = new CustomFieldValuesHolder(issueType, project.getId());
      // fields.put("customFields", CustomFieldUtils.getCustomFieldValues(cfvh.getCustomFields()));
      Map<String, Object> fields = new HashMap<String, Object>();
      fields.put("issue", issueObject);
      // TODO: How is this supposed to work? There is no issue created yet; ID = null.
      // wseliga note: Ineed I think that such call does not make sense - it will be always null
      MutableIssue originalIssue = getIssueManager().getIssueObject(issueObject.getId());

      // Give the CustomFields a chance to set their default values JRA-11762
      List<CustomField> customFieldObjects =
          ComponentAccessor.getCustomFieldManager().getCustomFieldObjects(issueObject);
      for (CustomField customField : customFieldObjects) {
        issueObject.setCustomFieldValue(customField, customField.getDefaultValue(issueObject));
      }

      fields.put(WorkflowFunctionUtils.ORIGINAL_ISSUE_KEY, originalIssue);
      final Issue issue = context.createIssue(reporter, issueObject);

      if (issue != null) {
        // Add Cc'ed users as watchers if params set - JRA-9983
        if (ccWatcher) {
          addCcWatchersToIssue(message, issue, reporter, context, context.getMonitor());
        }

        // Record the message id of this e-mail message so we can track replies to this message
        // and associate them with this issue
        recordMessageId(
            MailThreadManager.ISSUE_CREATED_FROM_EMAIL, message, issue.getId(), context);
      }

      // TODO: if this throws an error, then the issue is already created, but the email not deleted
      // - we will keep "handling" this email over and over :(
      createAttachmentsForMessage(message, issue, context);

      return true;
    } catch (Exception e) {
      context.getMonitor().warning(getI18nBean().getText("admin.mail.unable.to.create.issue"), e);
    }

    // something went wrong - don't delete the message
    return false;
  }
예제 #27
0
 public String getArgumentDisplay(String argument) {
   CustomField field = fieldManager.getCustomField(argument);
   return field.getName();
 }
예제 #28
0
 @Override
 public String getArgumentDisplay(String argument) {
   CustomFieldManager fieldManager = ComponentAccessor.getCustomFieldManager();
   CustomField field = fieldManager.getCustomFieldObject(argument);
   return (field != null) ? field.getName() : argument;
 }
  @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;
  }