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 File: JobDefinitionRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #2
Source File: RuleResource.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
@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 #3
Source File: TileMapServiceResourceIntegrationTest.java From mrgeo with Apache License 2.0 | 6 votes |
@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
Source File: ProcessDefinitionRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 File: OnboardDatasetMetricResource.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: ProcessInstanceRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #7
Source File: JobRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #8
Source File: NotebookRestApi.java From zeppelin with Apache License 2.0 | 6 votes |
@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 #9
Source File: DemoServletsAdapterTest.java From keycloak with Apache License 2.0 | 6 votes |
@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 #10
Source File: PersistentTopicsTest.java From pulsar with Apache License 2.0 | 6 votes |
@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 #11
Source File: ProcessInstanceRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #12
Source File: BatchRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #13
Source File: NamespacesTest.java From pulsar with Apache License 2.0 | 6 votes |
@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 #14
Source File: CacheManagerEndpoint.java From TeaStore with Apache License 2.0 | 6 votes |
/** * 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 #15
Source File: BatchRestServiceStatisticsTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 File: HistoricDecisionInstanceResourceImpl.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
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 #17
Source File: PersistentTopicsBase.java From pulsar with Apache License 2.0 | 6 votes |
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 #18
Source File: TenantFilter.java From hawkular-metrics with Apache License 2.0 | 6 votes |
@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 #19
Source File: ServiceRegistryClientImpl.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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 #20
Source File: CaseExecutionRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #21
Source File: PerformanceEndpoint.java From monolith with Apache License 2.0 | 6 votes |
@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 #22
Source File: ProcessDefinitionRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #23
Source File: MachineLearningResourceV2.java From sailfish-core with Apache License 2.0 | 6 votes |
@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 #24
Source File: TaskRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #25
Source File: RResourceIT.java From nexus-repository-r with Eclipse Public License 1.0 | 5 votes |
@Test public void updateProxy_noAuthz() throws Exception { repos.createRProxy(PROXY_NAME, REMOTE_URL); setUnauthorizedUser(); AbstractRepositoryApiRequest request = createProxyRequest(false); Response response = put(getUpdateRepositoryPathUrl(ProxyType.NAME, PROXY_NAME), request); assertEquals(Status.FORBIDDEN.getStatusCode(), response.getStatus()); }
Example #26
Source File: ErrorMessagesTest.java From sinavi-jfw with Apache License 2.0 | 5 votes |
@Test public void 指定したHTTPステータスのみが設定される() { ErrorMessage error = ErrorMessages.create().status(Status.INTERNAL_SERVER_ERROR.getStatusCode()).get(); assertThat(error, CoreMatchers.notNullValue()); assertThat(error.getStatus(), CoreMatchers.is(500)); assertThat(error.getMessage(), CoreMatchers.nullValue()); }
Example #27
Source File: RestServiceExceptionMapper.java From cxf-fediz with Apache License 2.0 | 5 votes |
@Override public Response toResponse(final Exception ex) { LOG.warn("Exception occured processing REST request: " + ex.getMessage(), ex); if (ex instanceof AccessDeniedException) { return Response.status(Response.Status.UNAUTHORIZED). header(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM_UNAUTHORIZED). build(); } if (ex instanceof ConstraintViolationException) { ConstraintViolationException cve = (ConstraintViolationException)ex; LOG.debug("{}\n{}", ex.getMessage(), cve.getConstraintViolations().toString()); return buildResponse(Response.Status.BAD_REQUEST, ex); } if (ex instanceof DataIntegrityViolationException) { return buildResponse(Response.Status.CONFLICT, ex); } if (ex instanceof EmptyResultDataAccessException) { return buildResponse(Response.Status.NOT_FOUND, ex); } if (ex instanceof DataRetrievalFailureException) { return buildResponse(Response.Status.NOT_FOUND, ex); } // Rest is interpreted as InternalServerError return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, ex); }
Example #28
Source File: StreamMetadataResourceImpl.java From pravega with Apache License 2.0 | 5 votes |
/** * Implementation of getStream REST API. * * @param scopeName The scope name of stream. * @param streamName The name of stream. * @param securityContext The security for API access. * @param asyncResponse AsyncResponse provides means for asynchronous server side response processing. */ @Override public void getStream(final String scopeName, final String streamName, final SecurityContext securityContext, final AsyncResponse asyncResponse) { long traceId = LoggerHelpers.traceEnter(log, "getStream"); try { restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), AuthResourceRepresentation.ofStreamInScope(scopeName, streamName), READ); } catch (AuthException e) { log.warn("Get stream for {} failed due to authentication failure.", scopeName + "/" + streamName); asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build()); LoggerHelpers.traceLeave(log, "getStream", traceId); return; } controllerService.getStream(scopeName, streamName) .thenApply(streamConfig -> Response.status(Status.OK) .entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfig)) .build()) .exceptionally(exception -> { if (exception.getCause() instanceof StoreException.DataNotFoundException || exception instanceof StoreException.DataNotFoundException) { log.warn("Stream: {}/{} not found", scopeName, streamName); return Response.status(Status.NOT_FOUND).build(); } else { log.warn("getStream for {}/{} failed with exception: {}", scopeName, streamName, exception); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }).thenApply(asyncResponse::resume) .thenAccept(x -> LoggerHelpers.traceLeave(log, "getStream", traceId)); }
Example #29
Source File: FilterRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testExecuteList() { given() .header(ACCEPT_JSON_HEADER) .pathParam("id", EXAMPLE_FILTER_ID) .then().expect() .statusCode(Status.OK.getStatusCode()) .body("$.size()", equalTo(1)) .when() .get(EXECUTE_LIST_FILTER_URL); verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), isNull(Query.class)); }
Example #30
Source File: HttpSBControllerImpl.java From onos with Apache License 2.0 | 5 votes |
@Override public int post(DeviceId device, String request, InputStream payload, MediaType mediaType) { Response response = getResponse(device, request, payload, mediaType); if (response == null) { return Status.NO_CONTENT.getStatusCode(); } return response.getStatus(); }