Here are the examples of the java api org.springframework.http.HttpEntity taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1491 Examples
19
View Source File : CoordinatorManager.java
License : Eclipse Public License 1.0
Project Creator : zhaoqilong3031
License : Eclipse Public License 1.0
Project Creator : zhaoqilong3031
/**
* @author Zhao Junjian
*/
@Component
@Log4j
public clreplaced CoordinatorManager {
@Autowired
private RestTemplate restTemplate;
private static final HttpEnreplacedy<?> REQUEST_ENreplacedY;
static int count = 0;
static {
final HttpHeaders header = new HttpHeaders();
header.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON_UTF8));
header.setContentType(MediaType.APPLICATION_JSON_UTF8);
REQUEST_ENreplacedY = new HttpEnreplacedy<>(header);
}
@Retryable(value = { TccCoordinatorException.clreplaced }, maxAttempts = 5, backoff = @Backoff(value = 0))
public void retryConfirm(Participant participant) {
final ResponseEnreplacedy<String> response = restTemplate.exchange(participant.getUri(), HttpMethod.PUT, REQUEST_ENreplacedY, String.clreplaced);
count++;
if (count < 4 || response.getStatusCode() != HttpStatus.NO_CONTENT) {
throw new TccCoordinatorException("事务处理失败");
}
count = 0;
}
@Recover
public void recover(TccCoordinatorException e) {
System.out.println(e.getMessage());
}
public void confirm(TccCoordinatorRequest request) {
Preconditions.checkNotNull(request);
List<Participant> participants = request.getParticipants();
Preconditions.checkNotNull(participants);
try {
participants.forEach(participant -> retryConfirm(participant));
} catch (Exception e) {
log.error("调用失败,需人工参与", e);
}
}
public void cancel(TccCoordinatorRequest request) {
Preconditions.checkNotNull(request);
List<Participant> participants = request.getParticipants();
for (Participant participant : participants) {
try {
restTemplate.exchange(participant.getUri(), HttpMethod.DELETE, REQUEST_ENreplacedY, String.clreplaced);
} catch (Exception e) {
log.warn("撤销失败", e);
}
}
}
}
19
View Source File : DashboardRestConsumer.java
License : Apache License 2.0
Project Creator : yugabyte
License : Apache License 2.0
Project Creator : yugabyte
public String removeProductFromCart(String asin) {
String restURL = restUrlBase + "shoppingCart/removeProduct";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("asin", asin);
HttpEnreplacedy<MultiValueMap<String, String>> request = new HttpEnreplacedy<MultiValueMap<String, String>>(params, null);
ResponseEnreplacedy<String> rateResponse = restTemplate.exchange(restURL, HttpMethod.POST, request, new ParameterizedTypeReference<String>() {
});
String addProductJsonResponse = rateResponse.getBody();
return addProductJsonResponse;
}
19
View Source File : DashboardRestConsumer.java
License : Apache License 2.0
Project Creator : yugabyte
License : Apache License 2.0
Project Creator : yugabyte
public String showCart() {
String restURL = restUrlBase + "shoppingCart";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("userId", "1");
HttpEnreplacedy<MultiValueMap<String, String>> request = new HttpEnreplacedy<MultiValueMap<String, String>>(params, null);
ResponseEnreplacedy<String> rateResponse = restTemplate.exchange(restURL, HttpMethod.POST, request, new ParameterizedTypeReference<String>() {
});
String addProductJsonResponse = rateResponse.getBody();
return addProductJsonResponse;
}
19
View Source File : DashboardRestConsumer.java
License : Apache License 2.0
Project Creator : yugabyte
License : Apache License 2.0
Project Creator : yugabyte
public String checkout() {
String restURL = restUrlBase + "shoppingCart/checkout";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("userId", "1");
HttpEnreplacedy<MultiValueMap<String, String>> request = new HttpEnreplacedy<MultiValueMap<String, String>>(params, null);
ResponseEnreplacedy<String> rateResponse = restTemplate.exchange(restURL, HttpMethod.POST, request, new ParameterizedTypeReference<String>() {
});
String addProductJsonResponse = rateResponse.getBody();
return addProductJsonResponse;
}
19
View Source File : DashboardRestConsumer.java
License : Apache License 2.0
Project Creator : yugabyte
License : Apache License 2.0
Project Creator : yugabyte
public String addProductToCart(String asin) {
String restURL = restUrlBase + "shoppingCart/addProduct";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("asin", asin);
HttpEnreplacedy<MultiValueMap<String, String>> request = new HttpEnreplacedy<MultiValueMap<String, String>>(params, null);
ResponseEnreplacedy<String> rateResponse = restTemplate.exchange(restURL, HttpMethod.POST, request, new ParameterizedTypeReference<String>() {
});
String addProductJsonResponse = rateResponse.getBody();
return addProductJsonResponse;
}
19
View Source File : SampleUndertowApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void testCompression() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEnreplacedy<?> requestEnreplacedy = new HttpEnreplacedy<>(requestHeaders);
ResponseEnreplacedy<byte[]> enreplacedy = this.restTemplate.exchange("/", HttpMethod.GET, requestEnreplacedy, byte[].clreplaced);
replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.OK);
try (GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(enreplacedy.getBody()))) {
replacedertThat(StreamUtils.copyToString(inflater, StandardCharsets.UTF_8)).isEqualTo("Hello World");
}
}
19
View Source File : RestServiceImpl.java
License : Apache License 2.0
Project Creator : youseries
License : Apache License 2.0
Project Creator : youseries
public <T> ResponseEnreplacedy<T> post(String uri, Object obj, Clreplaced<T> responseClazz) {
if (obj == null) {
obj = "blank";
}
HttpEnreplacedy<Object> enreplacedy = null;
if (headers != null) {
enreplacedy = new HttpEnreplacedy<Object>(obj, headers);
} else {
enreplacedy = new HttpEnreplacedy<Object>(obj);
}
return template.postForEnreplacedy(baseUrl + uri, enreplacedy, responseClazz);
}
19
View Source File : CommonConfigRepositoryUnitTest.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
@Test
public void updateConfig() {
when(xmConfigProperties.getXmConfigUrl()).thenReturn("configUrl");
configRepository.updateConfigFullPath(new Configuration("path", "content"), "hash");
HttpEnreplacedy<Configuration> expected = new HttpEnreplacedy<>(new Configuration("path", "content"));
verify(restTemplate).exchange(eq("configUrl/api/private/config?oldConfigHash=hash"), eq(HttpMethod.PUT), refEq(expected), eq(Void.clreplaced));
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void updateConfig(String tenantName, String path, String content) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
exchangePut(tenantName, getServiceConfigUrl() + path, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void deleteConfig(String tenantName, String path) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(createAuthHeaders());
exchangeDelete(tenantName, getServiceConfigUrl() + path, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public String getConfigFullPath(String tenantName, String path) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(createAuthHeaders());
return exchangeGet(tenantName, xmConfigUrl + path, enreplacedy).getBody();
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void updateConfigFullPath(String tenantName, String fullPath, String content, String oldConfigHash) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
String path = toUrlWithOldHash(tenantName, xmConfigUrl + fullPath, oldConfigHash);
exchangePut(null, path, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void updateConfigFullPath(String tenantName, String fullPath, String content) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
exchangePut(tenantName, xmConfigUrl + fullPath, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void createConfig(String tenantName, String path, String content) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
exchangePost(tenantName, getServiceConfigUrl() + path, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void deleteConfigFullPath(String tenantName, String fullPath) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(createAuthHeaders());
exchangeDelete(tenantName, xmConfigUrl + fullPath, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void createConfigFullPath(String tenantName, String fullPath, String content) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
exchangePost(tenantName, xmConfigUrl + fullPath, enreplacedy);
}
19
View Source File : TenantConfigRepository.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
public void updateConfig(String tenantName, String path, String content, String oldConfigHash) {
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(content, createAuthHeaders());
String pathWithHash = toUrlWithOldHash(tenantName, getServiceConfigUrl() + path, oldConfigHash);
exchangePut(null, pathWithHash, enreplacedy);
}
19
View Source File : HttpRetryService.java
License : Apache License 2.0
Project Creator : Xlinlin
License : Apache License 2.0
Project Creator : Xlinlin
/**
* [简要描述]:formdata 获取请求Response<br/>
* [详细描述]:<br/>
*
* @param httpEnreplacedy :
* @param uri :
* @param responseType :
* @return org.springframework.http.ResponseEnreplacedy<T>
* xiaolinlin 2020/1/16 - 18:27
*/
@Retryable(value = SocketTimeoutException.clreplaced, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
public <T> ResponseEnreplacedy<T> postFormData(HttpEnreplacedy httpEnreplacedy, String uri, Clreplaced responseType) {
if (null != httpEnreplacedy && StringUtils.isNotBlank(uri) && null != responseType) {
return restTemplate.postForEnreplacedy(uri, httpEnreplacedy, responseType);
}
return null;
}
19
View Source File : OauthResourceTokenConfig.java
License : MIT License
Project Creator : xkcoding
License : MIT License
Project Creator : xkcoding
/**
* 本地没有公钥的时候,从服务器上获取
* 需要进行 Basic 认证
*
* @return public key
*/
private String getKeyFromAuthorizationServer() {
ObjectMapper objectMapper = new ObjectMapper();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<>(null, httpHeaders);
String pubKey = new RestTemplate().getForObject(resourceServerProperties.getJwt().getKeyUri(), String.clreplaced, requestEnreplacedy);
try {
JSONObject body = objectMapper.readValue(pubKey, JSONObject.clreplaced);
log.info("Get Key From Authorization Server.");
return body.getStr("value");
} catch (IOException e) {
log.error("Get public key error: {}", e.getMessage());
}
return null;
}
19
View Source File : KeycloakContextProvider.java
License : Apache License 2.0
Project Creator : VonDerBeck
License : Apache License 2.0
Project Creator : VonDerBeck
/**
* Refreshs an access token for the configured Keycloak client.
* @return the refreshed Keycloak context holding the access token
*/
private KeycloakContext refreshToken() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED);
HttpEnreplacedy<String> request = new HttpEnreplacedy<String>("client_id=" + keycloakConfiguration.getClientId() + "&client_secret=" + keycloakConfiguration.getClientSecret() + "&refresh_token=" + context.getRefreshToken() + "&grant_type=refresh_token", headers);
try {
ResponseEnreplacedy<String> response = restTemplate.postForEnreplacedy(keycloakConfiguration.getKeycloakIssuerUrl() + "/protocol/openid-connect/token", request, String.clreplaced);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdenreplacedyProviderException("Could not connect to " + keycloakConfiguration.getKeycloakIssuerUrl() + ": HTTP status code " + response.getStatusCodeValue());
}
JSONObject json = new JSONObject(response.getBody());
String accessToken = json.getString("access_token");
String tokenType = json.getString("token_type");
String refreshToken = json.getString("refresh_token");
long expiresInMillis = json.getLong("expires_in") * 1000;
return new KeycloakContext(accessToken, tokenType, expiresInMillis, refreshToken);
} catch (RestClientException rce) {
LOG.refreshTokenFailed(rce);
throw new IdenreplacedyProviderException("Unable to refresh access token from Keycloak server", rce);
} catch (JSONException je) {
LOG.refreshTokenFailed(je);
throw new IdenreplacedyProviderException("Unable to refresh access token from Keycloak server", je);
}
}
19
View Source File : KeycloakContextProvider.java
License : Apache License 2.0
Project Creator : VonDerBeck
License : Apache License 2.0
Project Creator : VonDerBeck
/**
* Requests an access token for the configured Keycloak client.
* @return new Keycloak context holding the access token
*/
private KeycloakContext openAuthorizationContext() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED);
HttpEnreplacedy<String> request = new HttpEnreplacedy<String>("client_id=" + keycloakConfiguration.getClientId() + "&client_secret=" + keycloakConfiguration.getClientSecret() + "&grant_type=client_credentials", headers);
try {
ResponseEnreplacedy<String> response = restTemplate.postForEnreplacedy(keycloakConfiguration.getKeycloakIssuerUrl() + "/protocol/openid-connect/token", request, String.clreplaced);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdenreplacedyProviderException("Could not connect to " + keycloakConfiguration.getKeycloakIssuerUrl() + ": HTTP status code " + response.getStatusCodeValue());
}
JSONObject json = new JSONObject(response.getBody());
String accessToken = json.getString("access_token");
String tokenType = json.getString("token_type");
String refreshToken = json.getString("refresh_token");
long expiresInMillis = json.getLong("expires_in") * 1000;
return new KeycloakContext(accessToken, tokenType, expiresInMillis, refreshToken);
} catch (RestClientException rce) {
LOG.requestTokenFailed(rce);
throw new IdenreplacedyProviderException("Unable to get access token from Keycloak server", rce);
} catch (JSONException je) {
LOG.requestTokenFailed(je);
throw new IdenreplacedyProviderException("Unable to get access token from Keycloak server", je);
}
}
19
View Source File : MultipartBodyBuilder.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Return a {@code MultiValueMap} with the configured parts.
*/
public MultiValueMap<String, HttpEnreplacedy<?>> build() {
MultiValueMap<String, HttpEnreplacedy<?>> result = new LinkedMultiValueMap<>(this.parts.size());
for (Map.Entry<String, List<DefaultPartBuilder>> entry : this.parts.entrySet()) {
for (DefaultPartBuilder builder : entry.getValue()) {
HttpEnreplacedy<?> enreplacedy = builder.build();
result.add(entry.getKey(), enreplacedy);
}
}
return result;
}
19
View Source File : OrderController.java
License : Apache License 2.0
Project Creator : ukihsoroy
License : Apache License 2.0
Project Creator : ukihsoroy
private void invokerAccountService(int orderMoney) {
String url = "http://127.0.0.1:18084/account";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("userId", USER_ID);
map.add("money", orderMoney + "");
HttpEnreplacedy<MultiValueMap<String, String>> request = new HttpEnreplacedy<MultiValueMap<String, String>>(map, headers);
ResponseEnreplacedy<String> response = restTemplate.postForEnreplacedy(url, request, String.clreplaced);
}
19
View Source File : GoogleCloudMetadataUtil.java
License : Apache License 2.0
Project Creator : ThalesGroup
License : Apache License 2.0
Project Creator : ThalesGroup
static void fetchGoogleCloudInstanceIdenreplacedy(URI endpoint) {
RestTemplate restTemplate;
restTemplate = new RestTemplate();
try {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Metadata-Flavor", "Google");
HttpEnreplacedy<?> httpEnreplacedy = new HttpEnreplacedy<>(headers);
ResponseEnreplacedy<GoogleCloudInstanceIdenreplacedy> response = restTemplate.exchange(endpoint, HttpMethod.GET, httpEnreplacedy, GoogleCloudInstanceIdenreplacedy.clreplaced);
googleCloudInstanceIdenreplacedy = response.getBody();
} catch (RuntimeException ignored) {
/*
ResourceAccessException will occur if RestTemplate cannot reach the endpoint. We'll just let the idenreplacedy stay null.
*/
}
}
19
View Source File : ScheduleMongodb.java
License : MIT License
Project Creator : tencentyun
License : MIT License
Project Creator : tencentyun
@Service
public clreplaced ScheduleMongodb {
private static final Logger logger = LoggerFactory.getLogger(ScheduleMongodb.clreplaced);
@Autowired
private MongoDbService mongoDbService;
private static User user = new User((long) 100, "mongodb-auto-test", 26, "man", "深圳");
private static User userUpdater = new User((long) 100, "mongodb-auto-test", 23, "girl", "上海");
private static HttpEnreplacedy<User> request = new HttpEnreplacedy<>(user);
@Scheduled(fixedDelayString = "${consumer.auto.test.interval:5000}")
public void doWork() throws InterruptedException, Exception {
mongoDbService.save(user);
findResult();
mongoDbService.update(userUpdater);
findResult();
mongoDbService.deleteById(100L);
}
private void findResult() {
User userById = mongoDbService.findById(100L);
logger.info("find user by id: {},result is: {}", 100, userById);
List<User> usersList = mongoDbService.findByName("mongodb-auto-test");
for (User user1 : usersList) {
logger.info("find user by name: {},result is: {}", "mongodb-auto-test", user1);
}
List<User> all = mongoDbService.findAll();
Iterator<User> iterator = all.iterator();
while (iterator.hasNext()) {
logger.info("find all, result is: {}", iterator.next());
}
}
}
19
View Source File : AppRoleAuthenticationIntegrationTestBase.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
VaultToken generateWrappedSecretIdResponse() {
return getVaultOperations().doWithVault(restOperations -> {
HttpEnreplacedy<String> httpEnreplacedy = getWrappingHeaders();
VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/secret-id", HttpMethod.PUT, httpEnreplacedy, VaultResponse.clreplaced).getBody();
return VaultToken.of(response.getWrapInfo().get("token"));
});
}
19
View Source File : AppRoleAuthenticationIntegrationTestBase.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
VaultToken generateWrappedRoleIdResponse() {
return getVaultOperations().doWithVault(restOperations -> {
HttpEnreplacedy<String> httpEnreplacedy = getWrappingHeaders();
VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/role-id", HttpMethod.GET, httpEnreplacedy, VaultResponse.clreplaced).getBody();
return VaultToken.of(response.getWrapInfo().get("token"));
});
}
19
View Source File : GcpComputeAuthentication.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
protected String signJwt() {
try {
Map<String, String> urlParameters = new LinkedHashMap<>();
urlParameters.put("serviceAccount", this.options.getServiceAccount());
urlParameters.put("audience", getAudience(this.options.getRole()));
urlParameters.put("format", "full");
HttpHeaders headers = getMetadataHttpHeaders();
HttpEnreplacedy<Object> enreplacedy = new HttpEnreplacedy<>(headers);
ResponseEnreplacedy<String> response = this.googleMetadataRestOperations.exchange(COMPUTE_METADATA_URL_TEMPLATE, HttpMethod.GET, enreplacedy, String.clreplaced, urlParameters);
return response.getBody();
} catch (HttpStatusCodeException e) {
throw new VaultLoginException("Cannot obtain signed idenreplacedy", e);
}
}
19
View Source File : AzureMsiAuthentication.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
/**
* Azure MSI (Managed Service Idenreplacedy) authentication using Azure as trusted third party.
* <p>
* Azure MSI authentication uses {@link AzureVmEnvironment} and the MSI OAuth2 token
* (referenced as JWT token in Vault docs) to log into Vault. VM environment and OAuth2
* token are fetched from the Azure Instance Metadata service. Instances of this clreplaced are
* immutable once constructed.
*
* @author Mark Paluch
* @since 2.1
* @see AzureMsiAuthenticationOptions
* @see RestOperations
* @see <a href="https://www.vaultproject.io/docs/auth/azure.html">Auth Backend: azure</a>
* @link <a href=
* "https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service"
* >Azure Instance Metadata service</a>
*/
public clreplaced AzureMsiAuthentication implements ClientAuthentication {
private static final Log logger = LogFactory.getLog(AzureMsiAuthentication.clreplaced);
private static final HttpEnreplacedy<Void> METADATA_HEADERS;
static {
HttpHeaders headers = new HttpHeaders();
headers.add("Metadata", "true");
METADATA_HEADERS = new HttpEnreplacedy<>(headers);
}
private final AzureMsiAuthenticationOptions options;
private final RestOperations vaultRestOperations;
private final RestOperations azureMetadataRestOperations;
/**
* Create a new {@link AzureMsiAuthentication}.
* @param options must not be {@literal null}.
* @param restOperations must not be {@literal null}.
*/
public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, RestOperations restOperations) {
this(options, restOperations, restOperations);
}
/**
* Create a new {@link AzureMsiAuthentication} specifying
* {@link AzureMsiAuthenticationOptions}, a Vault and an Azure-Metadata-specific
* {@link RestOperations}.
* @param options must not be {@literal null}.
* @param vaultRestOperations must not be {@literal null}.
* @param azureMetadataRestOperations must not be {@literal null}.
*/
public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, RestOperations vaultRestOperations, RestOperations azureMetadataRestOperations) {
replacedert.notNull(options, "AzureAuthenticationOptions must not be null");
replacedert.notNull(vaultRestOperations, "Vault RestOperations must not be null");
replacedert.notNull(azureMetadataRestOperations, "Azure Instance Metadata RestOperations must not be null");
this.options = options;
this.vaultRestOperations = vaultRestOperations;
this.azureMetadataRestOperations = azureMetadataRestOperations;
}
/**
* Creates a {@link AuthenticationSteps} for Azure authentication given
* {@link AzureMsiAuthenticationOptions}.
* @param options must not be {@literal null}.
* @return {@link AuthenticationSteps} for Azure authentication.
*/
public static AuthenticationSteps createAuthenticationSteps(AzureMsiAuthenticationOptions options) {
replacedert.notNull(options, "AzureMsiAuthenticationOptions must not be null");
return createAuthenticationSteps(options, options.getVmEnvironment());
}
protected static AuthenticationSteps createAuthenticationSteps(AzureMsiAuthenticationOptions options, @Nullable AzureVmEnvironment environment) {
Node<String> msiToken = AuthenticationSteps.fromHttpRequest(HttpRequestBuilder.get(options.getIdenreplacedyTokenServiceUri()).with(METADATA_HEADERS).as(//
Map.clreplaced)).map(token -> (String) token.get("access_token"));
Node<AzureVmEnvironment> environmentSteps;
if (environment == null) {
environmentSteps = AuthenticationSteps.fromHttpRequest(HttpRequestBuilder.get(options.getInstanceMetadataServiceUri()).with(METADATA_HEADERS).as(//
Map.clreplaced)).map(AzureMsiAuthentication::toAzureVmEnvironment);
} else {
environmentSteps = AuthenticationSteps.fromValue(environment);
}
return environmentSteps.zipWith(msiToken).map(//
tuple -> getAzureLogin(options.getRole(), tuple.getLeft(), tuple.getRight())).login(AuthenticationUtil.getLoginPath(options.getPath()));
}
@Override
public VaultToken login() throws VaultException {
return createTokenUsingAzureMsiCompute();
}
private VaultToken createTokenUsingAzureMsiCompute() {
Map<String, String> login = getAzureLogin(this.options.getRole(), getVmEnvironment(), getAccessToken());
try {
VaultResponse response = this.vaultRestOperations.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.clreplaced);
replacedert.state(response != null && response.getAuth() != null, "Auth field must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Login successful using Azure authentication");
}
return LoginTokenUtil.from(response.getAuth());
} catch (RestClientException e) {
throw VaultLoginException.create("Azure", e);
}
}
private static Map<String, String> getAzureLogin(String role, AzureVmEnvironment vmEnvironment, String jwt) {
Map<String, String> loginBody = new LinkedHashMap<>();
loginBody.put("role", role);
loginBody.put("jwt", jwt);
loginBody.put("subscription_id", vmEnvironment.getSubscriptionId());
loginBody.put("resource_group_name", vmEnvironment.getResourceGroupName());
loginBody.put("vm_name", vmEnvironment.getVmName());
loginBody.put("vmss_name", vmEnvironment.getVmScaleSetName());
return loginBody;
}
private String getAccessToken() {
ResponseEnreplacedy<Map> response = this.azureMetadataRestOperations.exchange(this.options.getIdenreplacedyTokenServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.clreplaced);
return (String) response.getBody().get("access_token");
}
private AzureVmEnvironment getVmEnvironment() {
AzureVmEnvironment vmEnvironment = this.options.getVmEnvironment();
return vmEnvironment != null ? vmEnvironment : fetchAzureVmEnvironment();
}
private AzureVmEnvironment fetchAzureVmEnvironment() {
ResponseEnreplacedy<Map> response = this.azureMetadataRestOperations.exchange(this.options.getInstanceMetadataServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.clreplaced);
return toAzureVmEnvironment(response.getBody());
}
@SuppressWarnings("unchecked")
private static AzureVmEnvironment toAzureVmEnvironment(Map<String, Object> instanceMetadata) {
Map<String, String> compute = (Map) instanceMetadata.get("compute");
String subscriptionId = compute.get("subscriptionId");
String resourceGroupName = compute.get("resourceGroupName");
String vmName = compute.get("name");
String vmScaleSetName = compute.get("vmScaleSetName");
return new AzureVmEnvironment(subscriptionId, resourceGroupName, vmName, vmScaleSetName);
}
}
19
View Source File : SecretManagerSampleTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
public void testCreateReadSecret() {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("secretId", "secret-manager-sample-secret");
params.add("projectId", "");
params.add("secretPayload", "12345");
HttpEnreplacedy<MultiValueMap<String, Object>> request = new HttpEnreplacedy<>(params, new HttpHeaders());
ResponseEnreplacedy<String> response = this.testRestTemplate.postForEnreplacedy("/createSecret", request, String.clreplaced);
replacedertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
response = this.testRestTemplate.getForEnreplacedy("/getSecret?secretId=secret-manager-sample-secret", String.clreplaced);
replacedertThat(response.getBody()).contains("Secret ID: secret-manager-sample-secret | Value: 12345");
}
19
View Source File : SecretManagerSampleTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
public void testDeleteSecret() {
secretManagerTemplate.createSecret(SECRET_TO_DELETE, "test");
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("secretId", SECRET_TO_DELETE);
params.add("projectId", "");
HttpEnreplacedy<MultiValueMap<String, Object>> request = new HttpEnreplacedy<>(params, new HttpHeaders());
ResponseEnreplacedy<String> response = this.testRestTemplate.postForEnreplacedy("/deleteSecret", request, String.clreplaced);
replacedertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
}
19
View Source File : SourceControlEvent.java
License : Apache License 2.0
Project Creator : societe-generale
License : Apache License 2.0
Project Creator : societe-generale
@Data
public abstract clreplaced SourceControlEvent {
HttpEnreplacedy<String> rawMessage;
Repository repository;
}
19
View Source File : ClientCallbackController.java
License : MIT License
Project Creator : smltq
License : MIT License
Project Creator : smltq
@RequestMapping("/client/account/redirect")
public String getToken(@RequestParam String code) {
log.info("receive code {}", code);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "authorization_code");
params.add("code", code);
params.add("client_id", "client1");
params.add("client_secret", "secret");
params.add("redirect_uri", "http://localhost:8081/client/account/redirect");
HttpEnreplacedy<MultiValueMap<String, String>> requestEnreplacedy = new HttpEnreplacedy<>(params, headers);
ResponseEnreplacedy<String> response = restTemplate.postForEnreplacedy("http://localhost:8080/oauth/token", requestEnreplacedy, String.clreplaced);
String token = response.getBody();
log.info("token => {}", token);
return token;
}
19
View Source File : ImporterService.java
License : Apache License 2.0
Project Creator : skalogs
License : Apache License 2.0
Project Creator : skalogs
public SimulateData captureFromText(PayloadTextForReadOutput payloadTextForReadOutput) {
RestTemplate restTemplate = new RestTemplate();
HttpEnreplacedy<PayloadTextForReadOutput> request = new HttpEnreplacedy<>(payloadTextForReadOutput);
SimulateData objStatus = new SimulateData();
try {
objStatus = restTemplate.postForObject(importerConfiguration.getFullUrlSimulate() + "/manage/readOutputFromText", request, SimulateData.clreplaced);
return objStatus;
} catch (Exception e) {
log.error("status {}", e);
}
return objStatus;
}
19
View Source File : GateWayController.java
License : Apache License 2.0
Project Creator : Saseke
License : Apache License 2.0
Project Creator : Saseke
public String curUser(HttpEnreplacedy enreplacedy) {
UsernamePreplacedwordAuthenticationToken token = (UsernamePreplacedwordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
return (String) token.getPrincipal();
}
19
View Source File : UserClient.java
License : MIT License
Project Creator : rieckpil
License : MIT License
Project Creator : rieckpil
public User getSingleUser(Long id) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEnreplacedy<Void> requestEnreplacedy = new HttpEnreplacedy<>(headers);
return this.restTemplate.exchange("/api/users/{id}", HttpMethod.GET, requestEnreplacedy, User.clreplaced, id).getBody();
}
19
View Source File : AbstractOpenApiGeneratorWebIntTest.java
License : Apache License 2.0
Project Creator : qaware
License : Apache License 2.0
Project Creator : qaware
protected ResponseEnreplacedy<String> getResponseEnreplacedy(String path, HttpHeaders requestHeaders) {
HttpEnreplacedy<Void> enreplacedy = new HttpEnreplacedy<>(null, requestHeaders);
return testRestTemplate.exchange(buildHost() + path, HttpMethod.GET, enreplacedy, String.clreplaced);
}
19
View Source File : ZwitscherControllerTest.java
License : MIT License
Project Creator : qaware
License : MIT License
Project Creator : qaware
@Test
public void tweets() throws Exception {
ZwitscherRepository repository = mock(ZwitscherRepository.clreplaced);
ZwitscherController controller = new ZwitscherController(repository);
controller.setQuery("cloudnativenerd");
controller.setPageSize(42);
when(repository.search("cloudnativenerd", 42)).thenReturn(Collections.singleton("Hello Test."));
HttpEnreplacedy<Collection<String>> tweets = controller.tweets(null);
replacedertFalse(tweets.getBody().isEmpty());
}
19
View Source File : OAuth2ResourceServer.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
@Bean
public String getSignKey() {
RestTemplate keyUriRestTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
String username = this.resource.getClientId();
String preplacedword = this.resource.getClientSecret();
if (username != null && preplacedword != null) {
byte[] token = Base64.getEncoder().encode((username + ":" + preplacedword).getBytes());
headers.add("Authorization", "Basic " + new String(token));
}
HttpEnreplacedy<Void> request = new HttpEnreplacedy<>(headers);
String url = this.resource.getJwt().getKeyUri();
return (String) keyUriRestTemplate.exchange(url, HttpMethod.GET, request, Map.clreplaced).getBody().get("value");
}
19
View Source File : GeolocationProxyController.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
@RequestMapping(path = "", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String create(@RequestBody String body) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<String>(body, headers);
return restTemplate.exchange("http://geolocation/geolocation", HttpMethod.POST, enreplacedy, String.clreplaced).getBody();
}
19
View Source File : GeolocationProxyController.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
@RequestMapping(path = "", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String create(@RequestBody String body) throws Exception {
URI serviceUri = ZookeeperServiceDiscovery.getGeolocationServiceUri();
System.out.println("Proxying POST request to service " + serviceUri.toString() + " at path " + request.getRequestURI());
URI uri = new URI(serviceUri.getScheme(), null, serviceUri.getHost(), serviceUri.getPort(), request.getRequestURI(), request.getQueryString(), null);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<String>(body, headers);
return restTemplate.exchange(uri, HttpMethod.POST, enreplacedy, String.clreplaced).getBody();
}
19
View Source File : UserServiceInstanceService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public List getAll(String name) {
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaders(null);
String url = propertiesUtil.getApiServiceInstances();
ParameterizedTypeReference<ServiceInstanceList> responseType = new ParameterizedTypeReference<ServiceInstanceList>() {
};
ResponseEnreplacedy<List> response = restClientUtil.callRestApi(HttpMethod.GET, url + "/user?createUserId=" + name, enreplacedy, List.clreplaced);
logger.debug("response ::: " + response);
List serviceInstancesList = response.getBody();
return serviceInstancesList;
}
19
View Source File : UserServiceInstanceService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public List getAll(String instanceId, String userId) {
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaders(null);
String url = propertiesUtil.getApiAuth();
ParameterizedTypeReference<ServiceInstanceList> responseType = new ParameterizedTypeReference<ServiceInstanceList>() {
};
ResponseEnreplacedy<List> response = restClientUtil.callRestApi(HttpMethod.GET, url + "?instanceId=" + instanceId + "&userId=" + userId, enreplacedy, List.clreplaced);
logger.debug("response ::: " + response);
List serviceInstancesList = response.getBody();
return serviceInstancesList;
}
19
View Source File : UserServiceInstanceService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public InstanceUser createInstanceUser(InstanceUser instanceUser) {
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaders(instanceUser);
String url = propertiesUtil.getApiAuth();
ResponseEnreplacedy<InstanceUser> response = restClientUtil.callRestApi(HttpMethod.POST, url, enreplacedy, InstanceUser.clreplaced);
logger.debug("response ::: " + response);
InstanceUser rtnInstanceUser = response.getBody();
return rtnInstanceUser;
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy getUser(String name) {
String url = propertiesUtil.getApiUsersUser();
logger.debug("url >>>>>>>>>>>>" + url + name);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaders("");
return restClientUtil.callRestApi(HttpMethod.GET, url + name + ".json", enreplacedy, Object.clreplaced);
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy deleteInstanceUser(String instanceid, String name) {
String url = propertiesUtil.getApiUsers();
logger.debug("url >>>>>>>>>>>>" + url);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaderNotJson("");
ResponseEnreplacedy rss = restClientUtil.callRestApi(HttpMethod.DELETE, url + name + "/" + instanceid + "/", enreplacedy, Map.clreplaced);
return new ResponseEnreplacedy(rss.toString(), HttpStatus.OK);
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy deleteUser(String name) {
String url = propertiesUtil.getApiUsers();
logger.debug("url >>>>>>>>>>>>" + url);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaderNotJson("");
return restClientUtil.callRestApi(HttpMethod.DELETE, url + name, enreplacedy, Map.clreplaced);
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy createInstanceUser(Map map) {
String url = propertiesUtil.getApiServiceInstances();
logger.debug("url >>>>>>>>>>>>" + url);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaderNotJson(map);
return restClientUtil.callRestApi(HttpMethod.POST, url, enreplacedy, Map.clreplaced);
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy createUser(Map map) {
String url = propertiesUtil.getApiUsers();
logger.debug("url >>>>>>>>>>>>" + url);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaderNotJson(map);
return restClientUtil.callRestApi(HttpMethod.POST, url, enreplacedy, Map.clreplaced);
}
19
View Source File : UserService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
public ResponseEnreplacedy modifyUser(String name, Map map) {
try {
String url = propertiesUtil.getApiUsers();
logger.debug("url >>>>>>>>>>>>" + url);
HttpEnreplacedy<Object> enreplacedy = restClientUtil.restCommonHeaders(map);
return restClientUtil.callRestApi(HttpMethod.PUT, url + name + ".json", enreplacedy, Map.clreplaced);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEnreplacedy(e.toString(), HttpStatus.EXPECTATION_FAILED);
}
}
See More Examples