Java Code Examples for javax.ws.rs.core.Response#getEntity()

The following examples show how to use javax.ws.rs.core.Response#getEntity() . 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: ConnectionActionHandlerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetInoutOutputShapesToAnyIfMetadataCallFails() {
    @SuppressWarnings({"unchecked", "rawtypes"})
    final Class<Entity<Map<String, Object>>> entityType = (Class) Entity.class;
    ArgumentCaptor.forClass(entityType);

    // simulates fallback return
    final DynamicActionMetadata fallback = new DynamicActionMetadata.Builder().build();
    when(metadataCommand.execute()).thenReturn(fallback);
    when(((HystrixInvokableInfo<?>) metadataCommand).isSuccessfulExecution()).thenReturn(false);

    final Response response = handler.enrichWithMetadata(SALESFORCE_CREATE_OR_UPDATE, Collections.emptyMap());

    @SuppressWarnings("unchecked")
    final Meta<ConnectorDescriptor> meta = (Meta<ConnectorDescriptor>) response.getEntity();

    final ConnectorDescriptor descriptor = meta.getValue();
    assertThat(descriptor.getInputDataShape()).contains(ConnectionActionHandler.ANY_SHAPE);
    assertThat(descriptor.getOutputDataShape()).contains(salesforceOutputShape);
}
 
Example 2
Source File: TestSiteToSiteResource.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetController() throws Exception {
    final HttpServletRequest req = createCommonHttpServletRequest();

    final NiFiServiceFacade serviceFacade = mock(NiFiServiceFacade.class);
    final ControllerEntity controllerEntity = new ControllerEntity();
    final ControllerDTO controller = new ControllerDTO();
    controllerEntity.setController(controller);

    controller.setRemoteSiteHttpListeningPort(8080);
    controller.setRemoteSiteListeningPort(9990);

    doReturn(controller).when(serviceFacade).getSiteToSiteDetails();

    final SiteToSiteResource resource = getSiteToSiteResource(serviceFacade);
    final Response response = resource.getSiteToSiteDetails(req);

    ControllerEntity resultEntity = (ControllerEntity)response.getEntity();

    assertEquals(200, response.getStatus());
    assertEquals("remoteSiteHttpListeningPort should be retained", new Integer(8080), resultEntity.getController().getRemoteSiteHttpListeningPort());
    assertEquals("Other fields should be retained.", new Integer(9990), controllerEntity.getController().getRemoteSiteListeningPort());
}
 
Example 3
Source File: BrowserHistoryHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Response saveResponseAndRedirect(KeycloakSession session, AuthenticationSessionModel authSession, Response response, boolean actionRequest, HttpRequest httpRequest) {
    if (!shouldReplaceBrowserHistory(actionRequest, httpRequest)) {
        return response;
    }

    // For now, handle just status 200 with String body. See if more is needed...
    Object entity = response.getEntity();
    if (entity != null && entity instanceof String) {
        String responseString = (String) entity;

        URI lastExecutionURL = new AuthenticationFlowURLHelper(session, session.getContext().getRealm(), session.getContext().getUri()).getLastExecutionUrl(authSession);

        // Inject javascript for history "replaceState"
        String responseWithJavascript = responseWithJavascript(responseString, lastExecutionURL.toString());

        return Response.fromResponse(response).entity(responseWithJavascript).build();
    }


    return response;
}
 
Example 4
Source File: CreateChargeExceptionMapperTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Test
public void shouldThrow409_whenMandateStateInvalid(){
    when(mockResponse.readEntity(ConnectorErrorResponse.class))
            .thenReturn(new ConnectorErrorResponse(
                    ErrorIdentifier.MANDATE_STATE_INVALID, null, null));
    
    Response returnedResponse = mapper.toResponse(new CreateChargeException(mockResponse));
    PaymentError returnedError = (PaymentError) returnedResponse.getEntity();
    PaymentError expectedError = aPaymentError(CREATE_PAYMENT_MANDATE_STATE_INVALID);
    
    assertThat(returnedResponse.getStatus(), is(409));
    assertThat(returnedError.getDescription(), 
            is(expectedError.getDescription()));
    assertThat(returnedError.getCode(), is(expectedError.getCode()));
    
}
 
Example 5
Source File: CommentResourceTest.java    From gossip with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void return_a_empty_comment_list_when_have_a_newly_created_article() {
    ArticleDTO articleDTO = randomArticleDTO().setId(randomId());
    when(articleService.getOrRegisterArticle(articleDTO)).thenReturn(articleDTO);
    when(commentService.getCommentsByArticle(articleDTO)).thenReturn(emptyList());

    Response response = commentResource.loadComment(articleDTO);
    Object entity = response.getEntity();

    verify(articleService, only()).getOrRegisterArticle(articleDTO);
    verify(commentService, only()).getCommentsByArticle(any(ArticleDTO.class));

    assertThat(entity.getClass(), typeCompatibleWith(BaseApiResponse.class));
    BaseApiResponse<List<CommentDTO>> res = (BaseApiResponse<List<CommentDTO>>) entity;
    assertThat(res.getResult(), hasSize(0));
}
 
Example 6
Source File: TestDataTransferResource.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTransactionPortNotFound() throws Exception {
    final HttpServletRequest req = createCommonHttpServletRequest();

    final DataTransferResource resource = getDataTransferResource();
    final HttpFlowFileServerProtocol serverProtocol = resource.getHttpFlowFileServerProtocol(null);

    doThrow(new HandshakeException(ResponseCode.UNKNOWN_PORT, "Not found.")).when(serverProtocol).handshake(any());

    final ServletContext context = null;
    final UriInfo uriInfo = null;
    final InputStream inputStream = null;

    final Response response = resource.createPortTransaction("input-ports", "port-id", req, context, uriInfo, inputStream);

    TransactionResultEntity resultEntity = (TransactionResultEntity) response.getEntity();

    assertEquals(404, response.getStatus());
    assertEquals(ResponseCode.UNKNOWN_PORT.getCode(), resultEntity.getResponseCode());
}
 
Example 7
Source File: EndpointsQueriesTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.AvoidUsingHardCodedIP")
private void testEndpoint(String expectedHostname) throws ConfigStoreException {
    when(mockStateStore.fetchTasks()).thenReturn(TASK_INFOS);
    Response response = EndpointsQueries.getEndpoint(
            mockStateStore, SERVICE_NAME, CUSTOM_ENDPOINTS, "porta", SCHEDULER_CONFIG);
    assertEquals(200, response.getStatus());
    JSONObject json = new JSONObject((String) response.getEntity());
    assertEquals(json.toString(), 3, json.length());
    assertEquals(String.format("vip1.svc-name.%s:5432", SCHEDULER_CONFIG.getVipTLD()), json.get("vip"));
    JSONArray dns = json.getJSONArray("dns");
    assertEquals(4, dns.length());
    assertEquals(String.format("ports-1.%s.%s:1234", SERVICE_NAME, SCHEDULER_CONFIG.getAutoipTLD()), dns.get(0));
    assertEquals(String.format("ports-2.%s.%s:1243", SERVICE_NAME, SCHEDULER_CONFIG.getAutoipTLD()), dns.get(1));
    assertEquals(String.format("vips-1.%s.%s:2345", SERVICE_NAME, SCHEDULER_CONFIG.getAutoipTLD()), dns.get(2));
    assertEquals(String.format("vips-2.%s.%s:3456", SERVICE_NAME, SCHEDULER_CONFIG.getAutoipTLD()), dns.get(3));
    JSONArray address = json.getJSONArray("address");
    assertEquals(4, address.length());
    assertEquals(address.toString(), expectedHostname + ":1234", address.get(0));
    assertEquals(expectedHostname + ":1243", address.get(1));
    assertEquals(expectedHostname + ":2345", address.get(2));
    assertEquals(expectedHostname + ":3456", address.get(3));
}
 
Example 8
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenRenewal_ServerManagedStateEnabledAtGatewayWithServiceOverride() throws Exception {
  final String caller = "yarn";
  Map.Entry<TestTokenStateService, Response> result =
          doTestTokenRenewal(false, true, caller, null, createTestSubject(caller));

  // Make sure the expiration was not recorded by the TokenStateService, since it is disabled for this test
  TestTokenStateService tss = result.getKey();
  assertEquals("TokenStateService should be disabled for this test.", 0, tss.expirationData.size());

  Response renewalResponse = result.getValue();
  validateSuccessfulRenewalResponse(renewalResponse);
  String responseContent = (String) renewalResponse.getEntity();
  assertNotNull(responseContent);
  Map<String, String> json = parseJSONResponse(responseContent);
  assertTrue(Boolean.parseBoolean(json.get("renewed")));
  assertNotNull(json.get("expires")); // Should get back the original expiration from the token itself
}
 
Example 9
Source File: UserResourceTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testReadAll() {
    Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>();
    rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN));
    Mockito.when(secUtil.getAllRights()).thenReturn(rights);
    Mockito.when(secUtil.getUid()).thenReturn("myUid");
    Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(false);

    List<User> users = Arrays.asList(new User(), new User());
    Mockito.when(
            ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class),
                    Mockito.anyCollectionOf(String.class), Mockito.anyString(),
                    (Collection<String>) Mockito.isNull())).thenReturn(users);

    Response res = resource.readAll();
    Assert.assertEquals(200, res.getStatus());
    Object entity = res.getEntity();
    Assert.assertEquals(users, entity);
}
 
Example 10
Source File: DefaultExceptionMapperTest.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Test
public void testToResponseStatus500() {
    int code = 500;
    Response.Status status = Response.Status.fromStatusCode(code);
    String message = "Some error message";
    KubernetesClientException kubernetesClientException = new KubernetesClientException(message, new NullPointerException("something's gone bad!"));

    Response response = new DefaultExceptionMapper().toResponse(kubernetesClientException);
    assertEquals(code, response.getStatus());
    assertEquals(status.getReasonPhrase(), response.getStatusInfo().getReasonPhrase());
    assertTrue(response.getEntity() instanceof Status);
    Status responseEntity = (Status) response.getEntity();
    assertEquals("Internal Server Error", responseEntity.getReason());
    assertEquals(message, responseEntity.getMessage());
}
 
Example 11
Source File: TestDataTransferResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTransaction() throws Exception {
    final HttpServletRequest req = createCommonHttpServletRequest();

    final DataTransferResource resource = getDataTransferResource();

    final String locationUriStr = "http://localhost:8080/nifi-api/data-transfer/input-ports/port-id/transactions/transaction-id";

    final ServletContext context = null;
    final UriInfo uriInfo = mockUriInfo(locationUriStr);
    final Field uriInfoField = resource.getClass().getSuperclass().getSuperclass()
            .getDeclaredField("uriInfo");
    uriInfoField.setAccessible(true);
    uriInfoField.set(resource, uriInfo);

    final HttpServletRequest request = mock(HttpServletRequest.class);
    final Field httpServletRequestField = resource.getClass().getSuperclass().getSuperclass()
            .getDeclaredField("httpServletRequest");
    httpServletRequestField.setAccessible(true);
    httpServletRequestField.set(resource, request);

    final InputStream inputStream = null;

   final Response response = resource.createPortTransaction("input-ports", "port-id", req, context, uriInfo, inputStream);

    TransactionResultEntity resultEntity = (TransactionResultEntity) response.getEntity();

    assertEquals(201, response.getStatus());
    assertEquals(ResponseCode.PROPERTIES_OK.getCode(), resultEntity.getResponseCode());
    assertEquals(locationUriStr, response.getMetadata().getFirst(HttpHeaders.LOCATION_HEADER_NAME).toString());
}
 
Example 12
Source File: OnboardingResourceTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testProvision() {
    Map<String, String> requestBody = new HashMap<String, String>();
    requestBody.put(OnboardingResource.STATE_EDORG_ID, "TestOrg");
    requestBody.put(ResourceConstants.ENTITY_METADATA_TENANT_ID, "12345");
    requestBody.put(OnboardingResource.PRELOAD_FILES_ID, "small_sample_dataset");

    LandingZoneInfo landingZone = new LandingZoneInfo("LANDING ZONE", "INGESTION SERVER");

    Map<String, String> tenantBody = new HashMap<String, String>();
    tenantBody.put("landingZone", "LANDING ZONE");
    tenantBody.put("ingestionServer", "INGESTION SERVER");

    // Entity tenantEntity = Mockito.mock(Entity.class);
    // when(tenantEntity.getBody()).thenReturn(tenantBody);
    try {
        when(mockTenantResource.createLandingZone(Mockito.anyString(), Mockito.eq("TestOrg"), Mockito.anyBoolean())).thenReturn(landingZone);
    } catch (TenantResourceCreationException e) {
        Assert.fail(e.getMessage());
    }

    Response res = resource.provision(requestBody, null);
    assertTrue(Status.fromStatusCode(res.getStatus()) == Status.CREATED);
    Map<String, String> result = (Map<String, String>) res.getEntity();
    assertNotNull(result.get("landingZone"));
    Assert.assertEquals("LANDING ZONE", result.get("landingZone"));
    assertNotNull(result.get("serverName"));
    Assert.assertEquals("landingZone", result.get("serverName"));

    // Attempt to create the same edorg.
    res = resource.provision(requestBody, null);
    assertEquals(Status.CREATED, Status.fromStatusCode(res.getStatus()));
}
 
Example 13
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void validateRenewalResponse(final Response response,
                                            final int      expectedStatusCode,
                                            final boolean  expectedResult,
                                            final String   expectedMessage) throws IOException {
  assertEquals(expectedStatusCode, response.getStatus());
  assertTrue(response.hasEntity());
  String responseContent = (String) response.getEntity();
  assertNotNull(responseContent);
  assertFalse(responseContent.isEmpty());
  Map<String, String> json = parseJSONResponse(responseContent);
  boolean result = Boolean.valueOf(json.get("renewed"));
  assertEquals(expectedResult, result);
  assertEquals(expectedMessage, json.get("error"));
}
 
Example 14
Source File: Api1.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * @param a {@link App}
 * @return response
 */
@SuppressWarnings("unchecked")
public static Inflector<ContainerRequestContext, Response> grantPermitHandler(final App a) {
	return new Inflector<ContainerRequestContext, Response>() {
		public Response apply(ContainerRequestContext ctx) {
			App app = (a != null) ? a : getPrincipalApp();
			String subjectid = pathParam("subjectid", ctx);
			String resourcePath = pathParam(Config._TYPE, ctx);
			if (app != null) {
				Response resp = getEntity(ctx.getEntityStream(), List.class);
				if (resp.getStatusInfo() == Response.Status.OK) {
					List<String> permission = (List<String>) resp.getEntity();
					Set<App.AllowedMethods> set = new HashSet<>(permission.size());
					for (String perm : permission) {
						if (!StringUtils.isBlank(perm)) {
							App.AllowedMethods method = App.AllowedMethods.fromString(perm);
							if (method != null) {
								set.add(method);
							}
						}
					}
					if (!set.isEmpty()) {
						if (app.grantResourcePermission(subjectid, resourcePath, EnumSet.copyOf(set))) {
							app.update();
						}
						return Response.ok(app.getAllResourcePermissions(subjectid)).build();
					} else {
						return getStatusResponse(Response.Status.BAD_REQUEST, "No allowed methods specified.");
					}
				} else {
					return resp;
				}
			}
			return getStatusResponse(Response.Status.NOT_FOUND, "App not found.");
		}
	};
}
 
Example 15
Source File: StepActionHandlerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleVariantCompression() {
    final DynamicActionMetadata givenMetadata = new DynamicActionMetadata.Builder()
            .outputShape(new DataShape.Builder()
                    .createFrom(collectionShape)
                    .addVariant(new DataShape.Builder()
                            .createFrom(elementShape)
                            .putMetadata(DataShapeMetaData.SHOULD_COMPRESS, "true")
                            .compress()
                            .build())
                    .addVariant(dummyShape())
                    .build())
            .build();

    final Response response = handler.enrichStepMetadata(StepKind.split.name(), givenMetadata);

    @SuppressWarnings("unchecked")
    final Meta<StepDescriptor> meta = (Meta<StepDescriptor>) response.getEntity();

    final StepDescriptor descriptor = meta.getValue();
    assertThat(descriptor.getInputDataShape()).contains(StepMetadataHelper.NO_SHAPE);
    assertThat(descriptor.getOutputDataShape()).isPresent();
    assertThat(descriptor.getOutputDataShape()).get().isEqualToComparingFieldByField(new DataShape.Builder()
            .createFrom(elementShape)
            .putMetadata(DataShapeMetaData.SHOULD_COMPRESS, "true")
            .putMetadata("compressed", "false")
            .addVariant(dummyShape())
            .addVariant(collectionShape)
            .build());
}
 
Example 16
Source File: ServletsTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
public void testEmptyMessage() throws Exception {
    //This shouldn't throw exception
    Response response =
            Servlets.getErrorResponse(new NullPointerException(), Response.Status.INTERNAL_SERVER_ERROR);
    assertNotNull(response);
    ObjectNode responseEntity = (ObjectNode) response.getEntity();
    assertNotNull(responseEntity);
    assertNotNull(responseEntity.get(AtlasClient.ERROR));
}
 
Example 17
Source File: TestSiteToSiteResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testPeersVersionWasNotSpecified() throws Exception {
    final HttpServletRequest req = mock(HttpServletRequest.class);

    final NiFiServiceFacade serviceFacade = mock(NiFiServiceFacade.class);

    final SiteToSiteResource resource = getSiteToSiteResource(serviceFacade);

    final Response response = resource.getPeers(req);

    TransactionResultEntity resultEntity = (TransactionResultEntity) response.getEntity();
    assertEquals(400, response.getStatus());
    assertEquals(ResponseCode.ABORT.getCode(), resultEntity.getResponseCode());
}
 
Example 18
Source File: AdminServiceRestImplTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsJwalaAuthorizationEnabled() throws Exception {
    Response response = cut.isJwalaAuthorizationEnabled();
    ApplicationResponse applicationResponse = (ApplicationResponse) response.getEntity();
    Object content = applicationResponse.getApplicationResponseContent();
    assertEquals(content, AdminServiceRestImpl.JSON_RESPONSE_TRUE);
    System.setProperty("jwala.authorization", "false");
}
 
Example 19
Source File: TestSecretResource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void updateFileSecret() throws Exception {
  String pipelineId = "PIPELINE_VAULT_pipelineId";
  String secretName = "stage_id_config1";
  String secretValue = "secretValue";
  TestUtil.CredentialStoreTaskTestInjector.INSTANCE.store(
      CredentialStoresTask.DEFAULT_SDC_GROUP_AS_LIST, pipelineId + "/" + secretName,
      secretValue
  );
  String changedSecretValue = "changedSecretValue";

  String secretPath = pipelineId + "/" + secretName;

  Path tempFile = Files.createTempFile("secret.txt", ".crt");

  try {
    try (FileWriter f = new FileWriter(tempFile.toFile().getAbsolutePath())) {
      f.write(changedSecretValue);
    }

    FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("uploadedFile", tempFile.toFile());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
        .field("vault", pipelineId, MediaType.APPLICATION_JSON_TYPE)
        .field("name", secretName, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(fileDataBodyPart);


    Response response = target(
        Utils.format("/v1/secrets/{}/file/ctx=SecretManage", URLEncoder.encode(secretPath, StandardCharsets.UTF_8.name()))
    ).register(MultiPartFeature.class).request().post(Entity.entity(multipart, multipart.getMediaType()));

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

    InputStream responseEntity = (InputStream) response.getEntity();

    OkRestResponse<RSecret> secretResponse = ObjectMapperFactory.get()
        .readValue(responseEntity, new TypeReference<OkRestResponse<RSecret>>() {});

    RSecret rSecret = secretResponse.getData();
    Assert.assertNotNull(rSecret);
    Assert.assertEquals(pipelineId, rSecret.getVault().getValue());
    Assert.assertEquals(secretName, rSecret.getName().getValue());

    Assert.assertTrue(TestUtil.CredentialStoreTaskTestInjector.INSTANCE.getNames().contains(pipelineId + "/" + secretName));
    CredentialValue changedValue = TestUtil.CredentialStoreTaskTestInjector.INSTANCE.get("",
        pipelineId + "/" + secretName,
        ""
    );
    Assert.assertEquals(IOUtils.toString(new FileReader(tempFile.toFile())), changedValue.get());
    Assert.assertEquals(changedSecretValue, changedValue.get());
  } finally {
    Files.delete(tempFile);
  }
}
 
Example 20
Source File: WebApplicationExceptionMapperTest.java    From openscoring with GNU Affero General Public License v3.0 3 votes vote down vote up
static
private String getMessage(WebApplicationException exception){
	WebApplicationExceptionMapper exceptionMapper = new WebApplicationExceptionMapper();

	Response response = exceptionMapper.toResponse(exception);

	SimpleResponse entity = (SimpleResponse)response.getEntity();

	return entity.getMessage();
}