下面列出了java.util.concurrent.ConcurrentHashMap.KeySetView#com.google.api.client.http.HttpHeaders 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(expected = IOException.class)
public void execute_indexItemNotFound_notPushedToQueue_throwsIOException() throws Exception {
Item item = new Item().setName("id1").setAcl(getCustomerAcl());
RepositoryDoc doc = new RepositoryDoc.Builder().setItem(item).build();
doAnswer(
invocation -> {
SettableFuture<Operation> updateFuture = SettableFuture.create();
updateFuture.setException(
new GoogleJsonResponseException(
new HttpResponseException.Builder(
HTTP_NOT_FOUND, "not found", new HttpHeaders()),
new GoogleJsonError()));
return updateFuture;
})
.when(mockIndexingService)
.indexItem(item, RequestMode.UNSPECIFIED);
try {
doc.execute(mockIndexingService);
} finally {
InOrder inOrder = inOrder(mockIndexingService);
inOrder.verify(mockIndexingService).indexItem(item, RequestMode.UNSPECIFIED);
inOrder.verifyNoMoreInteractions();
assertEquals("id1", doc.getItem().getName());
}
}
/**
* Wrapper on {@link JsonBatchCallback#onFailure} to record failure while executing batched
* request.
*/
@Override
public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) {
if (event != null) {
event.failure();
event = null;
} else {
operationStats.event(request.requestToExecute.getClass().getName()).failure();
}
logger.log(Level.WARNING, "Request failed with error {0}", error);
if (request.retryPolicy.isRetryableStatusCode(error.getCode())) {
if (request.getRetries() < request.retryPolicy.getMaxRetryLimit()) {
request.setStatus(Status.RETRYING);
request.incrementRetries();
return;
}
}
GoogleJsonResponseException exception =
new GoogleJsonResponseException(
new Builder(error.getCode(), error.getMessage(), responseHeaders), error);
fail(exception);
}
/**
* Upload a file and attach it to a task
*
* @param task Globally unique identifier for the task.
* @param fileContent Content of the file to be uploaded
* @param fileName Name of the file to be uploaded
* @param fileType MIME type of the file to be uploaded
* @return Request object
*/
public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {
MultipartContent.Part part = new MultipartContent.Part()
.setContent(new InputStreamContent(fileType, fileContent))
.setHeaders(new HttpHeaders().set(
"Content-Disposition",
String.format("form-data; name=\"file\"; filename=\"%s\"", fileName) // TODO: escape fileName?
));
MultipartContent content = new MultipartContent()
.setMediaType(new HttpMediaType("multipart/form-data").setParameter("boundary", UUID.randomUUID().toString()))
.addPart(part);
String path = String.format("/tasks/%s/attachments", task);
return new ItemRequest<Attachment>(this, Attachment.class, path, "POST")
.data(content);
}
public static InputStream downloadObject(
Storage storage,
String bucketName,
String objectName,
String base64CseKey,
String base64CseKeyHash)
throws Exception {
// Set the CSEK headers
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("x-goog-encryption-algorithm", "AES256");
httpHeaders.set("x-goog-encryption-key", base64CseKey);
httpHeaders.set("x-goog-encryption-key-sha256", base64CseKeyHash);
Storage.Objects.Get getObject = storage.objects().get(bucketName, objectName);
getObject.setRequestHeaders(httpHeaders);
try {
return getObject.executeMediaAsInputStream();
} catch (GoogleJsonResponseException e) {
LOG.info("Error downloading: " + e.getContent());
System.exit(1);
return null;
}
}
@Test
public void shouldHandlePermissionDenied() throws IOException {
when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);
final GoogleJsonResponseException permissionDenied = new GoogleJsonResponseException(
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
new GoogleJsonError().set("status", "PERMISSION_DENIED"));
doThrow(permissionDenied).when(serviceAccountKeyManager).createJsonKey(any());
doThrow(permissionDenied).when(serviceAccountKeyManager).createP12Key(any());
exception.expect(InvalidExecutionException.class);
exception.expectMessage(String.format(
"Permission denied when creating keys for service account: %s. Styx needs to be Service Account Key Admin.",
SERVICE_ACCOUNT));
sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
/** Posts an RDF model to a Solid server. **/
public String postContent(
String url,
String slug,
String type,
Model model)
throws IOException {
StringWriter stringWriter = new StringWriter();
model.write(stringWriter, "TURTLE");
HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes());
HttpRequest postRequest = factory.buildPostRequest(
new GenericUrl(url), content);
HttpHeaders headers = new HttpHeaders();
headers.setCookie(authCookie);
headers.set("Link", "<" + type + ">; rel=\"type\"");
headers.set("Slug", slug);
postRequest.setHeaders(headers);
HttpResponse response = postRequest.execute();
validateResponse(response, 201);
return response.getHeaders().getLocation();
}
private void delete(String url) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept("text/turtle");
headers.setCookie(authCookie);
try {
HttpRequest deleteRequest = factory.buildDeleteRequest(new GenericUrl(url))
.setThrowExceptionOnExecuteError(false);
deleteRequest.setHeaders(headers);
validateResponse(deleteRequest.execute(), 200);
logger.debug("Deleted: %s", url);
} catch (IOException e) {
throw new IllegalStateException("Couldn't delete: " + url, e);
}
}
/**
* TODO(malcon): Consolidate GitHub and this one in one class
*/
private HttpRequestFactory getHttpRequestFactory(@Nullable UserPassword userPassword)
throws RepoException, ValidationException {
return httpTransport.createRequestFactory(
request -> {
request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
HttpHeaders httpHeaders = new HttpHeaders();
if (userPassword != null) {
httpHeaders.setBasicAuthentication(userPassword.getUsername(),
userPassword.getPassword_BeCareful());
}
request.setHeaders(httpHeaders);
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
}
@Override
public void initialize(HttpRequest request) throws IOException {
super.initialize(request);
HttpHeaders requestHeaders = request.getHeaders();
requestHeaders.setUserAgent(USER_AGENT);
if (!credentials.hasRequestMetadata()) {
return;
}
URI uri = null;
if (request.getUrl() != null) {
uri = request.getUrl().toURI();
}
Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata(uri);
if (credentialHeaders == null) {
return;
}
for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) {
String headerName = entry.getKey();
List<String> requestValues = new ArrayList<>(entry.getValue());
requestHeaders.put(headerName, requestValues);
}
}
@Test
public void testGenerateAndVerifyIapRequestIsSuccessful() throws Exception {
HttpRequest request =
httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(IAP_PROTECTED_URL));
HttpRequest iapRequest = BuildIapRequest.buildIapRequest(request, IAP_CLIENT_ID);
HttpResponse response = iapRequest.execute();
assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
String headerWithtoken = response.parseAsString();
String[] split = headerWithtoken.split(":");
assertNotNull(split);
assertEquals(2, split.length);
assertEquals("x-goog-authenticated-user-jwt", split[0].trim());
String jwtToken = split[1].trim();
HttpRequest verifyJwtRequest =
httpTransport
.createRequestFactory()
.buildGetRequest(new GenericUrl(IAP_PROTECTED_URL))
.setHeaders(new HttpHeaders().set("x-goog-iap-jwt-assertion", jwtToken));
boolean verified =
verifyIapRequestHeader.verifyJwtForAppEngine(
verifyJwtRequest, IAP_PROJECT_NUMBER, IAP_PROJECT_ID);
assertTrue(verified);
}
/** Processes failed copy requests */
private void onCopyFailure(
KeySetView<IOException, Boolean> innerExceptions,
GoogleJsonError jsonError,
HttpHeaders responseHeaders,
String srcBucketName,
String srcObjectName) {
GoogleJsonResponseException cause = createJsonResponseException(jsonError, responseHeaders);
innerExceptions.add(
errorExtractor.itemNotFound(cause)
? createFileNotFoundException(srcBucketName, srcObjectName, cause)
: new IOException(
String.format(
"Error copying '%s'", StringPaths.fromComponents(srcBucketName, srcObjectName)),
cause));
}
/**
* Initializes metadata (size, encoding, etc) from HTTP {@code headers}. Used for lazy
* initialization when fail fast is disabled.
*/
@VisibleForTesting
protected void initMetadata(HttpHeaders headers) throws IOException {
checkState(
!metadataInitialized,
"Cannot initialize metadata, it already initialized for '%s'",
resourceId);
String generationString = headers.getFirstHeaderStringValue("x-goog-generation");
if (generationString == null) {
throw new IOException(String.format("Failed to retrieve generation for '%s'", resourceId));
}
long generation = Long.parseLong(generationString);
String range = headers.getContentRange();
long sizeFromMetadata =
range == null
? headers.getContentLength()
: Long.parseLong(range.substring(range.lastIndexOf('/') + 1));
initMetadata(headers.getContentEncoding(), sizeFromMetadata, generation);
}
private final Response convertResponse(final Request inputRequest,
final HttpResponse inputResponse)
throws IOException {
final HttpHeaders headers = inputResponse.getHeaders();
Integer contentLength = null;
if (headers.getContentLength() != null && headers.getContentLength() <= Integer.MAX_VALUE) {
contentLength = inputResponse.getHeaders().getContentLength().intValue();
}
return Response.builder()
.body(inputResponse.getContent(), contentLength)
.status(inputResponse.getStatusCode())
.reason(inputResponse.getStatusMessage())
.headers(toMap(inputResponse.getHeaders()))
.request(inputRequest)
.build();
}
@Test
public void shouldHandleTooManyKeysCreated() throws IOException {
when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);
final GoogleJsonResponseException resourceExhausted = new GoogleJsonResponseException(
new HttpResponseException.Builder(429, "RESOURCE_EXHAUSTED", new HttpHeaders()),
new GoogleJsonError().set("status", "RESOURCE_EXHAUSTED"));
doThrow(resourceExhausted).when(serviceAccountKeyManager).createJsonKey(any());
doThrow(resourceExhausted).when(serviceAccountKeyManager).createP12Key(any());
exception.expect(InvalidExecutionException.class);
exception.expectMessage(String.format(
"Maximum number of keys on service account reached: %s. Styx requires 4 keys to operate.",
SERVICE_ACCOUNT));
sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
/**
* Initiates the resumable upload by sending a request to Google Cloud Storage.
*
* @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
* @return the URI for the initiated resumable upload
*/
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
// This follows the Google Cloud Storage guidelines for initiating resumable uploads:
// https://cloud.google.com/storage/docs/resumable-uploads-xml
HttpRequestFactory requestFactory =
httpTransport.createRequestFactory(
req -> {
HttpHeaders headers = createHttpHeaders();
headers.setContentLength(0L);
headers.set("x-goog-resumable", "start");
req.setHeaders(headers);
req.setLoggingEnabled(true);
});
try {
HttpRequest httpRequest =
requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
HttpResponse response = httpRequest.execute();
if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
throw new BatchJobException(
"Initiate upload failed. Resumable upload URI was not in the response.");
}
return URI.create(response.getHeaders().getLocation());
} catch (IOException e) {
throw new BatchJobException("Failed to initiate upload", e);
}
}
@Test(expected = IOException.class)
public void execute_indexFailed_pushedToQueue_throwsIOException() throws Exception {
Item item =
new Item().setName("id1").setQueue("Q1").setPayload("1234").setAcl(getCustomerAcl());
RepositoryDoc doc = new RepositoryDoc.Builder().setItem(item).build();
doAnswer(
invocation -> {
SettableFuture<Operation> updateFuture = SettableFuture.create();
updateFuture.setException(
new GoogleJsonResponseException(
new HttpResponseException.Builder(
HTTP_BAD_GATEWAY, "bad gateway", new HttpHeaders()),
new GoogleJsonError()));
return updateFuture;
})
.when(mockIndexingService)
.indexItem(item, RequestMode.UNSPECIFIED);
when(mockIndexingService.push(anyString(), any()))
.thenReturn(Futures.immediateFuture(new Item()));
try {
doc.execute(mockIndexingService);
} finally {
InOrder inOrder = inOrder(mockIndexingService);
inOrder.verify(mockIndexingService).indexItem(item, RequestMode.UNSPECIFIED);
ArgumentCaptor<PushItem> pushItemArgumentCaptor = ArgumentCaptor.forClass(PushItem.class);
inOrder
.verify(mockIndexingService)
.push(eq(item.getName()), pushItemArgumentCaptor.capture());
PushItem pushItem = pushItemArgumentCaptor.getValue();
assertEquals("Q1", pushItem.getQueue());
assertEquals("SERVER_ERROR", pushItem.getRepositoryError().getType());
assertEquals("1234", pushItem.getPayload());
assertEquals("id1", doc.getItem().getName());
}
}
static boolean runningOnComputeEngine(HttpTransport transport,
SystemEnvironmentProvider environment) {
// If the environment has requested that we do no GCE checks, return immediately.
if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
return false;
}
GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
try {
HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
request.getHeaders().set("Metadata-Flavor", "Google");
HttpResponse response = request.execute();
try {
HttpHeaders headers = response.getHeaders();
return headersContainValue(headers, "Metadata-Flavor", "Google");
} finally {
response.disconnect();
}
} catch (SocketTimeoutException expected) {
// Ignore logging timeouts which is the expected failure mode in non GCE environments.
} catch (IOException e) {
LOGGER.log(
Level.WARNING,
"Failed to detect whether we are running on Google Compute Engine.",
e);
}
}
return false;
}
@Test
public void testFailure() throws IOException {
AsyncRequest<GenericJson> req = new AsyncRequest<>(testRequest, retryPolicy, operationStats);
req.getCallback().onStart();
req.getCallback().onFailure(new GoogleJsonError(), new HttpHeaders());
// Calling failure again should create a new event
req.getCallback().onFailure(new GoogleJsonError(), new HttpHeaders());
verify(operationStats, times(2)).event(testRequest.getClass().getName());
verify(event, times(1)).start();
verify(event, times(2)).failure();
}
@Test
public void testRetryableFailure() throws IOException {
AsyncRequest<GenericJson> req = new AsyncRequest<>(testRequest, retryPolicy, operationStats);
when(retryPolicy.isRetryableStatusCode(anyInt())).thenReturn(true);
req.getCallback().onStart();
req.getCallback().onFailure(new GoogleJsonError(), new HttpHeaders());
req.getCallback().onStart();
req.getCallback().onFailure(new GoogleJsonError(), new HttpHeaders());
req.getCallback().onStart();
req.getCallback().onSuccess(new GenericJson(), new HttpHeaders());
verify(operationStats, times(3)).event(testRequest.getClass().getName());
verify(event, times(3)).start();
verify(event, times(2)).failure();
verify(event, times(1)).success();
}
public static GoogleJsonResponseException createJsonResponseException(
GoogleJsonError e, HttpHeaders responseHeaders) {
if (e != null) {
return new GoogleJsonResponseException(
new HttpResponseException.Builder(e.getCode(), e.getMessage(), responseHeaders), e);
}
return null;
}
@Override
public void onSuccess(Groups groups, HttpHeaders responseHeaders) throws IOException {
if (groups == null || groups.getGroups() == null || groups.getGroups().isEmpty()) {
log.debug("No groups found for user " + email);
return;
}
Set<Role> groupSet =
groups.getGroups().stream().flatMap(toRoleFn()).collect(Collectors.toSet());
emailGroupsMap.put(email, groupSet);
}
public HttpResponse getTaskForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, UUID taskId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTask");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTask");
}// verify the required parameter 'taskId' is set
if (taskId == null) {
throw new IllegalArgumentException("Missing the required parameter 'taskId' when calling getTask");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTask");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
uriVariables.put("taskId", taskId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/tasks/{taskId}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
@Test
public void testBatchRequestSocketTimeoutException() throws Exception {
BatchRequestService batchService = setupService();
batchService.startAsync().awaitRunning();
assertTrue(batchService.isRunning());
BatchRequest batchRequest = getMockBatchRequest();
when(batchRequestHelper.createBatch(any())).thenReturn(batchRequest);
when(retryPolicy.getMaxRetryLimit()).thenReturn(1);
when(retryPolicy.isRetryableStatusCode(504)).thenReturn(true);
AsyncRequest<GenericJson> requestToBatch =
new AsyncRequest<GenericJson>(testRequest, retryPolicy, operationStats);
AtomicInteger counter = new AtomicInteger();
GenericJson successfulResult = new GenericJson();
doAnswer(
invocation -> {
if (counter.incrementAndGet() == 1) {
throw new SocketTimeoutException();
}
requestToBatch.getCallback().onStart();
requestToBatch.getCallback().onSuccess(successfulResult, new HttpHeaders());
return null;
})
.when(batchRequestHelper)
.executeBatchRequest(batchRequest);
batchService.add(requestToBatch);
batchService.flush();
batchService.stopAsync().awaitTerminated();
assertEquals(successfulResult, requestToBatch.getFuture().get());
assertEquals(Status.COMPLETED, requestToBatch.getStatus());
assertEquals(1, requestToBatch.getRetries());
assertFalse(batchService.isRunning());
}
@Override
public void onFailure(ErrorOutput.ErrorBody e, HttpHeaders responseHeaders) throws IOException {
GoogleJsonErrorContainer errorContainer = new GoogleJsonErrorContainer();
if (e.hasError()) {
ErrorOutput.ErrorProto errorProto = e.getError();
GoogleJsonError error = new GoogleJsonError();
if (errorProto.hasCode()) {
error.setCode(errorProto.getCode());
}
if (errorProto.hasMessage()) {
error.setMessage(errorProto.getMessage());
}
List<ErrorInfo> errorInfos = new ArrayList<ErrorInfo>(errorProto.getErrorsCount());
for (ErrorOutput.IndividualError individualError : errorProto.getErrorsList()) {
ErrorInfo errorInfo = new ErrorInfo();
if (individualError.hasDomain()) {
errorInfo.setDomain(individualError.getDomain());
}
if (individualError.hasMessage()) {
errorInfo.setMessage(individualError.getMessage());
}
if (individualError.hasReason()) {
errorInfo.setReason(individualError.getReason());
}
errorInfos.add(errorInfo);
}
error.setErrors(errorInfos);
errorContainer.setError(error);
}
callback.onFailure(errorContainer, responseHeaders);
}
@Test
@SuppressWarnings("unchecked")
public void testNonRetryableErrorCode() throws Exception {
int httpErrorCode = 65535;
when(retryPolicy.isRetryableStatusCode(httpErrorCode)).thenReturn(false);
BatchRequestService batchService = setupService();
batchService.startAsync().awaitRunning();
assertTrue(batchService.isRunning());
BatchRequest batchRequest = getMockBatchRequest();
when(batchRequestHelper.createBatch(any())).thenReturn(batchRequest);
AsyncRequest<GenericJson> requestToBatch =
new AsyncRequest<GenericJson>(testRequest, retryPolicy, operationStats);
assertEquals(0, requestToBatch.getRetries());
assertEquals(Status.NEW, requestToBatch.getStatus());
GoogleJsonError error = new GoogleJsonError();
error.setCode(httpErrorCode);
error.setMessage("Unknown error code");
doAnswer(
i -> {
requestToBatch.getCallback().onFailure(error, new HttpHeaders());
return null;
})
.when(batchRequestHelper)
.executeBatchRequest(batchRequest);
batchService.add(requestToBatch);
batchService.flush();
batchService.stopAsync().awaitTerminated();
verify(retryPolicy).isRetryableStatusCode(httpErrorCode);
validateFailedResult(requestToBatch.getFuture());
assertEquals(Status.FAILED, requestToBatch.getStatus());
assertEquals(0, requestToBatch.getRetries());
assertFalse(batchService.isRunning());
}
@Test
public void notFoundResponseIsNotPResourceExhausted() {
assertThat(GcpUtil.isResourceExhausted(new GoogleJsonResponseException(
new HttpResponseException.Builder(404, "Not Found", new HttpHeaders()), new GoogleJsonError())), is(false));
assertThat(GcpUtil.isResourceExhausted(new GoogleJsonResponseException(
new HttpResponseException.Builder(404, "Not Found", new HttpHeaders()), null)), is(false));
}
public HttpResponse deleteConnectionForHttpResponse(String accessToken, UUID id) throws IOException {
// verify the required parameter 'id' is set
if (id == null) {
throw new IllegalArgumentException("Missing the required parameter 'id' when calling deleteConnection");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteConnection");
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept("");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections/{id}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("DELETE " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
@Override
public ClientResponse executeRequest(String url) throws IOException {
HttpResponse response = httpTransport.createRequestFactory()
.buildGetRequest(new GenericUrl(url))
.setHeaders(new HttpHeaders().set(HEADER_KEY_CLIENT_TYPE, getClientType().getValue()))
.execute();
return new ClientResponse(IOUtils.toString(response.getContent(), StandardCharsets.UTF_8), response.getStatusCode());
}
private void runTestThrowsHttpResponseException(Callable<?> c) throws Exception {
HttpResponseException ex =
new HttpResponseException.Builder(STATUS_CODE, ERROR_MESSAGE, new HttpHeaders()).build();
httpTransport = createMockHttpTransport(ex);
transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
try {
c.call();
fail();
} catch (GitHubApiException e) {
assertThat(e.getHttpCode()).isEqualTo(STATUS_CODE);
assertThat(e.getError()).isNull();
}
}
public VaultEndpoint(final VaultConfiguration conf, HttpTransport transport) throws VaultException {
this.conf = conf;
requestFactory = transport.createRequestFactory(
new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
request.setParser(new JsonObjectParser(JSON_FACTORY));
request.setHeaders(new HttpHeaders().set("X-Vault-Token", conf.getToken()));
request.setReadTimeout(conf.getReadTimeout());
request.setConnectTimeout(conf.getOpenTimeout());
}
}
);
}