@Test
  public void testFormatEmailLoggedInOnly() throws Exception {
    final ApplicationProperties applicationProperties = getMock(ApplicationProperties.class);
    expect(applicationProperties.getString(APKeys.JIRA_OPTION_EMAIL_VISIBLE))
        .andReturn("user")
        .times(2);

    final EmailFormatterImpl formatter = instantiate(EmailFormatterImpl.class);

    assertEquals(USER_EXAMPLE_ORG, formatter.formatEmail(USER_EXAMPLE_ORG, true));
    assertNull(formatter.formatEmail(USER_EXAMPLE_ORG, false));
  }
  @Test
  public void testFindGroupsWithNoMatch() throws Exception {
    final MockUser mockUser = new MockUser("mocky");

    expect(authenticationContext.getLoggedInUser()).andReturn(mockUser);
    expect(permissionManager.hasPermission(Permissions.USER_PICKER, mockUser)).andReturn(true);
    expect(groupPickerSearchService.findGroups("la")).andStubReturn(matchingGroups);
    expect(authenticationContext.getI18nHelper()).andStubReturn(i18nHelper);
    expect(applicationProperties.getDefaultBackedString(APKeys.JIRA_AJAX_AUTOCOMPLETE_LIMIT))
        .andStubReturn("20");

    GroupPickerResource resource = new GroupPickerResource(groupPickerResourceHelper);

    final List<GroupSuggestionBean> expectedGroups = Lists.newArrayList();

    final GroupSuggestionsBean expectedSuggestions =
        new GroupSuggestionsBean(
            0,
            NoopI18nHelper.makeTranslation(
                GroupPickerResourceHelperImpl.MORE_GROUP_RESULTS_I18N_KEY, "0", "0"),
            expectedGroups);

    replay(
        groupPickerSearchService, authenticationContext, applicationProperties, permissionManager);

    Response response = resource.findGroups("la", null, null);
    assertResponseCacheNever(response);
    assertResponseBody(expectedSuggestions, response);

    verify(groupPickerSearchService, authenticationContext, applicationProperties);
  }
  public int getMaxUsersDisplayedPerGroup() {
    if (maxMembers == null) {
      final int MAX_USERS_DISPLAYED_PER_GROUP = 200;

      String maxMembersStr =
          applicationProperties.getDefaultBackedString(APKeys.USER_MANAGEMENT_MAX_DISPLAY_MEMBERS);
      if (maxMembersStr != null) {
        try {
          maxMembers = Integer.valueOf(maxMembersStr.trim());
        } catch (NumberFormatException e) {
          log.warn(
              "Invalid format of '"
                  + APKeys.USER_MANAGEMENT_MAX_DISPLAY_MEMBERS
                  + "' property: '"
                  + maxMembersStr
                  + "'. Value should be an integer. Using "
                  + MAX_USERS_DISPLAYED_PER_GROUP);
          maxMembers = new Integer(MAX_USERS_DISPLAYED_PER_GROUP);
        }
      } else {
        log.debug(
            "'"
                + APKeys.USER_MANAGEMENT_MAX_DISPLAY_MEMBERS
                + "' is missing. Using "
                + MAX_USERS_DISPLAYED_PER_GROUP
                + " instead.");
        maxMembers = new Integer(MAX_USERS_DISPLAYED_PER_GROUP);
      }
    }

    return maxMembers.intValue();
  }
 @GET
 @AnonymousAllowed
 @Path("option/set")
 public Response setOption(@QueryParam("key") String key, @QueryParam("value") boolean value) {
   applicationProperties.setOption(key, value);
   return Response.ok(null).build();
 }
 @POST
 @AnonymousAllowed
 @Path("string/set")
 public Response setString(KeyValueHolder holder) {
   applicationProperties.setString(holder.key, holder.value);
   return Response.ok(null).build();
 }
  @Test
  public void testUserWithNoBrowseUserPermissionsDoesntReturnNonExactMatchedGroup() {
    String mockGroupName = "mockGroup";
    final MockUser mockUser = new MockUser("mocky");
    final MockGroup mockGroup = new MockGroup(mockGroupName);

    expect(authenticationContext.getLoggedInUser()).andReturn(mockUser);
    expect(permissionManager.hasPermission(Permissions.USER_PICKER, mockUser)).andReturn(false);
    expect(groupPickerSearchService.getGroupByName(mockGroupName)).andStubReturn(mockGroup);
    expect(authenticationContext.getI18nHelper()).andStubReturn(i18nHelper);
    expect(applicationProperties.getDefaultBackedString(APKeys.JIRA_AJAX_AUTOCOMPLETE_LIMIT))
        .andStubReturn("20");

    GroupPickerResource resource = new GroupPickerResource(groupPickerResourceHelper);

    final List<GroupSuggestionBean> expectedGroups = Lists.newArrayList();

    final GroupSuggestionsBean expectedSuggestions =
        new GroupSuggestionsBean(
            0,
            NoopI18nHelper.makeTranslation(
                GroupPickerResourceHelperImpl.MORE_GROUP_RESULTS_I18N_KEY, 0, 0),
            expectedGroups);

    replay(
        groupPickerSearchService, authenticationContext, applicationProperties, permissionManager);
    Response response = resource.findGroups("mockGr", null, null);
    assertResponseBody(expectedSuggestions, response);
  }
  private void validateExistingProjectHasValidStateForImport(
      final BackupProject backupProject,
      final BackupSystemInformation backupSystemInformation,
      final Project existingProject,
      final I18nHelper i18n,
      final MessageSet messageSet) {
    final String projectKey = backupProject.getProject().getKey();

    // Verify that the project has no existing issues
    final long issueCount = issueManager.getIssueCountForProject(existingProject.getId());
    if (issueCount != 0) {
      messageSet.addErrorMessage(
          getText(
              i18n,
              "admin.error.project.import.project.contains.issues",
              projectKey,
              String.valueOf(issueCount)));
    }

    // Verify that the project has no existing versions
    final long versionCount = versionManager.getVersions(existingProject.getId()).size();
    if (versionCount != 0) {
      messageSet.addErrorMessage(
          getText(
              i18n,
              "admin.error.project.import.project.contains.versions",
              projectKey,
              String.valueOf(versionCount)));
    }

    // Verify that the project has no existing components
    final long componentCount =
        projectComponentManager.findAllForProject(existingProject.getId()).size();
    if (componentCount != 0) {
      messageSet.addErrorMessage(
          getText(
              i18n,
              "admin.error.project.import.project.contains.components",
              projectKey,
              String.valueOf(componentCount)));
    }

    // Verify that if the project has a default assignee of Unassigned that the current instance of
    // JIRA supports unassigned issues
    if (projectHasDefaultAssigneeUnassigned(backupProject, backupSystemInformation)) {
      // We want this instance of JIRA to allow unassigned issues.
      final boolean allowUnassigned =
          applicationProperties.getOption(APKeys.JIRA_OPTION_ALLOWUNASSIGNED);
      if (!allowUnassigned) {
        messageSet.addErrorMessage(
            getText(
                i18n,
                "admin.error.project.import.project.default.assignee.not.allowed",
                backupProject.getProject().getName()));
      }
    }
  }
  @Test
  public void testGetLicenseExpiryStatusMessageForExpiredEvaluation() {
    mockLicense.setEvaluation(true);
    mockLicense.setExpiryDate(now);
    mockLicense.setExpired(true);

    applicationProperties.setOption(APKeys.JIRA_CONFIRMED_INSTALL_WITH_OLD_LICENSE, true);

    assertExpiryMessageContains("admin.license.expired");
  }
  @Test
  public void testFormatEmailAsLinkEncoding() {
    MockControl mockApplicationPropertiesControl =
        MockControl.createControl(ApplicationProperties.class);
    ApplicationProperties mockApplicationProperties =
        (ApplicationProperties) mockApplicationPropertiesControl.getMock();
    mockApplicationProperties.getString("jira.option.emailvisible");
    mockApplicationPropertiesControl.setDefaultReturnValue("show");
    mockApplicationPropertiesControl.replay();

    EmailFormatterImpl emailFormatter = new EmailFormatterImpl(mockApplicationProperties);

    String email = emailFormatter.formatEmailAsLink("*****@*****.**", null);
    assertEquals("<a href=\"mailto:[email protected]\">[email protected]</a>", email);

    email = emailFormatter.formatEmailAsLink("\"<script>alert('owned')</script>\"@localhost", null);
    assertEquals(
        "<a href=\"mailto:&quot;&lt;script&gt;alert(&#39;owned&#39;)&lt;/script&gt;&quot;@localhost\">&quot;&lt;script&gt;alert(&#39;owned&#39;)&lt;/script&gt;&quot;@localhost</a>",
        email);

    mockApplicationPropertiesControl.verify();
  }
 /**
  * @see UserPickerSearchService#canShowEmailAddresses(com.atlassian.jira.bc.JiraServiceContext)
  */
 @Override
 public boolean canShowEmailAddresses(final JiraServiceContext jiraServiceContext) {
   if (canPerformAjaxSearch(jiraServiceContext)) {
     final String emailVisibility =
         applicationProperties.getDefaultBackedString(APKeys.JIRA_OPTION_EMAIL_VISIBLE);
     if (VISIBILITY_PUBLIC.equals(emailVisibility)
         || (VISIBILITY_MASKED.equals(emailVisibility))
         || (VISIBILITY_USER.equals(emailVisibility)
             && (jiraServiceContext.getLoggedInUser() != null))) {
       return true;
     }
   }
   return false;
 }
  @Test
  public void testExternalUserManagementNoOsUser() throws Exception {
    applicationProperties.setOption(APKeys.JIRA_OPTION_USER_EXTERNALMGT, true);
    UpgradeTask_Build601 task = new MyUpgradeTask_Build601(null, false, applicationProperties);

    task.doUpgrade(false);
    Collection<String> errors = task.getErrors();

    assertEquals(1, errors.size());
    assertTrue(
        errors
            .iterator()
            .next()
            .contains(
                "JIRA is unable to migrate the User Directory configuration because external user management is enabled but the osuser.xml file is not available."));
  }
  @Test
  public void testFindGroupsWithDefaultLimit() throws Exception {
    for (int i = 0; i < GroupPickerResourceHelperImpl.DEFAULT_MAX_RESULTS + 1; ++i) {
      matchingGroups.add(new MockGroup("a" + String.valueOf(i)));
    }

    final MockUser mockUser = new MockUser("mocky");

    expect(authenticationContext.getLoggedInUser()).andReturn(mockUser);
    expect(permissionManager.hasPermission(Permissions.USER_PICKER, mockUser)).andReturn(true);
    expect(groupPickerSearchService.findGroups("a")).andStubReturn(matchingGroups);
    expect(authenticationContext.getI18nHelper()).andStubReturn(i18nHelper);
    expect(applicationProperties.getDefaultBackedString(APKeys.JIRA_AJAX_AUTOCOMPLETE_LIMIT))
        .andStubReturn(null);

    GroupPickerResource resource = new GroupPickerResource(groupPickerResourceHelper);

    final List<GroupSuggestionBean> expectedGroups = Lists.newArrayList();
    for (int i = 0; i < GroupPickerResourceHelperImpl.DEFAULT_MAX_RESULTS; ++i) {
      expectedGroups.add(
          new GroupSuggestionBean("a" + String.valueOf(i), "<b>a</b>" + String.valueOf(i)));
    }

    final GroupSuggestionsBean expectedSuggestions =
        new GroupSuggestionsBean(
            GroupPickerResourceHelperImpl.DEFAULT_MAX_RESULTS + 1,
            NoopI18nHelper.makeTranslation(
                GroupPickerResourceHelperImpl.MORE_GROUP_RESULTS_I18N_KEY,
                String.valueOf(GroupPickerResourceHelperImpl.DEFAULT_MAX_RESULTS),
                String.valueOf(GroupPickerResourceHelperImpl.DEFAULT_MAX_RESULTS + 1)),
            expectedGroups);

    replay(
        groupPickerSearchService, authenticationContext, applicationProperties, permissionManager);

    Response response = resource.findGroups("a", null, null);
    assertResponseCacheNever(response);
    assertResponseBody(expectedSuggestions, response);

    verify(groupPickerSearchService, authenticationContext, applicationProperties);
  }
  @Test
  public void testExcludedGroups() {
    for (int i = 1; i < 4; ++i) {
      matchingGroups.add(new MockGroup("a" + String.valueOf(i)));
    }

    final MockUser mockUser = new MockUser("mocky");

    expect(authenticationContext.getLoggedInUser()).andReturn(mockUser);
    expect(permissionManager.hasPermission(Permissions.USER_PICKER, mockUser)).andReturn(true);
    expect(groupPickerSearchService.findGroups("a")).andStubReturn(matchingGroups);
    expect(authenticationContext.getI18nHelper()).andStubReturn(i18nHelper);
    expect(applicationProperties.getDefaultBackedString(APKeys.JIRA_AJAX_AUTOCOMPLETE_LIMIT))
        .andStubReturn("20");

    GroupPickerResource resource = new GroupPickerResource(groupPickerResourceHelper);

    final List<GroupSuggestionBean> expectedGroups = Lists.newArrayList();
    expectedGroups.add(new GroupSuggestionBean("a3", "<b>a</b>3"));

    final GroupSuggestionsBean expectedSuggestions =
        new GroupSuggestionsBean(
            1,
            NoopI18nHelper.makeTranslation(
                GroupPickerResourceHelperImpl.MORE_GROUP_RESULTS_I18N_KEY, 1, 1),
            expectedGroups);

    List<String> excluded = new ArrayList<String>();
    excluded.add("a1");
    excluded.add("a2");

    replay(
        groupPickerSearchService, authenticationContext, applicationProperties, permissionManager);
    Response response = resource.findGroups("a", excluded, null);
    assertResponseBody(expectedSuggestions, response);
  }
 protected boolean isScreenshotAppletEnabledForLinux() {
   return applicationProperties.getOption(APKeys.JIRA_SCREENSHOTAPPLET_LINUX_ENABLED);
 }
 @Override
 public boolean isScreenshotAppletEnabled() {
   return applicationProperties.getOption(APKeys.JIRA_SCREENSHOTAPPLET_ENABLED);
 }
 @Override
 public boolean attachmentsEnabled() {
   boolean allowAttachments = applicationProperties.getOption(APKeys.JIRA_OPTION_ALLOWATTACHMENTS);
   boolean attachmentPathSet = StringUtils.isNotBlank(attachmentPathManager.getAttachmentPath());
   return allowAttachments && attachmentPathSet;
 }
 private boolean attachmentsAllowedAndDirectoryIsSet() {
   String attachmentDir = attachmentPathManager.getAttachmentPath();
   return applicationProperties.getOption(APKeys.JIRA_OPTION_ALLOWATTACHMENTS)
       && StringUtils.isNotBlank(attachmentDir);
 }
 /// CLOVER:OFF
 boolean isExternalUserManagementEnabled() {
   return applicationProperties.getOption(APKeys.JIRA_OPTION_USER_EXTERNALMGT);
 }
 private void setLicenseExtenstionTimestamp(final long timestamp) {
   applicationProperties.setOption(APKeys.JIRA_CONFIRMED_INSTALL_WITH_OLD_LICENSE, true);
   applicationProperties.setString(
       APKeys.JIRA_CONFIRMED_INSTALL_WITH_OLD_LICENSE_TIMESTAMP, String.valueOf(timestamp));
 }
 @Override
 public boolean isFieldVisibleAndInScope(final Issue issue) {
   return applicationProperties.getOption(APKeys.JIRA_OPTION_TIMETRACKING)
       && !fieldVisibilityManager.isFieldHidden(IssueFieldConstants.TIMETRACKING, issue);
 }