@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();
    }
  }
  @Override
  public void handle(Request request, Response response) throws Exception {
    String key = request.mandatoryParam("issue");
    issueService.doTransition(key, request.mandatoryParam("transition"));

    responseWriter.write(key, request, response);
  }
  private static MetricDto newMetricTemplate(Request request) {
    int id = request.mandatoryParamAsInt(PARAM_ID);
    String key = request.param(PARAM_KEY);
    if (key != null) {
      MetricKeyValidator.checkMetricKeyFormat(key);
    }
    String type = request.param(PARAM_TYPE);
    String name = request.param(PARAM_NAME);
    String domain = request.param(PARAM_DOMAIN);
    String description = request.param(PARAM_DESCRIPTION);

    MetricDto metricTemplate = new MetricDto().setId(id);
    if (key != null) {
      metricTemplate.setKey(key);
    }
    if (type != null) {
      metricTemplate.setValueType(type);
    }
    if (name != null) {
      metricTemplate.setShortName(name);
    }
    if (domain != null) {
      metricTemplate.setDomain(domain);
    }
    if (description != null) {
      metricTemplate.setDescription(description);
    }
    return metricTemplate;
  }
  @Override
  public void handle(Request request, Response response) throws Exception {
    DbSession session = dbClient.openSession(false);
    try {
      String profileKey =
          QProfileIdentificationParamUtils.getProfileKeyFromParameters(
              request, profileFactory, session);
      if (dbClient.qualityProfileDao().getByKey(session, profileKey) == null) {
        throw new NotFoundException(
            String.format("Could not find a profile with key '%s'", profileKey));
      }

      QProfileActivityQuery query = new QProfileActivityQuery().setQprofileKey(profileKey);
      Date since = request.paramAsDateTime(PARAM_SINCE);
      if (since != null) {
        query.setSince(since);
      }
      Date to = request.paramAsDateTime(PARAM_TO);
      if (to != null) {
        query.setTo(to);
      }
      SearchOptions options = new SearchOptions();

      int page = request.mandatoryParamAsInt(Param.PAGE);
      options.setPage(page, request.mandatoryParamAsInt(Param.PAGE_SIZE));

      Result<QProfileActivity> result = searchActivities(query, options);
      writeResponse(
          response.newJsonWriter(),
          result,
          Paging.create(options.getLimit(), page, (int) result.getTotal()));
    } finally {
      session.close();
    }
  }
 private static BulkApplyTemplateWsRequest toBulkApplyTemplateWsRequest(Request request) {
   return new BulkApplyTemplateWsRequest()
       .setTemplateId(request.param(PARAM_TEMPLATE_ID))
       .setOrganization(request.param(PARAM_ORGANIZATION_KEY))
       .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
       .setQualifier(request.param(PARAM_QUALIFIER))
       .setQuery(request.param(Param.TEXT_QUERY));
 }
 private OrganizationDto createOrganizationDto(Request request, String name, String key) {
   return new OrganizationDto()
       .setUuid(uuidFactory.create())
       .setName(name)
       .setKey(key)
       .setDescription(request.param(PARAM_DESCRIPTION))
       .setUrl(request.param(PARAM_URL))
       .setAvatarUrl(request.param(PARAM_AVATAR_URL));
 }
  @Override
  public void handle(Request request, Response response) throws Exception {
    String permission = request.mandatoryParam(PARAM_PERMISSION);
    String userLogin = request.mandatoryParam(PARAM_USER_LOGIN);
    permissionService.removePermission(
        new PermissionChange().setPermission(permission).setUser(userLogin));

    response.noContent();
  }
 private static RemoveProjectCreatorFromTemplateWsRequest toWsRequest(Request request) {
   RemoveProjectCreatorFromTemplateWsRequest wsRequest =
       RemoveProjectCreatorFromTemplateWsRequest.builder()
           .setPermission(request.mandatoryParam(PARAM_PERMISSION))
           .setTemplateId(request.param(PARAM_TEMPLATE_ID))
           .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
           .build();
   validateProjectPermission(wsRequest.getPermission());
   return wsRequest;
 }
Exemple #9
0
  private static ActivityWsRequest toSearchWsRequest(Request request) {
    ActivityWsRequest activityWsRequest =
        new ActivityWsRequest()
            .setComponentId(request.param(PARAM_COMPONENT_ID))
            .setQuery(
                defaultString(
                    request.param(Param.TEXT_QUERY), request.param(PARAM_COMPONENT_QUERY)))
            .setStatus(request.paramAsStrings(PARAM_STATUS))
            .setType(request.param(PARAM_TYPE))
            .setMinSubmittedAt(request.param(PARAM_MIN_SUBMITTED_AT))
            .setMaxExecutedAt(request.param(PARAM_MAX_EXECUTED_AT))
            .setOnlyCurrents(request.paramAsBoolean(PARAM_ONLY_CURRENTS))
            .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE));

    checkRequest(
        activityWsRequest.getComponentId() == null || activityWsRequest.getQuery() == null,
        "%s and %s must not be set at the same time",
        PARAM_COMPONENT_ID,
        PARAM_COMPONENT_QUERY);
    checkRequest(
        activityWsRequest.getPageSize() <= MAX_PAGE_SIZE,
        "The '%s' parameter must be less than %d",
        Param.PAGE_SIZE,
        MAX_PAGE_SIZE);

    return activityWsRequest;
  }
  @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();
  }
Exemple #11
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);
    }
  }
 public static void verifyRequest(WebService.Action action, Request request) {
   // verify the HTTP verb
   if (action.isPost() && !"POST".equals(request.method())) {
     throw new ServerException(
         HttpServletResponse.SC_METHOD_NOT_ALLOWED, "HTTP method POST is required");
   }
 }
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkGlobalPermission(UserRole.ADMIN);
    List<String> uuids = request.paramAsStrings(PARAM_IDS);
    List<String> keys = request.paramAsStrings(PARAM_KEYS);

    DbSession dbSession = dbClient.openSession(false);
    try {
      List<ComponentDto> projects = searchProjects(dbSession, uuids, keys);
      componentCleanerService.delete(dbSession, projects);
    } finally {
      MyBatis.closeQuietly(dbSession);
    }

    response.noContent();
  }
 @Override
 public void handle(Request request, Response response) {
   QualityGateDto newQualityGate =
       qualityGates.copy(
           QGatesWs.parseId(request, QGatesWs.PARAM_ID),
           request.mandatoryParam(QGatesWs.PARAM_NAME));
   JsonWriter writer = response.newJsonWriter();
   QGatesWs.writeQualityGate(newQualityGate, writer).close();
 }
 @Override
 public void handle(Request request, Response response) {
   String fileKey = request.mandatoryParam("resource");
   UserSession.get().checkComponentPermission(UserRole.CODEVIEWER, fileKey);
   Integer from = request.mandatoryParamAsInt("from");
   Integer to = request.paramAsInt("to");
   try (DbSession session = dbClient.openSession(false)) {
     ComponentDto componentDto = dbClient.componentDao().getByKey(session, fileKey);
     List<String> lines =
         sourceService.getLinesAsTxt(componentDto.uuid(), from, to == null ? null : to - 1);
     JsonWriter json = response.newJsonWriter().beginArray().beginObject();
     Integer lineCounter = from;
     for (String line : lines) {
       json.prop(lineCounter.toString(), line);
       lineCounter++;
     }
     json.endObject().endArray().close();
   }
 }
  @Override
  public void handle(Request wsRequest, Response wsResponse) throws Exception {
    String name = wsRequest.mandatoryParam(PARAM_TEMPLATE_NAME);
    String description = wsRequest.param(PARAM_TEMPLATE_DESCRIPTION);
    String projectPattern = wsRequest.param(PARAM_TEMPLATE_PATTERN);

    DbSession dbSession = dbClient.openSession(false);
    try {
      checkGlobalAdminUser(userSession);
      validateTemplateNameForCreation(dbSession, name);
      validateProjectPattern(projectPattern);

      PermissionTemplateDto permissionTemplate =
          insertTemplate(dbSession, name, description, projectPattern);

      Permissions.CreatePermissionTemplateResponse response = buildResponse(permissionTemplate);
      writeProtobuf(response, wsRequest, wsResponse);
    } finally {
      dbClient.closeSession(dbSession);
    }
  }
Exemple #17
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);

    String key = request.mandatoryParam(PARAM_KEY);
    preventDeletionOfDefaultOrganization(key, defaultOrganizationProvider.get());

    try (DbSession dbSession = dbClient.openSession(false)) {
      dbClient.organizationDao().deleteByKey(dbSession, key);
      dbSession.commit();

      response.noContent();
    }
  }
  @Override
  public void handle(Request request, Response response) {
    final String ruleKeyParam = request.mandatoryParam("key");
    RuleKey ruleKey = RuleKey.parse(ruleKeyParam);
    Rule rule = findRule(ruleKey);
    if (rule == null) {
      throw new NotFoundException("Rule not found: " + ruleKey);
    }

    JsonWriter json = response.newJsonWriter();
    json.beginObject().name("rule").beginObject();
    writeRule(rule, json);
    writeTags(rule, json);
    json.endObject().endObject().close();
  }
Exemple #19
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkPermission(GlobalPermissions.SYSTEM_ADMIN);

    Part part = request.mandatoryParamAsPart(PARAM_FILE);
    String fileName = part.getFileName();
    checkArgument(fileName.endsWith(".jar"), "Only jar file is allowed");
    InputStream inputStream = part.getInputStream();
    try {
      File destPlugin = new File(downloadDir, fileName);
      Files.copy(inputStream, destPlugin.toPath(), REPLACE_EXISTING);
      response.noContent();
    } finally {
      closeQuietly(inputStream);
    }
  }
Exemple #20
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkLoggedIn();
    List<String> logins = request.mandatoryParamAsStrings(PARAM_LOGINS);

    response.stream().setMediaType(MediaTypes.PROTOBUF);
    ScannerInput.User.Builder userBuilder = ScannerInput.User.newBuilder();
    OutputStream output = response.stream().output();
    try {
      for (Iterator<UserDoc> userDocIterator = userIndex.selectUsersForBatch(logins);
          userDocIterator.hasNext(); ) {
        handleUser(userDocIterator.next(), userBuilder, output);
      }
    } finally {
      output.close();
    }
  }
 @CheckForNull
 private static String getAndCheckKey(Request request) {
   String rqstKey = request.param(PARAM_KEY);
   if (rqstKey != null) {
     checkArgument(
         rqstKey.length() >= KEY_MIN_LENGTH,
         "Key '%s' must be at least %s chars long",
         rqstKey,
         KEY_MIN_LENGTH);
     checkArgument(
         rqstKey.length() <= KEY_MAX_LENGTH,
         "Key '%s' must be at most %s chars long",
         rqstKey,
         KEY_MAX_LENGTH);
     checkArgument(
         slugify(rqstKey).equals(rqstKey), "Key '%s' contains at least one invalid char", rqstKey);
   }
   return rqstKey;
 }
Exemple #22
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkLoggedIn().checkPermission(GlobalPermissions.SYSTEM_ADMIN);
    int id = request.mandatoryParamAsInt(PARAM_ID);

    DbSession dbSession = dbClient.openSession(false);
    try {
      MetricDto metricTemplate = newMetricTemplate(request);
      MetricDto metricInDb = dbClient.metricDao().selectById(dbSession, id);
      checkMetricInDbAndTemplate(dbSession, metricInDb, metricTemplate);

      updateMetricInDb(dbSession, metricInDb, metricTemplate);
      JsonWriter json = response.newJsonWriter();
      writeMetric(json, metricInDb);
      json.close();
      rubyBridge.metricCache().invalidate();
    } finally {
      MyBatis.closeQuietly(dbSession);
    }
  }
  @Override
  public void handle(Request request, Response response) throws Exception {
    userSession.checkPermission(GlobalPermissions.PREVIEW_EXECUTION);
    final String moduleKey = request.mandatoryParam(PARAM_KEY);

    response.stream().setMediaType(MediaTypes.PROTOBUF);
    DbSession session = dbClient.openSession(false);
    try {
      ComponentDto component = componentFinder.getByKey(session, moduleKey);
      Map<String, String> keysByUUid = keysByUUid(session, component);

      BatchInput.ServerIssue.Builder issueBuilder = BatchInput.ServerIssue.newBuilder();
      for (Iterator<IssueDoc> issueDocIterator = issueIndex.selectIssuesForBatch(component);
          issueDocIterator.hasNext(); ) {
        handleIssue(issueDocIterator.next(), issueBuilder, keysByUUid, response.stream().output());
      }
    } finally {
      MyBatis.closeQuietly(session);
    }
  }
Exemple #24
0
  @Override
  public void handle(Request request, Response response) {
    String issueKey = request.requiredParam("key");
    IssueQueryResult queryResult =
        issueFinder.find(IssueQuery.builder().issueKeys(Arrays.asList(issueKey)).build());
    if (queryResult.issues().size() != 1) {
      throw new NotFoundException("Issue not found: " + issueKey);
    }
    DefaultIssue issue = (DefaultIssue) queryResult.first();

    JsonWriter json = response.newJsonWriter();
    json.beginObject().name("issue").beginObject();

    writeIssue(queryResult, issue, json);
    writeTransitions(issue, json);
    writeActions(issue, json);
    writeComments(queryResult, issue, json);
    writeChangelog(issue, json);

    json.endObject().endObject().close();
  }
Exemple #25
0
  @Override
  public void handle(Request request, Response response) {
    String componentUuid = request.mandatoryParam(PARAM_UUID);

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

    DbSession session = dbClient.openSession(false);
    try {
      ComponentDto component = componentFinder.getByUuid(session, componentUuid);
      userSession.checkComponentPermission(UserRole.USER, component.getKey());

      Map<String, MeasureDto> measuresByMetricKey = measuresByMetricKey(component, session);
      appendComponent(json, component, userSession, session);
      appendPermissions(json, component, userSession);
      appendMeasures(json, measuresByMetricKey);

    } finally {
      MyBatis.closeQuietly(session);
    }

    json.endObject();
    json.close();
  }
Exemple #26
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    DbSession dbSession = dbClient.openSession(false);
    try {
      Integer userId = userSession.getUserId();
      DashboardDto dashboard =
          dbClient
              .dashboardDao()
              .selectAllowedByKey(
                  dbSession,
                  request.mandatoryParamAsLong(PARAM_KEY),
                  userId != null ? userId.longValue() : null);
      if (dashboard == null) {
        throw new NotFoundException();
      }

      JsonWriter json = response.newJsonWriter();
      json.beginObject();
      json.prop("key", dashboard.getKey());
      json.prop("name", dashboard.getName());
      json.prop("layout", dashboard.getColumnLayout());
      json.prop("desc", dashboard.getDescription());
      json.prop("global", dashboard.getGlobal());
      json.prop("shared", dashboard.getShared());
      if (dashboard.getUserId() != null) {
        UserDto user = dbClient.userDao().selectUserById(dashboard.getUserId());
        if (user != null) {
          json.name("owner").beginObject();
          // TODO to be shared and extracted from here
          json.prop("login", user.getLogin());
          json.prop("name", user.getName());
          json.endObject();
        }
      }
      // load widgets and related properties
      json.name("widgets").beginArray();
      Collection<WidgetDto> widgets =
          dbClient.widgetDao().findByDashboard(dbSession, dashboard.getKey());
      ListMultimap<Long, WidgetPropertyDto> propertiesByWidget =
          WidgetPropertyDto.groupByWidgetId(
              dbClient.widgetPropertyDao().selectByDashboard(dbSession, dashboard.getKey()));
      for (WidgetDto widget : widgets) {
        json.beginObject();
        json.prop("id", widget.getId());
        json.prop("key", widget.getWidgetKey());
        json.prop("name", widget.getName());
        json.prop("desc", widget.getDescription());
        json.prop("col", widget.getColumnIndex());
        json.prop("row", widget.getRowIndex());
        json.prop("configured", widget.getConfigured());
        json.prop("componentId", widget.getResourceId());
        json.name("props").beginArray();
        for (WidgetPropertyDto prop : propertiesByWidget.get(widget.getId())) {
          json.beginObject();
          json.prop("key", prop.getPropertyKey());
          json.prop("val", prop.getTextValue());
          json.endObject();
        }
        json.endArray().endObject();
      }

      json.endArray();
      json.endObject();
      json.close();
    } finally {
      dbSession.close();
    }
  }