private void checkPermissions(ComponentDto baseComponent) {
   String projectUuid = firstNonNull(baseComponent.projectUuid(), baseComponent.uuid());
   if (!userSession.hasComponentUuidPermission(UserRole.ADMIN, projectUuid)
       && !userSession.hasComponentUuidPermission(UserRole.USER, projectUuid)) {
     throw insufficientPrivilegesException();
   }
 }
Example #2
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    if (settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE)) {
      userSession.checkLoggedIn();
    } else {
      userSession.checkIsRoot();
    }

    String name = wsSupport.getAndCheckMandatoryName(request);
    String requestKey = getAndCheckKey(request);
    String key = useOrGenerateKey(requestKey, name);
    wsSupport.getAndCheckDescription(request);
    wsSupport.getAndCheckUrl(request);
    wsSupport.getAndCheckAvatar(request);

    try (DbSession dbSession = dbClient.openSession(false)) {
      checkKeyIsNotUsed(dbSession, key, requestKey, name);

      OrganizationDto dto = createOrganizationDto(request, name, key);
      dbClient.organizationDao().insert(dbSession, dto);
      GroupDto group = createOwnersGroup(dbSession, dto);
      addCurrentUserToGroup(dbSession, group);
      dbSession.commit();

      writeResponse(request, response, dto);
    }
  }
Example #3
0
 private String formatMeasure(@Nullable MeasureDto measure, Metric metric) {
   if (measure == null) {
     return null;
   }
   Metric.ValueType metricType = metric.getType();
   Double value = getDoubleValue(measure, metric);
   String data = measure.getData();
   if (value != null) {
     switch (metricType) {
       case FLOAT:
         return i18n.formatDouble(userSession.locale(), value);
       case INT:
         return i18n.formatInteger(userSession.locale(), value.intValue());
       case PERCENT:
         return i18n.formatDouble(userSession.locale(), value) + "%";
       case WORK_DUR:
         return durations.format(
             userSession.locale(),
             durations.create(value.longValue()),
             Durations.DurationFormat.SHORT);
     }
   }
   if ((metricType.equals(Metric.ValueType.STRING) || metricType.equals(Metric.ValueType.RATING))
       && data != null) {
     return data;
   }
   return null;
 }
Example #4
0
 private void writeTransitions(Issue issue, JsonWriter json) {
   json.name("transitions").beginArray();
   if (UserSession.get().isLoggedIn()) {
     List<Transition> transitions = issueService.listTransitions(issue, UserSession.get());
     for (Transition transition : transitions) {
       json.value(transition.key());
     }
   }
   json.endArray();
 }
Example #5
0
  public DefaultIssue createManualIssue(
      String componentKey,
      RuleKey ruleKey,
      @Nullable Integer line,
      @Nullable String message,
      @Nullable String severity) {
    verifyLoggedIn();

    DbSession dbSession = dbClient.openSession(false);
    try {
      Optional<ComponentDto> componentOptional =
          dbClient.componentDao().selectByKey(dbSession, componentKey);
      if (!componentOptional.isPresent()) {
        throw new BadRequestException(
            String.format("Component with key '%s' not found", componentKey));
      }
      ComponentDto component = componentOptional.get();
      ComponentDto project =
          dbClient.componentDao().selectOrFailByUuid(dbSession, component.projectUuid());

      userSession.checkComponentPermission(UserRole.USER, project.getKey());
      if (!ruleKey.isManual()) {
        throw new IllegalArgumentException(
            "Issues can be created only on rules marked as 'manual': " + ruleKey);
      }
      Rule rule = getNullableRuleByKey(ruleKey);
      if (rule == null) {
        throw new IllegalArgumentException("Unknown rule: " + ruleKey);
      }

      DefaultIssue issue =
          new DefaultIssueBuilder()
              .componentKey(component.getKey())
              .projectKey(project.getKey())
              .line(line)
              .message(!Strings.isNullOrEmpty(message) ? message : rule.getName())
              .severity(Objects.firstNonNull(severity, Severity.MAJOR))
              .ruleKey(ruleKey)
              .reporter(userSession.getLogin())
              .assignee(findSourceLineUser(dbSession, component.uuid(), line))
              .build();

      Date now = new Date();
      issue.setCreationDate(now);
      issue.setUpdateDate(now);
      issueStorage.save(issue);
      return issue;
    } finally {
      dbSession.close();
    }
  }
  @Override
  public void handle(Request request, Response response) {
    String query = request.mandatoryParam(Param.TEXT_QUERY);
    if (query.length() < MINIMUM_SEARCH_CHARACTERS) {
      throw new IllegalArgumentException(
          String.format("Minimum search is %s characters", MINIMUM_SEARCH_CHARACTERS));
    }
    String componentUuid = request.mandatoryParam(PARAM_COMPONENT_UUID);

    JsonWriter json = response.newJsonWriter();
    json.beginObject();

    DbSession session = dbClient.openSession(false);
    try {
      ComponentDto componentDto = componentFinder.getByUuid(session, componentUuid);
      userSession.checkProjectUuidPermission(UserRole.USER, componentDto.projectUuid());

      Set<Long> projectIds =
          newLinkedHashSet(
              dbClient
                  .componentIndexDao()
                  .selectProjectIdsFromQueryAndViewOrSubViewUuid(
                      session, query, componentDto.uuid()));
      Collection<Long> authorizedProjectIds =
          dbClient
              .authorizationDao()
              .keepAuthorizedProjectIds(
                  session, projectIds, userSession.getUserId(), UserRole.USER);

      SearchOptions options = new SearchOptions();
      options.setPage(request.mandatoryParamAsInt(PAGE), request.mandatoryParamAsInt(PAGE_SIZE));
      Set<Long> pagedProjectIds = pagedProjectIds(authorizedProjectIds, options);

      List<ComponentDto> projects = dbClient.componentDao().selectByIds(session, pagedProjectIds);

      options.writeJson(json, authorizedProjectIds.size());
      json.name("components").beginArray();
      for (ComponentDto project : projects) {
        json.beginObject();
        json.prop("uuid", project.uuid());
        json.prop("name", project.name());
        json.endObject();
      }
      json.endArray();
    } finally {
      MyBatis.closeQuietly(session);
    }

    json.endObject();
    json.close();
  }
Example #7
0
  public Issue plan(String issueKey, @Nullable String actionPlanKey) {
    verifyLoggedIn();

    DbSession session = dbClient.openSession(false);
    try {
      ActionPlan actionPlan = null;
      if (!Strings.isNullOrEmpty(actionPlanKey)) {
        actionPlan = actionPlanService.findByKey(actionPlanKey, userSession);
        if (actionPlan == null) {
          throw new BadRequestException("Unknown action plan: " + actionPlanKey);
        }
      }
      DefaultIssue issue = getByKeyForUpdate(session, issueKey).toDefaultIssue();

      IssueChangeContext context =
          IssueChangeContext.createUser(new Date(), userSession.getLogin());
      if (issueUpdater.plan(issue, actionPlan, context)) {
        saveIssue(session, issue, context, null);
      }
      return issue;

    } finally {
      session.close();
    }
  }
Example #8
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkLoggedIn().checkPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);

    String name = request.mandatoryParam(PARAM_PROFILE_NAME);
    String language = request.mandatoryParam(PARAM_LANGUAGE);

    DbSession dbSession = dbClient.openSession(false);

    try {
      QProfileResult result = new QProfileResult();
      QualityProfileDto profile =
          profileFactory.create(dbSession, QProfileName.createFor(language, name));
      result.setProfile(profile);
      for (ProfileImporter importer : importers) {
        InputStream contentToImport =
            request.paramAsInputStream(getBackupParamName(importer.getKey()));
        if (contentToImport != null) {
          result.add(exporters.importXml(profile, importer.getKey(), contentToImport, dbSession));
        }
      }
      dbSession.commit();

      response.stream().setMediaType(request.getMediaType());
      JsonWriter jsonWriter =
          JsonWriter.of(new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8));
      writeResult(jsonWriter, result);
    } finally {
      dbSession.close();
    }
  }
Example #9
0
  @Override
  public void handle(Request wsRequest, Response wsResponse) throws Exception {
    userSession.checkAnyGlobalPermissions(AUTHORIZED_PERMISSIONS);

    String taskUuid = wsRequest.mandatoryParam(PARAM_TASK_UUID);
    DbSession dbSession = dbClient.openSession(false);
    try {
      WsCe.TaskResponse.Builder wsTaskResponse = WsCe.TaskResponse.newBuilder();
      Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskUuid);
      if (queueDto.isPresent()) {
        wsTaskResponse.setTask(wsTaskFormatter.formatQueue(dbSession, queueDto.get()));
      } else {
        Optional<CeActivityDto> activityDto =
            dbClient.ceActivityDao().selectByUuid(dbSession, taskUuid);
        if (activityDto.isPresent()) {
          wsTaskResponse.setTask(wsTaskFormatter.formatActivity(dbSession, activityDto.get()));
        } else {
          throw new NotFoundException();
        }
      }
      writeProtobuf(wsTaskResponse.build(), wsRequest, wsResponse);

    } finally {
      dbClient.closeSession(dbSession);
    }
  }
Example #10
0
  private void appendComponent(
      JsonWriter json, ComponentDto component, UserSession userSession, DbSession session) {
    List<PropertyDto> propertyDtos =
        dbClient
            .propertiesDao()
            .selectByQuery(
                PropertyQuery.builder()
                    .setKey("favourite")
                    .setComponentId(component.getId())
                    .setUserId(userSession.getUserId())
                    .build(),
                session);
    boolean isFavourite = propertyDtos.size() == 1;

    json.prop("key", component.key());
    json.prop("uuid", component.uuid());
    json.prop("path", component.path());
    json.prop("name", component.name());
    json.prop("longName", component.longName());
    json.prop("q", component.qualifier());

    ComponentDto parentProject = retrieveRootIfNotCurrentComponent(component, session);
    ComponentDto project =
        dbClient.componentDao().selectOrFailByUuid(session, component.projectUuid());

    // Do not display parent project if parent project and project are the same
    boolean displayParentProject =
        parentProject != null && !parentProject.uuid().equals(project.uuid());
    json.prop("subProject", displayParentProject ? parentProject.key() : null);
    json.prop("subProjectName", displayParentProject ? parentProject.longName() : null);
    json.prop("project", project.key());
    json.prop("projectName", project.longName());

    json.prop("fav", isFavourite);
  }
 public Result<ActionPlan> deleteActionPlan(String actionPlanKey) {
   Result<ActionPlan> result = createResultForExistingActionPlan(actionPlanKey);
   if (result.ok()) {
     actionPlanService.delete(actionPlanKey, UserSession.get());
   }
   return result;
 }
 public Result<ActionPlan> createActionPlan(Map<String, String> parameters) {
   Result<ActionPlan> result = createActionPlanResult(parameters);
   if (result.ok()) {
     result.set(actionPlanService.create(result.get(), UserSession.get()));
   }
   return result;
 }
 /** Execute issue filter from existing filter with optional overridable parameters */
 public IssueFilterResult execute(Long issueFilterId, Map<String, Object> overrideProps) {
   DefaultIssueFilter issueFilter = issueFilterService.find(issueFilterId, UserSession.get());
   Map<String, Object> props = issueFilterService.deserializeIssueFilterQuery(issueFilter);
   overrideProps(props, overrideProps);
   IssueQuery issueQuery = PublicRubyIssueService.toQuery(props);
   return issueFilterService.execute(issueQuery);
 }
  /** Create manual issue */
  public Result<DefaultIssue> create(Map<String, String> params) {
    Result<DefaultIssue> result = Result.of();
    try {
      // mandatory parameters
      String componentKey = params.get("component");
      if (StringUtils.isBlank(componentKey)) {
        result.addError("Component is not set");
      }
      RuleKey ruleKey = null;
      String rule = params.get("rule");
      if (StringUtils.isBlank(rule)) {
        result.addError(Result.Message.ofL10n("issue.manual.missing_rule"));
      } else {
        ruleKey = RuleKey.parse(rule);
      }

      if (result.ok()) {
        DefaultIssue issue =
            issueService.createManualIssue(
                componentKey,
                ruleKey,
                RubyUtils.toInteger(params.get("line")),
                params.get("message"),
                params.get("severity"),
                RubyUtils.toDouble(params.get("effortToFix")),
                UserSession.get());
        result.set(issue);
      }

    } catch (Exception e) {
      result.addError(e.getMessage());
    }
    return result;
  }
Example #15
0
 @CheckForNull
 private String formatAgeDate(@Nullable Date date) {
   if (date != null) {
     return i18n.ageFromNow(UserSession.get().locale(), date);
   }
   return null;
 }
Example #16
0
  private void writeChangelog(Issue issue, JsonWriter json) {
    json.name("changelog")
        .beginArray()
        .beginObject()
        .prop("creationDate", DateUtils.formatDateTime(issue.creationDate()))
        .prop("fCreationDate", formatDate(issue.creationDate()))
        .name("diffs")
        .beginArray()
        .value(i18n.message(UserSession.get().locale(), "created", null))
        .endArray()
        .endObject();

    IssueChangelog changelog = issueChangelogService.changelog(issue);
    for (FieldDiffs diffs : changelog.changes()) {
      String userLogin = diffs.userLogin();
      json.beginObject()
          .prop("userName", userLogin != null ? changelog.user(diffs).name() : null)
          .prop("creationDate", DateUtils.formatDateTime(diffs.creationDate()))
          .prop("fCreationDate", formatDate(diffs.creationDate()));
      json.name("diffs").beginArray();
      List<String> diffsFormatted = issueChangelogService.formatDiffs(diffs);
      for (String diff : diffsFormatted) {
        json.value(diff);
      }
      json.endArray();
      json.endObject();
    }
    json.endArray();
  }
 public Result<ActionPlan> openActionPlan(String actionPlanKey) {
   Result<ActionPlan> result = createResultForExistingActionPlan(actionPlanKey);
   if (result.ok()) {
     result.set(
         actionPlanService.setStatus(actionPlanKey, ActionPlan.STATUS_OPEN, UserSession.get()));
   }
   return result;
 }
Example #18
0
 /**
  * Never return null, but an empty list if the issue does not exist. No security check is done
  * since it should already have been done to get the issue
  */
 public List<Transition> listTransitions(@Nullable Issue issue) {
   if (issue == null) {
     return Collections.emptyList();
   }
   List<Transition> outTransitions = workflow.outTransitions(issue);
   List<Transition> allowedTransitions = new ArrayList<>();
   for (Transition transition : outTransitions) {
     String projectUuid = issue.projectUuid();
     if (userSession.isLoggedIn() && StringUtils.isBlank(transition.requiredProjectPermission())
         || (projectUuid != null
             && userSession.hasComponentUuidPermission(
                 transition.requiredProjectPermission(), projectUuid))) {
       allowedTransitions.add(transition);
     }
   }
   return allowedTransitions;
 }
Example #19
0
 @Test
 public void should_support_only_issues_with_issue_admin_permission() {
   when(userSessionMock.hasProjectPermission(UserRole.ISSUE_ADMIN, "foo:bar")).thenReturn(true);
   assertThat(action.supports(new DefaultIssue().setProjectKey("foo:bar").setResolution(null)))
       .isTrue();
   assertThat(action.supports(new DefaultIssue().setProjectKey("foo:bar2").setResolution(null)))
       .isFalse();
 }
 public Result<Issue> doTransition(String issueKey, String transitionKey) {
   Result<Issue> result = Result.of();
   try {
     result.set(issueService.doTransition(issueKey, transitionKey, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
 public Result<Issue> executeAction(String issueKey, String actionKey) {
   Result<Issue> result = Result.of();
   try {
     result.set(actionService.execute(issueKey, actionKey, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
 public Result<IssueComment> editComment(String commentKey, String newText) {
   Result<IssueComment> result = Result.of();
   try {
     result.set(commentService.editComment(commentKey, newText, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
 public Result<IssueComment> addComment(String issueKey, String text) {
   Result<IssueComment> result = Result.of();
   try {
     result.set(commentService.addComment(issueKey, text, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
 public Result<Issue> plan(String issueKey, @Nullable String actionPlanKey) {
   Result<Issue> result = Result.of();
   try {
     result.set(issueService.plan(issueKey, actionPlanKey, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
 public Result<Issue> setSeverity(String issueKey, String severity) {
   Result<Issue> result = Result.of();
   try {
     result.set(issueService.setSeverity(issueKey, severity, UserSession.get()));
   } catch (Exception e) {
     result.addError(e.getMessage());
   }
   return result;
 }
Example #26
0
  public Issue setSeverity(String issueKey, String severity) {
    verifyLoggedIn();

    DbSession session = dbClient.openSession(false);
    try {
      DefaultIssue issue = getByKeyForUpdate(session, issueKey).toDefaultIssue();
      userSession.checkComponentPermission(UserRole.ISSUE_ADMIN, issue.projectKey());

      IssueChangeContext context =
          IssueChangeContext.createUser(new Date(), userSession.getLogin());
      if (issueUpdater.setManualSeverity(issue, severity, context)) {
        saveIssue(session, issue, context, null);
      }
      return issue;
    } finally {
      session.close();
    }
  }
 public void writeTransitions(Issue issue, JsonWriter json) {
   json.name("transitions").beginArray();
   if (userSession.isLoggedIn()) {
     for (Transition transition : issueService.listTransitions(issue)) {
       json.value(transition.key());
     }
   }
   json.endArray();
 }
Example #28
0
 private void addCurrentUserToGroup(DbSession dbSession, GroupDto group) {
   dbClient
       .userGroupDao()
       .insert(
           dbSession,
           new UserGroupDto()
               .setGroupId(group.getId())
               .setUserId(userSession.getUserId().longValue()));
 }
Example #29
0
 private void checkPermissions(CeTaskQuery query) {
   List<String> componentUuids = query.getComponentUuids();
   if (componentUuids != null && componentUuids.size() == 1) {
     if (!isAllowedOnComponentUuid(userSession, componentUuids.get(0))) {
       throw new ForbiddenException("Requires administration permission");
     }
   } else {
     userSession.checkPermission(UserRole.ADMIN);
   }
 }
 public boolean isUserAuthorized(DefaultIssueFilter issueFilter) {
   try {
     UserSession userSession = UserSession.get();
     String user = issueFilterService.getLoggedLogin(userSession);
     issueFilterService.verifyCurrentUserCanReadFilter(issueFilter, user);
     return true;
   } catch (Exception e) {
     return false;
   }
 }