类javax.ws.rs.core.Response.Status源码实例Demo

下面列出了怎么用javax.ws.rs.core.Response.Status的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: zeppelin   文件: NotebookRestApi.java
@PUT
@Path("{noteId}/paragraph/{paragraphId}/config")
@ZeppelinApi
public Response updateParagraphConfig(@PathParam("noteId") String noteId,
                                      @PathParam("paragraphId") String paragraphId,
                                      String message) throws IOException {
  String user = authenticationService.getPrincipal();
  LOG.info("{} will update paragraph config {} {}", user, noteId, paragraphId);

  Note note = notebook.getNote(noteId);
  checkIfNoteIsNotNull(note);
  checkIfUserCanWrite(noteId, "Insufficient privileges you cannot update this paragraph config");
  Paragraph p = note.getParagraph(paragraphId);
  checkIfParagraphIsNotNull(p);

  Map<String, Object> newConfig = gson.fromJson(message, HashMap.class);
  configureParagraph(p, newConfig, user);
  AuthenticationInfo subject = new AuthenticationInfo(user);
  notebook.saveNote(note, subject);
  return new JsonResponse<>(Status.OK, "", p).build();
}
 
/**
 * Create this by providing json payload as follows:
 *
 *    curl -H "Content-Type: application/json" -X POST -d <payload> <url>
 *    Eg: curl -H "Content-Type: application/json" -X POST -d
 *            '{"datasetName":"xyz","metricName":"xyz", "dataSource":"PinotThirdeyeDataSource", "properties": { "prop1":"1", "prop2":"2"}}'
 *                http://localhost:8080/onboard/create
 * @param payload
 */
@POST
@Path("/create")
public Response createOnboardConfig(String payload) {
  OnboardDatasetMetricDTO onboardConfig = null;
  Response response = null;
  try {
    onboardConfig = OBJECT_MAPPER.readValue(payload, OnboardDatasetMetricDTO.class);
    Long id = onboardDatasetMetricDAO.save(onboardConfig);
    response = Response.status(Status.OK).entity(String.format("Created config with id %d", id)).build();
  } catch (Exception e) {
    response = Response.status(Status.INTERNAL_SERVER_ERROR)
        .entity(String.format("Invalid payload %s %s",  payload, e)).build();
  }
  return response;
}
 
@Test
@Category(UnitTest.class)
public void testGetTileMapMercator() throws Exception
{
  String version = "1.0.0";

  when(request.getRequestURL())
      .thenReturn(new StringBuffer("http://localhost:9998/tms/1.0.0/" +
          rgbsmall_nopyramids_abs + "/global-mercator"));
  when(service.getMetadata(rgbsmall_nopyramids_abs))
      .thenReturn(getMetadata(rgbsmall_nopyramids_abs));

  Response response = target("tms" + "/" + version + "/" +
      URLEncoder.encode(rgbsmall_nopyramids_abs, "UTF-8") + "/global-mercator")
      .request().get();

  Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());

  verify(request, times(1)).getRequestURL();
  verify(service, times(1)).getMetadata(rgbsmall_nopyramids_abs);
  verify(service, times(0));
  service.listImages();
  verifyNoMoreInteractions(request, service);
}
 
@Test
public void testProcessInstantiationWithCaseInstanceId() throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put("caseInstanceId", "myCaseInstanceId");

  given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)
    .contentType(POST_JSON_CONTENT_TYPE).body(json)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
      .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID))
    .when().post(START_PROCESS_INSTANCE_URL);

  verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID));
  verify(mockInstantiationBuilder).caseInstanceId("myCaseInstanceId");
  verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean());
}
 
源代码5 项目: pulsar   文件: NamespacesTest.java
@Test
public void testSplitBundleWithUnDividedRange() throws Exception {
    URL localWebServiceUrl = new URL(pulsar.getSafeWebServiceAddress());
    String bundledNsLocal = "test-bundled-namespace-1";
    BundlesData bundleData = new BundlesData(
            Lists.newArrayList("0x00000000", "0x08375b1a", "0x08375b1b", "0xffffffff"));
    createBundledTestNamespaces(this.testTenant, this.testLocalCluster, bundledNsLocal, bundleData);
    final NamespaceName testNs = NamespaceName.get(this.testTenant, this.testLocalCluster, bundledNsLocal);

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    doReturn(CompletableFuture.completedFuture(null)).when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    mockWebUrl(localWebServiceUrl, testNs);

    // split bundles
    try {
        namespaces.splitNamespaceBundle(testTenant, testLocalCluster, bundledNsLocal, "0x08375b1a_0x08375b1b",
                false, false);
    } catch (RestException re) {
        assertEquals(re.getResponse().getStatus(), Status.PRECONDITION_FAILED.getStatusCode());
    }
}
 
源代码6 项目: sailfish-core   文件: MachineLearningResourceV2.java
@GET
@Path("/{token}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response tokenGet(@QueryParam("testCaseId") Integer testCaseId, @PathParam("token") String token) {
    try {
        HttpSession session = httpRequest.getSession();
        String sessionKey = token;

        SessionStorage sessionStorage = (SessionStorage)session.getAttribute(sessionKey);

        if (sessionStorage == null) {
            return Response.status(Status.UNAUTHORIZED).build();
        }

        ReportMLResponse response = new ReportMLResponse();
        response.setPredictions(sessionStorage.getPredictions(testCaseId));
        response.setUserMarks(sessionStorage.getCheckedMessages());
        response.setToken(token);

        return Response.ok().entity(response).build();
    } catch (Exception ex) {
        logger.error("unable to generate a response with ml data", ex);
        return Response.serverError().entity("server error: " + ex.toString()).build();
    }
}
 
public HistoricDecisionInstanceDto getHistoricDecisionInstance(Boolean includeInputs, Boolean includeOutputs, Boolean disableBinaryFetching, Boolean disableCustomObjectDeserialization) {
  HistoryService historyService = engine.getHistoryService();

  HistoricDecisionInstanceQuery query = historyService.createHistoricDecisionInstanceQuery().decisionInstanceId(decisionInstanceId);
  if (includeInputs != null && includeInputs) {
    query.includeInputs();
  }
  if (includeOutputs != null && includeOutputs) {
    query.includeOutputs();
  }
  if (disableBinaryFetching != null && disableBinaryFetching) {
    query.disableBinaryFetching();
  }
  if (disableCustomObjectDeserialization != null && disableCustomObjectDeserialization) {
    query.disableCustomObjectDeserialization();
  }

  HistoricDecisionInstance instance = query.singleResult();

  if (instance == null) {
    throw new InvalidRequestException(Status.NOT_FOUND, "Historic decision instance with id '" + decisionInstanceId + "' does not exist");
  }

  return HistoricDecisionInstanceDto.fromHistoricDecisionInstance(instance);
}
 
源代码8 项目: hawkular-metrics   文件: TenantFilter.java
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    UriInfo uriInfo = requestContext.getUriInfo();
    String path = uriInfo.getPath();

    if (path.startsWith("/tenants") || path.startsWith(StatusHandler.PATH) || path.equals(BaseHandler.PATH)) {
        // Some handlers do not check the tenant header
        return;
    }

    String tenant = requestContext.getHeaders().getFirst(TENANT_HEADER_NAME);
    if (tenant != null && !tenant.trim().isEmpty()) {
        // We're good already
        return;
    }
    // Fail on missing tenant info
    Response response = Response.status(Status.BAD_REQUEST)
                                .type(APPLICATION_JSON_TYPE)
                                .entity(new ApiError(MISSING_TENANT_MSG))
                                .build();
    requestContext.abortWith(response);
}
 
@Override
public boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId) {
  Holder<HttpClientResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  CountDownLatch countDownLatch = new CountDownLatch(1);
  restClientUtil.delete(ipPort,
      String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_OPERATION_ONE, microserviceId, microserviceInstanceId),
      new RequestParam(),
      syncHandler(countDownLatch, HttpClientResponse.class, holder));
  try {
    countDownLatch.await();
    if (holder.value != null) {
      if (holder.value.statusCode() == Status.OK.getStatusCode()) {
        return true;
      }
      LOGGER.warn(holder.value.statusMessage());
    }
  } catch (Exception e) {
    LOGGER.error("unregister microservice instance {}/{} failed",
        microserviceId,
        microserviceInstanceId,
        e);
  }
  return false;
}
 
@Test
public void testSuspendProcessDefinitionExcludingInstances() {
  Map<String, Object> params = new HashMap<String, Object>();
  params.put("suspended", true);
  params.put("includeProcessInstances", false);

  given()
    .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)
    .contentType(ContentType.JSON)
    .body(params)
  .then()
    .expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL);

  verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null);
}
 
@Test
public void testActivateJobDefinitionByProcessDefinitionKeyIncludingInstaces() {
  Map<String, Object> params = new HashMap<String, Object>();
  params.put("suspended", false);
  params.put("includeJobs", true);
  params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

  given()
    .contentType(ContentType.JSON)
    .body(params)
  .then()
    .expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .put(JOB_DEFINITION_SUSPENDED_URL);

  verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
  verify(mockSuspensionStateBuilder).includeJobs(true);
  verify(mockSuspensionStateBuilder).activate();
}
 
@Test
public void testGetRenderedFormForDifferentPlatformEncoding() throws NoSuchFieldException, IllegalAccessException, UnsupportedEncodingException {
  String expectedResult = "<formField>unicode symbol: \u2200</formField>";
  when(formServiceMock.getRenderedTaskForm(MockProvider.EXAMPLE_TASK_ID)).thenReturn(expectedResult);

  Response response = given()
      .pathParam("id", EXAMPLE_TASK_ID)
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
          .contentType(XHTML_XML_CONTENT_TYPE)
      .when()
        .get(RENDERED_FORM_URL);

  String responseContent = new String(response.asByteArray(), EncodingUtil.DEFAULT_ENCODING);
  Assertions.assertThat(responseContent).isEqualTo(expectedResult);
}
 
@Test
public void testCaseInstanceVariableValuesEqualsIgnoreCase() {
  String variableName = "varName";
  String variableValue = "varValue";
  String queryValue = variableName + "_eq_" + variableValue;
  
  given()
  .queryParam("caseInstanceVariables", queryValue)
  .queryParam("variableValuesIgnoreCase", true)
  .then()
  .expect()
  .statusCode(Status.OK.getStatusCode())
  .when()
  .get(CASE_EXECUTION_QUERY_URL);
  
  verify(mockedQuery).matchVariableValuesIgnoreCase();
  verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue);
}
 
源代码14 项目: pulsar   文件: PersistentTopicsBase.java
protected void internalCreateNonPartitionedTopic(boolean authoritative) {
    validateWriteOperationOnTopic(authoritative);
    validateNonPartitionTopicName(topicName.getLocalName());
    if (topicName.isGlobal()) {
        validateGlobalNamespaceOwnership(namespaceName);
    }

    validateTopicOwnership(topicName, authoritative);

    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative, false);
    if (partitionMetadata.partitions > 0) {
        log.warn("[{}] Partitioned topic with the same name already exists {}", clientAppId(), topicName);
        throw new RestException(Status.CONFLICT, "This topic already exists");
    }

    try {
        Topic createdTopic = getOrCreateTopic(topicName);
        log.info("[{}] Successfully created non-partitioned topic {}", clientAppId(), createdTopic);
    } catch (Exception e) {
        log.error("[{}] Failed to create non-partitioned topic {}", clientAppId(), topicName, e);
        throw new RestException(e);
    }
}
 
@Test
public void testBatchQueryByBatchId() {
  Response response = given()
      .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
    .get(BATCH_STATISTICS_URL);

  InOrder inOrder = inOrder(queryMock);
  inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID);
  inOrder.verify(queryMock).list();
  inOrder.verifyNoMoreInteractions();

  verifyBatchStatisticsListJson(response.asString());
}
 
源代码16 项目: TeaStore   文件: CacheManagerEndpoint.java
/**
 * Clears the cache for the class.
 * @param className fully qualified class name.
 * @return Status Code 200 and cleared class name if clear succeeded, 404 if it didn't.
 */
@DELETE
@Path("/class/{class}")
public Response clearClassCache(@PathParam("class") final String className) {
	boolean classfound = true;
	try {
		Class<?> entityClass = Class.forName(className);
		CacheManager.MANAGER.clearLocalCacheOnly(entityClass);
	} catch (Exception e) {
		classfound = false;
	}
	if (classfound) {
		return Response.ok(className).build();
	}
	return Response.status(Status.NOT_FOUND).build();
}
 
源代码17 项目: monolith   文件: PerformanceEndpoint.java
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<Performance> findByIdQuery = em.createQuery("SELECT DISTINCT p FROM Performance p LEFT JOIN FETCH p.show WHERE p.id = :entityId ORDER BY p.id", Performance.class);
   findByIdQuery.setParameter("entityId", id);
   Performance entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   PerformanceDTO dto = new PerformanceDTO(entity);
   return Response.ok(dto).build();
}
 
@Test
public void testBatchQueryByBatchId() {
  Response response = given()
    .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID)
  .then().expect()
    .statusCode(Status.OK.getStatusCode())
  .when()
    .get(BATCH_RESOURCE_URL);

  InOrder inOrder = inOrder(queryMock);
  inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID);
  inOrder.verify(queryMock).list();
  inOrder.verifyNoMoreInteractions();

  verifyBatchListJson(response.asString());
}
 
@Test
public void testSuspendAsyncWithMultipleGroupOperations() {
  List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
  ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
  Map<String, Object> messageBodyJson = new HashMap<String, Object>();
  messageBodyJson.put("processInstanceIds", ids);
  messageBodyJson.put("processInstanceQuery", query);
  messageBodyJson.put("suspended", true);

  when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
  given()
    .contentType(ContentType.JSON)
    .body(messageBodyJson)
    .then()
    .expect()
    .statusCode(Status.OK.getStatusCode())
    .when()
    .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);

  verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
  verify(mockUpdateProcessInstancesSuspensionStateBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
  verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
 
源代码20 项目: openhab-core   文件: RuleResource.java
@GET
@Path("/{ruleUID}/{moduleCategory}/{id}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets the rule's module corresponding to the given Category and ID.", response = ModuleDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ModuleDTO.class),
        @ApiResponse(code = 404, message = "Rule corresponding to the given UID does not found or does not have a module with such Category and ID.") })
public Response getModuleById(@PathParam("ruleUID") @ApiParam(value = "ruleUID") String ruleUID,
        @PathParam("moduleCategory") @ApiParam(value = "moduleCategory") String moduleCategory,
        @PathParam("id") @ApiParam(value = "id") String id) {
    Rule rule = ruleRegistry.get(ruleUID);
    if (rule != null) {
        final ModuleDTO dto = getModuleDTO(rule, moduleCategory, id);
        if (dto != null) {
            return Response.ok(dto).build();
        }
    }
    return Response.status(Status.NOT_FOUND).build();
}
 
@Test
public void testSuspendAsyncWithHistoricProcessInstanceQuery() {
  Map<String, Object> messageBodyJson = new HashMap<String, Object>();
  List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
  messageBodyJson.put("processInstanceIds", ids);
  messageBodyJson.put("suspended", true);

  when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
  given()
    .contentType(ContentType.JSON)
    .body(messageBodyJson)
    .then()
    .expect()
    .statusCode(Status.OK.getStatusCode())
    .when()
    .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);

  verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
  verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
 
@Test
public void testTenantIdListParameter() {
  mockQuery = setUpMockJobQuery(createMockJobsTwoTenants());

  Response response = given()
    .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST)
  .then().expect()
    .statusCode(Status.OK.getStatusCode())
  .when()
    .get(JOBS_RESOURCE_URL);

  verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
  verify(mockQuery).list();

  String content = response.asString();
  List<String> jobs = from(content).getList("");
  assertThat(jobs).hasSize(2);

  String returnedTenantId1 = from(content).getString("[0].tenantId");
  String returnedTenantId2 = from(content).getString("[1].tenantId");

  assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
  assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
}
 
源代码23 项目: keycloak   文件: DemoServletsAdapterTest.java
@Test
public void testBasicAuth() {
    String value = "hello";
    Client client = ClientBuilder.newClient();

    //pause(1000000);

    Response response = client.target(basicAuthPage
            .setTemplateValues(value).buildUri()).request().header("Authorization", BasicAuthHelper.createHeader("mposolda", "password")).get();

    assertThat(response, Matchers.statusCodeIs(Status.OK));
    assertEquals(value, response.readEntity(String.class));
    response.close();

    response = client.target(basicAuthPage
            .setTemplateValues(value).buildUri()).request().header("Authorization", BasicAuthHelper.createHeader("invalid-user", "password")).get();
    assertThat(response, Matchers.statusCodeIs(Status.UNAUTHORIZED));
    assertThat(response, Matchers.body(anyOf(containsString("Unauthorized"), containsString("Status 401"))));

    response = client.target(basicAuthPage
            .setTemplateValues(value).buildUri()).request().header("Authorization", BasicAuthHelper.createHeader("admin", "invalid-password")).get();
    assertThat(response, Matchers.statusCodeIs(Status.UNAUTHORIZED));
    assertThat(response, Matchers.body(anyOf(containsString("Unauthorized"), containsString("Status 401"))));

    client.close();
}
 
源代码24 项目: pulsar   文件: PersistentTopicsTest.java
@Test
public void testTerminatePartitionedTopic() {
    String testLocalTopicName = "topic-not-found";

    // 3) Create the partitioned topic
    AsyncResponse response  = mock(AsyncResponse.class);
    persistentTopics.createPartitionedTopic(response, testTenant, testNamespace, testLocalTopicName, 1);
    ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
    verify(response, timeout(5000).times(1)).resume(responseCaptor.capture());
    Assert.assertEquals(responseCaptor.getValue().getStatus(), Response.Status.NO_CONTENT.getStatusCode());

    // 5) Create a subscription
    response  = mock(AsyncResponse.class);
    persistentTopics.createSubscription(response, testTenant, testNamespace, testLocalTopicName, "test", true,
            (MessageIdImpl) MessageId.earliest, false);
    responseCaptor = ArgumentCaptor.forClass(Response.class);
    verify(response, timeout(5000).times(1)).resume(responseCaptor.capture());
    Assert.assertEquals(responseCaptor.getValue().getStatus(), Response.Status.NO_CONTENT.getStatusCode());

    // 9) terminate partitioned topic
    response = mock(AsyncResponse.class);
    persistentTopics.terminatePartitionedTopic(response, testTenant, testNamespace, testLocalTopicName, true);
    verify(response, timeout(5000).times(1)).resume(Arrays.asList(new MessageIdImpl(3, -1, -1)));
}
 
@Test
public void testTaskCountReportWithGroupByTaskDef() {
  given()
    .queryParam("reportType", "count")
    .queryParam("groupBy", "taskName")
  .then()
    .expect()
      .statusCode(Status.OK.getStatusCode())
      .contentType(ContentType.JSON)
  .when()
    .get(TASK_REPORT_URL);

  verify(mockedReportQuery).countByTaskName();
  verifyNoMoreInteractions(mockedReportQuery);
}
 
@Test
public void testQueryCount() {
  given()
      .header("accept", MediaType.APPLICATION_JSON)
    .expect()
    .statusCode(Status.OK.getStatusCode())
    .body("count", equalTo(1))
    .when()
      .get(TASK_COUNT_QUERY_URL);

  verify(mockQuery).count();
}
 
@Test
public void testSortOrderParameterOnly() {
  given().queryParam("sortOrder", "asc")
      .then()
      .expect()
      .statusCode(Status.BAD_REQUEST.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type",
          equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message",
          equalTo("Only a single sorting parameter specified. sortBy and sortOrder required"))
      .when().get(JOBS_RESOURCE_URL);
}
 
@Test
public void testMissingFirstResultParameter() {
  int maxResults = 10;

  given()
    .queryParam("maxResults", maxResults)
  .then()
    .expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL);

  verify(mockedQuery).listPage(0, maxResults);
}
 
源代码29 项目: secure-data-service   文件: RealmResource.java
@POST
@RightsAllowed({ Right.CRUD_REALM })
public Response createRealm(EntityBody newRealm, @Context final UriInfo uriInfo) {

    if (!canEditCurrentRealm(newRealm)) {
        EntityBody body = new EntityBody();
        body.put(RESPONSE, "You are not authorized to create a realm for another ed org");
        return Response.status(Status.FORBIDDEN).entity(body).build();
    }
    Response validateUniqueness = validateUniqueId(null, (String) newRealm.get(UNIQUE_IDENTIFIER),
            (String) newRealm.get(NAME), getIdpId(newRealm));
    if (validateUniqueness != null) {
        LOG.debug("On realm create, uniqueId is not unique");
        return validateUniqueness;
    }

    Response validateArtifactResolution = validateArtifactResolution((String) newRealm.get(ARTIFACT_RESOLUTION_ENDPOINT), (String) newRealm.get(SOURCE_ID));
    if (validateArtifactResolution != null) {
        LOG.debug("Invalid artifact resolution information");
        return validateArtifactResolution;
    }

    // set the tenant and edOrg
    newRealm.put("tenantId", SecurityUtil.getTenantId());
    newRealm.put(ED_ORG, SecurityUtil.getEdOrg());

    String id = service.create(newRealm);
    logSecurityEvent(uriInfo, null, newRealm);

    // Also create custom roles
    roleInitializer.dropAndBuildRoles(id);
    
    String uri = uriToString(uriInfo) + "/" + id;

    return Response.status(Status.CREATED).header("Location", uri).build();
}
 
/**
 * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default.
 */
@Test
public void testMissingMaxResultsParameter() {
  int firstResult = 10;

  given()
    .queryParam("firstResult", firstResult)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
    .when()
      .get(DECISION_DEFINITION_QUERY_URL);

  verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE);
}