Java Code Examples for org.springframework.web.client.HttpStatusCodeException

The following are top voted examples for showing how to use org.springframework.web.client.HttpStatusCodeException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: teamcity-hashicorp-vault-plugin   File: VaultTemplate.java   View source code 7 votes vote down vote up
@Override
public void delete(final String path) {

    Assert.hasText(path, "Path must not be empty");

    try {
        sessionTemplate.delete(path);
    } catch (HttpStatusCodeException e) {

        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return;
        }

        throw VaultResponses.buildException(e, path);
    }
}
 
Example 2
Project: loom   File: RolesUpdater.java   View source code 7 votes vote down vote up
@Override
protected List<JsonRole> getResourcesFromGet(final RestTemplate rt, final URI targetURI)
        throws HttpStatusCodeException, UpdaterHttpException {
    ResponseEntity<JsonRoles> resp = rt.getForEntity(targetURI, JsonRoles.class);
    if (resp != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("response is not null: " + resp.getStatusCode());
        }
        if (resp.getStatusCode() == HttpStatus.OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("response is OK");
            }
            return resp.getBody().getRoles();
        } else {
            throw new UpdaterHttpException(
                    "unable to collect roles - status code: " + resp.getStatusCode().toString());
        }
    } else {
        throw new UpdaterHttpException("unable to collect roles - HTTP response was null");
    }
}
 
Example 3
Project: loom   File: DomainsUpdater.java   View source code 7 votes vote down vote up
@Override
protected List<JsonDomain> getResourcesFromGet(final RestTemplate rt, final URI targetURI)
        throws HttpStatusCodeException, UpdaterHttpException {
    ResponseEntity<JsonDomains> resp = rt.getForEntity(targetURI, JsonDomains.class);
    if (resp != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("response is not null: " + resp.getStatusCode());
        }
        if (resp.getStatusCode() == HttpStatus.OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("response is OK");
            }
            return resp.getBody().getDomains();
        } else {
            throw new UpdaterHttpException(
                    "unable to collect domains - status code: " + resp.getStatusCode().toString());
        }
    } else {
        throw new UpdaterHttpException("unable to collect domains - HTTP response was null");
    }
}
 
Example 4
Project: spring-cloud-skipper   File: ManifestCommands.java   View source code 6 votes vote down vote up
@ShellMethod(key = "manifest get", value = "Get the manifest for a release")
public Object getManifest(
		@ShellOption(help = "release name") @NotNull String releaseName,
		@ShellOption(help = "specific release version.", defaultValue = NULL) Integer releaseVersion) {
	String manifest;
	try {
		if (releaseVersion == null) {
			manifest = this.skipperClient.manifest(releaseName);
		}
		else {
			manifest = this.skipperClient.manifest(releaseName, releaseVersion);
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			// 404 means release not found.
			// TODO it'd be nice to rethrow ReleaseNotFoundException in
			// SkipperClient but that exception is on server
			return "Release with name '" + releaseName + "' not found";
		}
		// if something else, rethrow
		throw e;
	}
	return manifest;
}
 
Example 5
Project: meparty   File: RestApiProxyInvocationHandler.java   View source code 6 votes vote down vote up
RestResponse<Object> doRestExchange(RestExchangeProperties properties)
    throws IOException, HttpStatusCodeException {

  ResponseEntity<String> responseEntity = restTemplate.exchange(properties.getUrl(),
      properties.getHttpMethod(), properties.getHttpEntity(),
      new ParameterizedTypeReference<String>() {
      }, properties.getUrlVariables());


  ObjectMapper objectMapper = new ObjectMapper();

  Object returnBody = null;
  if (!StringHelper.isNullOrEmpty(responseEntity.getBody())) {
    if (responseEntity.getBody().startsWith("[")) {
      returnBody = objectMapper.readValue(responseEntity.getBody(),
          objectMapper.getTypeFactory().constructCollectionType(List.class,
              properties.getReturnType()));
    } else {
      returnBody = objectMapper.readValue(responseEntity.getBody(), properties.getReturnType());
    }
  }
  RestResponse<Object> restResponse = new RestResponse<>(returnBody,
      responseEntity.getHeaders(),
      responseEntity.getStatusCode());

  return restResponse;
}
 
Example 6
Project: teamcity-hashicorp-vault-plugin   File: VaultTemplate.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> VaultResponseSupport<T> read(final String path, final Class<T> responseType) {

    final ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses
            .getTypeReference(responseType);

    try {
        ResponseEntity<VaultResponseSupport<T>> exchange = sessionTemplate.exchange(
                path, HttpMethod.GET, null, ref);

        return exchange.getBody();
    } catch (HttpStatusCodeException e) {

        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }

        throw VaultResponses.buildException(e, path);
    }
}
 
Example 7
Project: teamcity-hashicorp-vault-plugin   File: VaultTemplate.java   View source code 6 votes vote down vote up
private <T> T doRead(final String path, final Class<T> responseType) {

        return doWithSession(new RestOperationsCallback<T>() {

            @Override
            public T doWithRestOperations(RestOperations restOperations) {

                try {
                    return restOperations.getForObject(path, responseType);
                } catch (HttpStatusCodeException e) {

                    if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                        return null;
                    }

                    throw VaultResponses.buildException(e, path);
                }
            }
        });
    }
 
Example 8
Project: istio-by-example-java   File: GuestbookService.java   View source code 6 votes vote down vote up
public List<Map> all() {
  try {
    Map response = restTemplate.getForObject(endpoint, Map.class);

    Map embedded = (Map) response.get("_embedded");
    List<Map> messages = (List<Map>) embedded.get("messages");
    return messages.stream()
        .filter(message -> message.containsKey("_links"))
        .map(message -> (Map) message.get("_links"))
        .filter(links -> links.containsKey("self"))
        .map(links -> (Map) links.get("self"))
        .map(self -> (String) self.get("href"))
        .map(href -> restTemplate.getForObject(href, Map.class))
        .collect(Collectors.toList());
  } catch (HttpStatusCodeException e) {
    // Istio would've performed circuit breaking and retries
    // but it doesn't handle bulkheads / returning default values on full failures.
    log.error("Error from Guestbook Service, falling back", e);
    return allFallback();
  }
}
 
Example 9
Project: loom   File: RoleAssignmentsUpdater.java   View source code 6 votes vote down vote up
@Override
protected List<JsonRoleAssignment> getResourcesFromGet(final RestTemplate rt, final URI targetURI)
        throws HttpStatusCodeException, UpdaterHttpException {
    ResponseEntity<JsonRoleAssignments> resp = rt.getForEntity(targetURI, JsonRoleAssignments.class);
    if (resp != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("response is not null: " + resp.getStatusCode());
        }
        if (resp.getStatusCode() == HttpStatus.OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("response is OK");
            }
            return resp.getBody().getRoleAssignments();
        } else {
            throw new UpdaterHttpException(
                    "unable to collect roleAssigments - status code: " + resp.getStatusCode().toString());
        }
    } else {
        throw new UpdaterHttpException("unable to collect roleAssignments - HTTP response was null");
    }
}
 
Example 10
Project: loom   File: ProjectsUpdater.java   View source code 6 votes vote down vote up
@Override
protected List<JsonProject> getResourcesFromGet(final RestTemplate rt, final URI targetURI)
        throws HttpStatusCodeException, UpdaterHttpException {
    ResponseEntity<JsonProjects> resp = rt.getForEntity(targetURI, JsonProjects.class);
    if (resp != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("response is not null: " + resp.getStatusCode());
        }
        if (resp.getStatusCode() == HttpStatus.OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("response is OK");
            }
            return resp.getBody().getProjects();
        } else {
            throw new UpdaterHttpException(
                    "unable to collect projects - status code: " + resp.getStatusCode().toString());
        }
    } else {
        throw new UpdaterHttpException("unable to collect projects - HTTP response was null");
    }
}
 
Example 11
Project: loom   File: UsersUpdater.java   View source code 6 votes vote down vote up
@Override
protected List<JsonUser> getResourcesFromGet(final RestTemplate rt, final URI targetURI)
        throws HttpStatusCodeException, UpdaterHttpException {
    ResponseEntity<JsonUsers> resp = rt.getForEntity(targetURI, JsonUsers.class);
    if (resp != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("response is not null: " + resp.getStatusCode());
        }
        if (resp.getStatusCode() == HttpStatus.OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("response is OK");
            }
            return resp.getBody().getUsers();
        } else {
            throw new UpdaterHttpException(
                    "unable to collect users - status code: " + resp.getStatusCode().toString());
        }
    } else {
        throw new UpdaterHttpException("unable to collect users - HTTP response was null");
    }
}
 
Example 12
Project: apollo-custom   File: ControllerIntegrationExceptionTest.java   View source code 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
  AppDTO dto = generateSampleDTOData();

  when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));

  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  } catch (HttpStatusCodeException e) {
    @SuppressWarnings("unchecked")
    Map<String, String> attr = gson.fromJson(e.getResponseBodyAsString(), Map.class);
    Assert.assertEquals("save failed", attr.get("message"));
  }
  App savedApp = appService.findOne(dto.getAppId());
  Assert.assertNull(savedApp);
}
 
Example 13
Project: apollo   File: ControllerIntegrationExceptionTest.java   View source code 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
  AppDTO dto = generateSampleDTOData();

  when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));

  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  } catch (HttpStatusCodeException e) {
    @SuppressWarnings("unchecked")
    Map<String, String> attr = gson.fromJson(e.getResponseBodyAsString(), Map.class);
    Assert.assertEquals("save failed", attr.get("message"));
  }
  App savedApp = appService.findOne(dto.getAppId());
  Assert.assertNull(savedApp);
}
 
Example 14
Project: spring-vault   File: ClientCertificateAuthentication.java   View source code 6 votes vote down vote up
private VaultToken createTokenUsingTlsCertAuthentication(String path) {

		try {
			VaultResponse response = restOperations.postForObject("auth/{mount}/login",
					Collections.emptyMap(), VaultResponse.class, path);

			Assert.state(response.getAuth() != null, "Auth field must not be null");

			logger.debug("Login successful using TLS certificates");

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (HttpStatusCodeException e) {
			throw new VaultException(String.format(
					"Cannot login using TLS certificates: %s",
					VaultResponses.getError(e.getResponseBodyAsString())));
		}
	}
 
Example 15
Project: spring-vault   File: AppIdAuthentication.java   View source code 6 votes vote down vote up
private VaultToken createTokenUsingAppId() {

		Map<String, String> login = getAppIdLogin(options.getAppId(), options
				.getUserIdMechanism().createUserId());

		try {
			VaultResponse response = restOperations.postForObject("auth/{mount}/login",
					login, VaultResponse.class, options.getPath());

			Assert.state(response != null && response.getAuth() != null,
					"Auth field must not be null");

			logger.debug("Login successful using AppId authentication");

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (HttpStatusCodeException e) {
			throw new VaultException(String.format("Cannot login using app-id: %s",
					VaultResponses.getError(e.getResponseBodyAsString())));
		}
	}
 
Example 16
Project: spring-vault   File: CubbyholeAuthentication.java   View source code 6 votes vote down vote up
@Nullable
private Map<String, Object> lookupToken() {

	try {

		ResponseEntity<VaultResponse> entity = restOperations.exchange(
				options.getPath(), HttpMethod.GET,
				new HttpEntity<>(VaultHttpHeaders.from(options.getInitialToken())),
				VaultResponse.class);

		Assert.state(entity.getBody() != null, "Auth response must not be null");

		return entity.getBody().getData();
	}
	catch (HttpStatusCodeException e) {
		throw new VaultException(String.format(
				"Cannot retrieve Token from Cubbyhole: %s %s", e.getStatusCode(),
				VaultResponses.getError(e.getResponseBodyAsString())));
	}
}
 
Example 17
Project: spring-vault   File: LoginTokenAdapter.java   View source code 6 votes vote down vote up
private static Map<String, Object> lookupSelf(RestOperations restOperations,
		VaultToken token) {

	try {
		ResponseEntity<VaultResponse> entity = restOperations.exchange(
				"auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>(
						VaultHttpHeaders.from(token)), VaultResponse.class);

		Assert.state(entity.getBody() != null && entity.getBody().getData() != null,
				"Token response is null");

		return entity.getBody().getData();
	}
	catch (HttpStatusCodeException e) {
		throw new VaultTokenLookupException(String.format(
				"Token self-lookup failed: %s %s", e.getStatusCode(),
				VaultResponses.getError(e.getResponseBodyAsString())));
	}
}
 
Example 18
Project: spring-vault   File: AppRoleAuthentication.java   View source code 6 votes vote down vote up
private VaultToken createTokenUsingAppRole() {

		Map<String, String> login = getAppRoleLoginBody(options.getRoleId(),
				options.getSecretId());

		try {
			VaultResponse response = restOperations.postForObject("auth/{mount}/login",
					login, VaultResponse.class, options.getPath());

			Assert.state(response != null && response.getAuth() != null,
					"Auth field must not be null");

			logger.debug("Login successful using AppRole authentication");

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (HttpStatusCodeException e) {
			throw new VaultException(String.format("Cannot login using AppRole: %s",
					VaultResponses.getError(e.getResponseBodyAsString())));
		}
	}
 
Example 19
Project: spring-vault   File: VaultTemplate.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> VaultResponseSupport<T> read(final String path, final Class<T> responseType) {

	final ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses
			.getTypeReference(responseType);

	try {
		ResponseEntity<VaultResponseSupport<T>> exchange = sessionTemplate.exchange(
				path, HttpMethod.GET, null, ref);

		return exchange.getBody();
	}
	catch (HttpStatusCodeException e) {

		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return null;
		}

		throw VaultResponses.buildException(e, path);
	}
}
 
Example 20
Project: spring-vault   File: VaultTemplate.java   View source code 6 votes vote down vote up
@Override
public void delete(final String path) {

	Assert.hasText(path, "Path must not be empty");

	try {
		sessionTemplate.delete(path);
	}
	catch (HttpStatusCodeException e) {

		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return;
		}

		throw VaultResponses.buildException(e, path);
	}
}
 
Example 21
Project: spring-vault   File: VaultTemplate.java   View source code 6 votes vote down vote up
@Nullable
private <T> T doRead(final String path, final Class<T> responseType) {

	return doWithSession(restOperations -> {

		try {
			return restOperations.getForObject(path, responseType);
		}
		catch (HttpStatusCodeException e) {

			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				return null;
			}

			throw VaultResponses.buildException(e, path);
		}
	});
}
 
Example 22
Project: spring-vault   File: VaultSysTemplate.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public boolean isInitialized() {

	return requireResponse(vaultOperations.doWithVault(restOperations -> {

		try {
			Map<String, Boolean> body = restOperations.getForObject("sys/init",
					Map.class);

			Assert.state(body != null, "Initialization response must not be null");

			return body.get("initialized");
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	}));
}
 
Example 23
Project: spring-vault   File: VaultSysTemplate.java   View source code 6 votes vote down vote up
@Override
public VaultInitializationResponse initialize(
		final VaultInitializationRequest vaultInitializationRequest) {

	Assert.notNull(vaultInitializationRequest, "VaultInitialization must not be null");

	return requireResponse(vaultOperations.doWithVault(restOperations -> {

		try {
			ResponseEntity<VaultInitializationResponseImpl> exchange = restOperations
					.exchange("sys/init", HttpMethod.PUT, new HttpEntity<Object>(
							vaultInitializationRequest),
							VaultInitializationResponseImpl.class);

			Assert.state(exchange.getBody() != null,
					"Initialization response must not be null");

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	}));
}
 
Example 24
Project: spring-vault   File: VaultSysTemplate.java   View source code 6 votes vote down vote up
@Override
public VaultHealth doWithRestOperations(RestOperations restOperations) {

	try {
		ResponseEntity<VaultHealthImpl> healthResponse = restOperations.exchange(
				"sys/health", HttpMethod.GET, null, VaultHealthImpl.class);
		return healthResponse.getBody();
	}
	catch (HttpStatusCodeException responseError) {

		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readValue(responseError.getResponseBodyAsString(),
					VaultHealthImpl.class);
		}
		catch (Exception jsonError) {
			throw responseError;
		}
	}
}
 
Example 25
Project: spring-vault   File: VaultPkiTemplate.java   View source code 6 votes vote down vote up
private <T> T requestCertificate(String roleName, String requestPath,
		Map<String, Object> request, Class<T> responseType) {

	request.put("format", "der");

	T response = vaultOperations.doWithSession(restOperations -> {

		try {
			return restOperations.postForObject(requestPath, request, responseType,
					path, roleName);
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	});

	Assert.state(response != null, "VaultCertificateResponse must not be null");

	return response;
}
 
Example 26
Project: spring-vault   File: VaultPkiTemplate.java   View source code 6 votes vote down vote up
@Override
public void revoke(String serialNumber) throws VaultException {

	Assert.hasText(serialNumber, "Serial number must not be null or empty");

	vaultOperations.doWithSession(restOperations -> {

		try {
			restOperations.postForObject("{path}/revoke",
					Collections.singletonMap("serial_number", serialNumber),
					Map.class, path);

			return null;
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	});
}
 
Example 27
Project: spring-vault   File: VaultPkiTemplate.java   View source code 6 votes vote down vote up
@Override
public InputStream getCrl(Encoding encoding) throws VaultException {

	Assert.notNull(encoding, "Encoding must not be null");

	return vaultOperations.doWithSession(restOperations -> {

		String requestPath = encoding == Encoding.DER ? "{path}/crl"
				: "{path}/crl/pem";
		try {
			ResponseEntity<byte[]> response = restOperations.getForEntity(
					requestPath, byte[].class, path);

			return new ByteArrayInputStream(response.getBody());
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	});
}
 
Example 28
Project: spring-vault   File: VaultTokenTemplate.java   View source code 6 votes vote down vote up
private <T extends VaultResponseSupport<?>> T writeAndReturn(String path,
		@Nullable Object body, Class<T> responseType) {

	Assert.hasText(path, "Path must not be empty");

	T response = vaultOperations.doWithSession(restOperations -> {
		try {
			ResponseEntity<T> exchange = restOperations.exchange(path,
					HttpMethod.POST, body == null ? HttpEntity.EMPTY
							: new HttpEntity<>(body), responseType);

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e, path);
		}
	});

	Assert.state(response != null, "Response must not be null");

	return response;
}
 
Example 29
Project: spring-vault   File: VaultTokenTemplate.java   View source code 6 votes vote down vote up
private void write(String path, Class<?> responseType) {

		Assert.hasText(path, "Path must not be empty");

		vaultOperations.doWithSession(restOperations -> {

			try {
				restOperations.exchange(path, HttpMethod.POST, HttpEntity.EMPTY,
						responseType);
			}
			catch (HttpStatusCodeException e) {
				throw VaultResponses.buildException(e, path);
			}

			return null;
		});
	}
 
Example 30
Project: openlmis-stockmanagement   File: NotificationService.java   View source code 6 votes vote down vote up
/**
 * Send an email notification.
 *
 * @param user    receiver of the notification
 * @param subject subject of the email
 * @param content content of the email
 * @return true if success, false if failed.
 */
public boolean notify(UserDto user, String subject, String content) {
  NotificationRequest request = new NotificationRequest(
      from, user.getEmail(), subject, content
  );
  
  try {
    restTemplate.postForObject(
        RequestHelper.createUri(notificationUrl),
        RequestHelper.createEntity(authService.obtainAccessToken(),
            request),
        Object.class);
  } catch (HttpStatusCodeException ex) {
    logger.error(
        "Unable to send notification. Error code: {}, response message: {}",
        ex.getStatusCode(), ex.getResponseBodyAsString()
    );
    return false;
  }
  return true;
}
 
Example 31
Project: openlmis-stockmanagement   File: BaseReferenceDataService.java   View source code 6 votes vote down vote up
/**
 * Return one object from Reference data service.
 *
 * @param id UUID of requesting object.
 * @return Requesting reference data object.
 */
public T findOne(UUID id) {
  String url = getServiceUrl() + getUrl() + id;

  RestTemplate restTemplate = new RestTemplate();

  try {
    ResponseEntity<T> responseEntity = restTemplate.exchange(
        buildUri(url), HttpMethod.GET, createEntity(obtainAccessToken()),
        getResultClass());
    return responseEntity.getBody();
  } catch (HttpStatusCodeException ex) {
    // rest template will handle 404 as an exception, instead of returning null
    if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
      logger.warn("{} with id {} does not exist. ", getResultClass().getSimpleName(), id);
      return null;
    } else {
      throw buildDataRetrievalException(ex);
    }
  }
}
 
Example 32
Project: openlmis-stockmanagement   File: BaseReferenceDataService.java   View source code 6 votes vote down vote up
private Collection<T> findAllWithMethod(String resourceUrl, Map<String, Object> uriParameters,
                                        Map<String, Object> payload, HttpMethod method) {
  String url = getServiceUrl() + getUrl() + resourceUrl;
  RestTemplate restTemplate = new RestTemplate();

  Map<String, Object> params = new HashMap<>();
  params.putAll(uriParameters);

  try {
    ResponseEntity<T[]> responseEntity = restTemplate.exchange(buildUri(url, params),
        method, createEntity(obtainAccessToken(), payload),
        getArrayResultClass());

    return new ArrayList<>(Arrays.asList(responseEntity.getBody()));
  } catch (HttpStatusCodeException ex) {
    throw buildDataRetrievalException(ex);
  }
}
 
Example 33
Project: openlmis-stockmanagement   File: BaseCommunicationService.java   View source code 6 votes vote down vote up
protected <P> Page<P> getPage(String resourceUrl, Map<String, Object> parameters, Object payload,
                              HttpMethod method, Class<P> type) {
  String url = getServiceUrl() + getUrl() + resourceUrl;

  Map<String, Object> params = new HashMap<>();
  params.putAll(parameters);

  try {
    ResponseEntity<PageImplRepresentation<P>> response = restTemplate.exchange(
        buildUri(url, params),
        method,
        createEntity(obtainAccessToken(), payload),
        new DynamicPageTypeReference<>(type)
    );
    return response.getBody();

  } catch (HttpStatusCodeException ex) {
    throw buildDataRetrievalException(ex);
  }
}
 
Example 34
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: RemoteVehicleDetailsService.java   View source code 6 votes vote down vote up
@Override
public VehicleDetails getVehicleDetails(VehicleIdentificationNumber vin)
		throws VehicleIdentificationNumberNotFoundException {
	Assert.notNull(vin, "VIN must not be null");
	logger.debug("Retrieving vehicle data for: " + vin);
	try {
		return this.restTemplate.getForObject("/vehicle/{vin}/details",
				VehicleDetails.class, vin);
	}
	catch (HttpStatusCodeException ex) {
		if (HttpStatus.NOT_FOUND.equals(ex.getStatusCode())) {
			throw new VehicleIdentificationNumberNotFoundException(vin, ex);
		}
		throw ex;
	}
}
 
Example 35
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
@Override
public ServiceCallResult getStatistics(GetStatisticsArg arg) {
    Assert.notNull(arg.getId(), "id is null");
    URI url = getUrlContainer(arg.getId(), "stats").queryParam("stream", arg.isStream()).build().toUri();
    ServiceCallResult callResult = new ServiceCallResult();
    try {
        ListenableFuture<Object> future = restTemplate.execute(url, HttpMethod.GET, null, response -> {
            StreamContext<Statistics> context = new StreamContext<>(response.getBody(), arg.getWatcher());
            context.getInterrupter().setFuture(arg.getInterrupter());
            statisticsProcessor.processResponseStream(context);
            return null;
        });
        waitFuture(callResult, future);
    } catch (HttpStatusCodeException e) {
        processStatusCodeException(e, callResult, url);
    }
    return callResult;
}
 
Example 36
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
private <T> T postOrNullAction(UriComponentsBuilder ub, Object cmd, Class<T> responseType) {
    String url = ub.toUriString();
    try {
        ResponseEntity<T> entity = getSlow(() -> {
            HttpEntity<?> req = null;
            if(cmd != null) {
                req = wrapEntity(cmd);
            }
            return restTemplate.postForEntity(url, req, responseType);
        });
        return entity.getBody();
    } catch (HttpStatusCodeException e) {
        log.warn("Failed to execute POST on {}, due to {}", url, formatHttpException(e));
        if(e.getStatusCode().is4xxClientError()) {
            return null;
        }
        throw e;
    }
}
 
Example 37
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
private <T extends ServiceCallResult> T getAction(UriComponentsBuilder ub, Class<T> responseType, Supplier<T> factory) {
    if(factory == null) {
        factory = () -> BeanUtils.instantiate(responseType);
    }
    URI uri = ub.build().toUri();
    T resp;
    try {
        ResponseEntity<T> entity = getFast(() -> {
            return restTemplate.getForEntity(uri, responseType);
        });
        resp = entity.getBody();
        if(resp == null) {
            resp = factory.get();
        }
        resp.setCode(ResultCode.OK);
        return resp;
    } catch (HttpStatusCodeException e) {
        log.warn("Failed to execute GET on {}, due to {}", uri, e.toString());
        resp = factory.get();
        processStatusCodeException(e, resp, uri);
        return resp;
    }
}
 
Example 38
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
@Override
public ServiceCallResult subscribeToEvents(GetEventsArg arg) {
    ServiceCallResult callResult = new ServiceCallResult();
    UriComponentsBuilder ucb = makeUrl("events");
    if(arg.getSince() != null) {
        ucb.queryParam("since", arg.getSince());
    }
    if(arg.getUntil() != null) {
        ucb.queryParam("until", arg.getUntil());
    }
    URI uri = ucb.build().toUri();
    try {
        ListenableFuture<Object> future = restTemplate.execute(uri, HttpMethod.GET, null, response -> {
            online();// may be we need schedule it into another thread
            StreamContext<DockerEvent> context = new StreamContext<>(response.getBody(), arg.getWatcher());
            context.getInterrupter().setFuture(arg.getInterrupter());
            eventStreamProcessor.processResponseStream(context);
            return null;
        });
        waitFuture(callResult, future);
    } catch (HttpStatusCodeException e) {
        processStatusCodeException(e, callResult, uri);
    }
    return callResult;
}
 
Example 39
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
private void processStatusCodeException(HttpStatusCodeException e, ServiceCallResult res, URI uri) {
    setCode(e.getStatusCode(), res);
    String msg = null;
    try {
        if(MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
            objectMapper.reader().withValueToUpdate(res).readValue(e.getResponseBodyAsString());
            msg = res.getMessage();
        }
    } catch (Exception ex) {
        log.error("Can not process status code exception message.", ex);
    }
    // in some cases msg may be null on success reading value, but anyway we need to make non null value manually
    if(msg == null) {
        msg = formatHttpException(e);
        res.setMessage(msg);
    }
    // we log message as debug because consumer code must log error too, but with high level,
    // when we log it as warn then error will cause to many duplicate lines in log
    log.warn("Fail to execute '{}' due to error: {}", uri, msg);
}
 
Example 40
Project: haven-platform   File: DockerServiceImpl.java   View source code 6 votes vote down vote up
private ServiceCallResult stopBasedAction(String id, StopContainerArg arg, String action) {
    Assert.notNull(id, "id is null");
    UriComponentsBuilder ub = getUrlContainer(id, action);
    int time = arg.getTimeBeforeKill();
    if (time > 0) {
        ub.queryParam("t", time);
    }
    URI uri = ub.build().toUri();
    try {
        ResponseEntity<String> res = getSlow(() -> restTemplate.postForEntity(uri, null, String.class));
        return DockerUtils.getServiceCallResult(res);
    } catch (HttpStatusCodeException e) {
        log.warn("In {}, can't \"{}\" container: {}, code: {}, message: {}", getId(), action, id, e.getStatusCode(), e.getResponseBodyAsString());
        ServiceCallResult callResult = new ServiceCallResult();
        processStatusCodeException(e, callResult, uri);
        return callResult;
    }
}