javax.ws.rs.core.Response.Status Java Examples

The following examples show how to use javax.ws.rs.core.Response.Status. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: zeppelin   Author: apache   File: NotebookRestApi.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source Project: incubator-pinot   Author: apache   File: OnboardDatasetMetricResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source Project: mrgeo   Author: ngageoint   File: TileMapServiceResourceIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
@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());
}
 
Example #5
Source Project: pulsar   Author: apache   File: NamespacesTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #6
Source Project: sailfish-core   Author: exactpro   File: MachineLearningResourceV2.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #7
Source Project: camunda-bpm-platform   Author: camunda   File: HistoricDecisionInstanceResourceImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source Project: hawkular-metrics   Author: hawkular   File: TenantFilter.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source Project: servicecomb-java-chassis   Author: apache   File: ServiceRegistryClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
@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);
}
 
Example #11
Source Project: camunda-bpm-platform   Author: camunda   File: JobDefinitionRestServiceInteractionTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #12
Source Project: camunda-bpm-platform   Author: camunda   File: TaskRestServiceInteractionTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source Project: camunda-bpm-platform   Author: camunda   File: CaseExecutionRestServiceQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source Project: pulsar   Author: apache   File: PersistentTopicsBase.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #15
Source Project: camunda-bpm-platform   Author: camunda   File: BatchRestServiceStatisticsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #16
Source Project: TeaStore   Author: DescartesResearch   File: CacheManagerEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #17
Source Project: monolith   Author: ticket-monster-msa   File: PerformanceEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source Project: camunda-bpm-platform   Author: camunda   File: BatchRestServiceQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #19
@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();
}
 
Example #20
Source Project: openhab-core   Author: openhab   File: RuleResource.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example #21
@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();
}
 
Example #22
Source Project: camunda-bpm-platform   Author: camunda   File: JobRestServiceQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #23
Source Project: keycloak   Author: keycloak   File: DemoServletsAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #24
Source Project: pulsar   Author: apache   File: PersistentTopicsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #25
Source Project: camunda-bpm-platform   Author: camunda   File: HistoricTaskReportRestServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source Project: camunda-bpm-platform   Author: camunda   File: TaskRestServiceQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #27
Source Project: camunda-bpm-platform   Author: camunda   File: JobRestServiceQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
@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);
}
 
Example #29
Source Project: secure-data-service   Author: inbloom   File: RealmResource.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source Project: camunda-bpm-platform   Author: camunda   File: DecisionDefinitionRestServiceQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}