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

The following examples show how to use javax.ws.rs.core.Response#getStatus() . 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: OpenstackRouterWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the results of the REST API POST with creation operation.
 */
@Test
public void testCreateRouterWithCreationOperation() {
    mockOpenstackRouterAdminService.createRouter(anyObject());
    replay(mockOpenstackRouterAdminService);
    expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
    replay(mockOpenstackHaService);

    final WebTarget wt = target();
    InputStream jsonStream = OpenstackRouterWebResourceTest.class
            .getResourceAsStream("openstack-router.json");

    Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(jsonStream));
    final int status = response.getStatus();

    assertThat(status, is(201));

    verify(mockOpenstackRouterAdminService);
}
 
Example 2
Source File: DocumentClientService.java    From yaas_java_jersey_wishlist with Apache License 2.0 6 votes vote down vote up
public void deleteWishlist(final YaasAwareParameters yaasAware, final String wishlistId, final AccessToken token) {
    final Response response = documentClient
            .tenant(yaasAware.getHybrisTenant())
            .client(client)
            .dataType(WISHLIST_PATH)
            .dataId(wishlistId)
            .prepareDelete()
            .withAuthorization(token.toAuthorizationHeaderValue())
            .execute();

    if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) {
        return;
    } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        throw new NotFoundException("Cannot find wishlist with ID " + wishlistId, response);
    }
    throw ErrorHandler.resolveErrorResponse(response, token);
}
 
Example 3
Source File: WatcherClient.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
public boolean updateLastIpInFile(final String filePath, final String newIp) {
    Response response = null;
    boolean isFinished;

    try {
        response = service.path("cmd")
                .path("updateIP")
                .queryParam("filePath", filePath)
                .queryParam("newIp", newIp)
                .request(MediaType.APPLICATION_JSON)
                .post(null);

        isFinished = response.getStatus() == Response.Status.OK.getStatusCode();
        CLIENT_LOGGER.info(filePath + " was updated with the following ip: " + newIp);
    } catch (Exception ex) {
        isFinished = false;
        CLIENT_LOGGER.severe("Can't update ip in a file: " + ex);
    } finally {
        if (response != null) {
            response.close();
        }
    }

    return isFinished;
}
 
Example 4
Source File: SchAdmin.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Validates Component type is supported by Control Hub instance or not.
 */
private static boolean isValidComponentType(String url, String userAuthToken, String componentType) {
  Response response = null;
  try {
    response = ClientBuilder.newClient()
      .target(url + "/security/rest/v1/componentTypes")
      .register(new CsrfProtectionFilter("CSRF"))
      .request()
      .header(SSOConstants.X_USER_AUTH_TOKEN, userAuthToken)
      .get();
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
      String componentTypesStr = response.readEntity(String.class);
      return componentTypesStr.contains(componentType);
    }
  } finally {
    if (response != null) {
      response.close();
    }
  }
  return false;
}
 
Example 5
Source File: HttpSBControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public int put(DeviceId device, String request, InputStream payload, MediaType mediaType) {

    WebTarget wt = getWebTarget(device, request);

    Response response = null;
    if (payload != null) {
        try {
            response = wt.request(mediaType).put(Entity.entity(IOUtils.
                    toString(payload, StandardCharsets.UTF_8), mediaType));
        } catch (IOException e) {
            log.error("Cannot do PUT {} request on device {} because can't read payload", request, device);
        }
    } else {
        response = wt.request(mediaType).put(Entity.entity(null, mediaType));
    }

    if (response == null) {
        return Status.NO_CONTENT.getStatusCode();
    }
    return response.getStatus();
}
 
Example 6
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testDeleteMovie() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();
    moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId());

    if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
        System.out.println(moviesResponse.readEntity(String.class));
        throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus());
    }

    moviesResponse.close();
    System.out.println("Response Code: " + moviesResponse.getStatus());
}
 
Example 7
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Get list of workspaces from geoserver
 */
public Response getWorkspaces() {
  final Response resp = getWebTarget().path("rest/workspaces.json").request().get();

  if (resp.getStatus() == Status.OK.getStatusCode()) {
    resp.bufferEntity();

    // get the workspace names
    final JSONArray workspaceArray =
        getArrayEntryNames(
            JSONObject.fromObject(resp.readEntity(String.class)),
            "workspaces",
            "workspace");

    final JSONObject workspacesObj = new JSONObject();
    workspacesObj.put("workspaces", workspaceArray);

    return Response.ok(workspacesObj.toString(defaultIndentation)).build();
  }

  return resp;
}
 
Example 8
Source File: CrossRealmPermissionsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void expectNotFound(PermissionsTest.InvocationWithResponse invocation, RealmResource realm) {
    int statusCode = 0;
    try {
        AtomicReference<Response> responseReference = new AtomicReference<>();
        invocation.invoke(realm, responseReference);
        Response response = responseReference.get();
        if (response != null) {
            statusCode = response.getStatus();
        } else {
            fail("Expected failure");
        }
    } catch (ClientErrorException e) {
        statusCode = e.getResponse().getStatus();
    }

    assertEquals(404, statusCode);
}
 
Example 9
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Add a style to geoserver
 */
public Response addStyle(final String styleName, final InputStream fileInStream) {

  final Response addStyleResponse =
      getWebTarget().path("rest/styles").request().post(
          Entity.entity(
              "{'style':{'name':'" + styleName + "','filename':'" + styleName + ".sld'}}",
              MediaType.APPLICATION_JSON));
  // Return the reponse if this style is not correctly created. This
  // method actually makes 2 rest calls to GeoServer
  if (addStyleResponse.getStatus() != Status.CREATED.getStatusCode()) {
    return addStyleResponse;
  }
  return getWebTarget().path("rest/styles/" + styleName).request().put(
      Entity.entity(fileInStream, "application/vnd.ogc.sld+xml"));
}
 
Example 10
Source File: LedgerService.java    From pay-publicapi with MIT License 6 votes vote down vote up
public SearchRefundsResponseFromLedger searchRefunds(Account account, Map<String, String> paramsAsMap) {

        paramsAsMap.put(PARAM_ACCOUNT_ID, account.getAccountId());
        paramsAsMap.put(PARAM_TRANSACTION_TYPE, REFUND_TRANSACTION_TYPE);

        Response response = client
                .target(ledgerUriGenerator.transactionsURIWithParams(paramsAsMap))
                .request()
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get();

        if (response.getStatus() == SC_OK) {
            try {
                return response.readEntity(SearchRefundsResponseFromLedger.class);
            } catch (ProcessingException exception) {
                throw new SearchRefundsException(exception);
            }
        }

        throw new SearchRefundsException(response);
    }
 
Example 11
Source File: OpenstackVtapNetworkWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the results of the REST API POST method with creating new vtap network operation.
 */
@Test
public void testCreateVtapNetworkWithCreateOperation() {
    expect(mockVtapService.createVtapNetwork(anyObject(), anyObject(), anyObject()))
            .andReturn(vtapNetwork).once();
    replay(mockVtapService);

    final WebTarget wt = target();
    InputStream jsonStream = OpenstackVtapNetworkWebResourceTest.class
            .getResourceAsStream("openstack-vtap-config.json");
    Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(jsonStream));
    final int status = response.getStatus();

    assertThat(status, is(200));

    verify(mockVtapService);
}
 
Example 12
Source File: NativeApiV1ServiceImpl.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
@Override
public EchoRes echoPost() throws MipsException {
	try {
		EchoReq req = new EchoReq(merchantId);
		cryptoService.createSignature(req);
		Response response = nativeApiV1Resource.echo(req);
		if (response == null || response.getStatus() != 200) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "No response from nativeAPI for echo (POST) operation, http response " + (response != null ? response.getStatus() : "--")); 
		}
		EchoRes res = response.readEntity(EchoRes.class);
		if (!cryptoService.isSignatureValid(res)) {
			throw new MipsException(RespCode.INTERNAL_ERROR, "Invalid signature for response " + res.toJson()); 
		}
		return res;
	} 
	catch (Exception e) {
		throw new MipsException(RespCode.INTERNAL_ERROR, "nativeAPI call for echo (POST) operation failed: ", e); 
	}
}
 
Example 13
Source File: OpenstackSecurityGroupRuleWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the results of the REST API DELETE with non-existing security group rule ID.
 */
@Test
public void testDeleteSecurityGroupRuleWithNonexistId() {
    expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
    replay(mockOpenstackHaService);
    mockOpenstackSecurityGroupAdminService.removeSecurityGroupRule(anyString());
    expectLastCall().andThrow(new IllegalArgumentException());
    replay(mockOpenstackSecurityGroupAdminService);

    final WebTarget wt = target();

    Response response = wt.path(PATH + "/non-exist-id")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .delete();
    final int status = response.getStatus();

    assertThat(status, is(400));

    verify(mockOpenstackSecurityGroupAdminService);
}
 
Example 14
Source File: RestUtil.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
  * Throw common exceptions.
  * @param responseWithStatus response
  * @throws NotFoundException error 404
  * @throws LoadBalancerTimeoutException timeout error
  */
public static void throwCommonExceptions(Response responseWithStatus)
		throws NotFoundException, LoadBalancerTimeoutException {
	if (responseWithStatus.getStatus() == Status.NOT_FOUND.getStatusCode()) {
		throw new NotFoundException();
	} else if (responseWithStatus.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
		throw new LoadBalancerTimeoutException("Timout waiting for Store.", Service.AUTH);
	}
}
 
Example 15
Source File: ShopifyErrorResponseException.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
public ShopifyErrorResponseException(final Response response) {
	super(buildMessage(response));
	response.bufferEntity();
	this.responseBody = response.readEntity(String.class);
	this.shopifyErrorCodes = ShopifyErrorCodeFactory.create(responseBody);
	this.statusCode = response.getStatus();
}
 
Example 16
Source File: RealmsConfigurationLoader.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Response response = admin().realms().realm(realm.getRealm()).clients().create(client);
    response.close();

    if (response.getStatus() == 409 && ignoreConflicts) {
        log.warn("Ignoring conflict when creating a client: " + client.getClientId());
        client = admin().realms().realm(realm.getRealm()).clients().findByClientId(client.getClientId()).get(0);
    } else if (response.getStatus() == 201) {
        client.setId(extractIdFromResponse(response));
    } else {
        throw new RuntimeException("Failed to create client with status: " + response.getStatusInfo().getReasonPhrase());
    }
    clientIdMap.put(client.getClientId(), client.getId());
}
 
Example 17
Source File: CancelPaymentService.java    From pay-publicapi with MIT License 5 votes vote down vote up
public Response cancel(Account account, String chargeId) {
    Response connectorResponse = client
            .target(connectorUriGenerator.cancelURI(account, chargeId))
            .request()
            .post(null);

    if (connectorResponse.getStatus() == HttpStatus.SC_NO_CONTENT) {
        connectorResponse.close();
        return Response.noContent().build();
    }

    throw new CancelChargeException(connectorResponse);
}
 
Example 18
Source File: EndpointTest.java    From microservices-traffic-management-using-istio with Apache License 2.0 5 votes vote down vote up
public void testEndpoint(String endpoint, String expectedOutput) {
    String port = System.getProperty("liberty.test.port");
    String war = System.getProperty("war.name");
    String url = "http://localhost:" + port + "/" + war + endpoint;
    System.out.println("Testing " + url);
    Response response = sendRequest(url, "GET");
    int responseCode = response.getStatus();
    assertTrue("Incorrect response code: " + responseCode,
               responseCode == 200);
    
    String responseString = response.readEntity(String.class);
    response.close();
    assertTrue("Incorrect response, response is " + responseString, responseString.contains(expectedOutput));
}
 
Example 19
Source File: MetricsEventRunnable.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void sendUpdate(List<SDCMetricsJson> sdcMetricsJsonList) {
  int delaySecs = 1;
  int attempts = 0;
  while (attempts < retryAttempts || retryAttempts == -1) {
    if (attempts > 0) {
      delaySecs = delaySecs * 2;
      delaySecs = Math.min(delaySecs, 60);
      LOG.warn("Post attempt '{}', waiting for '{}' seconds before retrying ...",
          attempts, delaySecs);
      sleep(delaySecs);
    }
    attempts++;
    Response response = null;
    try {
      response = webTarget.request()
          .header(SSOConstants.X_REST_CALL, SSOConstants.SDC_COMPONENT_NAME)
          .header(SSOConstants.X_APP_AUTH_TOKEN, runtimeInfo.getAppAuthToken().replaceAll("(\\r|\\n)", ""))
          .header(SSOConstants.X_APP_COMPONENT_ID, runtimeInfo.getId())
          .post(
              Entity.json(
                  sdcMetricsJsonList
              )
          );
      if (response.getStatus() == HttpURLConnection.HTTP_OK) {
        LOG.trace("Sending metrics was successful");
        return;
      } else if (response.getStatus() == HttpURLConnection.HTTP_UNAVAILABLE) {
        LOG.warn("Error writing to time-series app: Control Hub unavailable");
        // retry
      } else if (response.getStatus() == HttpURLConnection.HTTP_FORBIDDEN) {
        // no retry in this case
        String errorResponseMessage = response.readEntity(String.class);
        LOG.error(Utils.format("Error writing to Control Hub: {}", errorResponseMessage));
        return;
      } else {
        String responseMessage = response.readEntity(String.class);
        LOG.error(Utils.format("Error writing to Control Hub: {}", responseMessage));
        //retry
      }
    } catch (Exception ex) {
      LOG.error(Utils.format("Error writing to Control Hub: {}", ex.toString(), ex));
      // retry
    } finally {
      if (response != null) {
        response.close();
      }
    }
  }

  // no success after retry
  LOG.warn("Unable to write metrics to Control Hub after {} attempts", retryAttempts);
}
 
Example 20
Source File: AgentRequestManager.java    From Baragon with Apache License 2.0 4 votes vote down vote up
private AgentBatchResponseItem getResponseItem(Response httpResponse, BaragonRequestBatchItem item) {
  Optional<String> maybeMessage = httpResponse.getEntity() != null ? Optional.of(httpResponse.getEntity().toString()) : Optional.<String>absent();
  return new AgentBatchResponseItem(item.getRequestId(), httpResponse.getStatus(), maybeMessage, item.getRequestType());
}