下面列出了怎么用com.google.api.client.http.HttpResponse的API类实例代码及写法,或者点击链接到github查看源代码。
public void testUploadServerError_WithoutUnsuccessfulHandler() throws Exception {
int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
MediaTransport fakeTransport = new MediaTransport(contentLength);
fakeTransport.testServerError = true;
InputStream is = new ByteArrayInputStream(new byte[contentLength]);
InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
mediaContent.setLength(contentLength);
MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
assertEquals(500, response.getStatusCode());
// There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
// request with server error
assertEquals(3, fakeTransport.lowLevelExecCalls);
}
public HttpResponse deleteOrderForHttpResponse(String orderId) throws IOException {
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling deleteOrder");
}
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("order_id", orderId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}");
String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = null;
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute();
}
public HttpResponse testJsonFormDataForHttpResponse(String param, String param2) throws IOException {
// verify the required parameter 'param' is set
if (param == null) {
throw new IllegalArgumentException("Missing the required parameter 'param' when calling testJsonFormData");
}// verify the required parameter 'param2' is set
if (param2 == null) {
throw new IllegalArgumentException("Missing the required parameter 'param2' when calling testJsonFormData");
}
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/jsonFormData");
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = null;
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute();
}
/**
* searches for an Superfund by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param superFundID Superfund id for single object
* @param accessToken Authorization token for user set in header of each request
* @return SuperFunds
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFunds getSuperfund(String accessToken, String xeroTenantId, UUID superFundID) throws IOException {
try {
TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
HttpResponse response = getSuperfundForHttpResponse(accessToken, xeroTenantId, superFundID);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSuperfund -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
@Override
public boolean handleResponse(
HttpRequest request,
HttpResponse response,
boolean supportsRetry) throws IOException {
try {
boolean retry = preRetryHandler.handleResponse(request, response, supportsRetry);
if (!retry) {
retry = retryHandler.handleResponse(request, response, supportsRetry);
}
return retry;
} finally {
// Pre-retry handler may have reset the unsuccessful response handler on the
// request. This changes it back.
request.setUnsuccessfulResponseHandler(this);
}
}
/**
* retrieve settings
* <p><b>200</b> - payroll settings
* @param xeroTenantId Xero identifier for Tenant
* @param accessToken Authorization token for user set in header of each request
* @return SettingsObject
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SettingsObject getSettings(String accessToken, String xeroTenantId) throws IOException {
try {
TypeReference<SettingsObject> typeRef = new TypeReference<SettingsObject>() {};
HttpResponse response = getSettingsForHttpResponse(accessToken, xeroTenantId);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSettings -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
/**
* searches Pay Items
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - validation error for a bad request
* @param xeroTenantId Xero identifier for Tenant
* @param ifModifiedSince Only records created or modified since this timestamp will be returned
* @param where Filter by an any element
* @param order Order by an any element
* @param page e.g. page=1 – Up to 100 objects will be returned in a single API call
* @param accessToken Authorization token for user set in header of each request
* @return PayItems
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayItems getPayItems(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
try {
TypeReference<PayItems> typeRef = new TypeReference<PayItems>() {};
HttpResponse response = getPayItemsForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayItems -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
/** Tests that a non-retriable error is not retried. */
@Test
public void testErrorCodeForbidden() throws IOException {
when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
when(mockLowLevelResponse.getStatusCode())
.thenReturn(403) // Non-retryable error.
.thenReturn(200); // Shouldn't happen.
try {
Storage.Buckets.Get result = storage.buckets().get("test");
HttpResponse response = result.executeUnparsed();
assertNotNull(response);
} catch (HttpResponseException e) {
assertThat(e.getMessage(), Matchers.containsString("403"));
}
verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
verify(mockLowLevelRequest).setWriteTimeout(anyInt());
verify(mockLowLevelRequest).execute();
verify(mockLowLevelResponse).getStatusCode();
expectedLogs.verifyWarn("Request failed with code 403");
}
public HttpResponse testEndpointParametersForHttpResponse(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws IOException {
// verify the required parameter 'number' is set
if (number == null) {
throw new IllegalArgumentException("Missing the required parameter 'number' when calling testEndpointParameters");
}// verify the required parameter '_double' is set
if (_double == null) {
throw new IllegalArgumentException("Missing the required parameter '_double' when calling testEndpointParameters");
}// verify the required parameter 'patternWithoutDelimiter' is set
if (patternWithoutDelimiter == null) {
throw new IllegalArgumentException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters");
}// verify the required parameter '_byte' is set
if (_byte == null) {
throw new IllegalArgumentException("Missing the required parameter '_byte' when calling testEndpointParameters");
}
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake");
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = new EmptyContent();
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
public HttpResponse updateUserForHttpResponse(String username, User body) throws IOException {
// verify the required parameter 'username' is set
if (username == null) {
throw new IllegalArgumentException("Missing the required parameter 'username' when calling updateUser");
}// verify the required parameter 'body' is set
if (body == null) {
throw new IllegalArgumentException("Missing the required parameter 'body' when calling updateUser");
}
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}");
String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = apiClient.new JacksonJsonHttpContent(body);
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute();
}
/**
* Allows you to create a task
* Allows you to create a specific task
* <p><b>200</b> - OK/success, returns the newly created time entry
* @param xeroTenantId Xero identifier for Tenant
* @param projectId You can specify an individual project by appending the projectId to the endpoint
* @param timeEntryCreateOrUpdate The time entry object you are creating
* @param accessToken Authorization token for user set in header of each request
* @return TimeEntry
* @throws IOException if an error occurs while attempting to invoke the API
**/
public TimeEntry createTimeEntry(String accessToken, String xeroTenantId, UUID projectId, TimeEntryCreateOrUpdate timeEntryCreateOrUpdate) throws IOException {
try {
TypeReference<TimeEntry> typeRef = new TypeReference<TimeEntry>() {};
HttpResponse response = createTimeEntryForHttpResponse(accessToken, xeroTenantId, projectId, timeEntryCreateOrUpdate);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createTimeEntry -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
/**
* searches Payroll Calendars
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - validation error for a bad request
* @param xeroTenantId Xero identifier for Tenant
* @param payrollCalendarID Payroll Calendar id for single object
* @param accessToken Authorization token for user set in header of each request
* @return PayrollCalendars
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayrollCalendars getPayrollCalendar(String accessToken, String xeroTenantId, UUID payrollCalendarID) throws IOException {
try {
TypeReference<PayrollCalendars> typeRef = new TypeReference<PayrollCalendars>() {};
HttpResponse response = getPayrollCalendarForHttpResponse(accessToken, xeroTenantId, payrollCalendarID);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayrollCalendar -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
private String loginAndGetId(HttpRequestFactory requestFactory, String tld) throws IOException {
logger.atInfo().log("Logging in to MoSAPI");
HttpRequest request =
requestFactory.buildGetRequest(new GenericUrl(String.format(LOGIN_URL, tld)));
request.getHeaders().setBasicAuthentication(String.format("%s_ry", tld), password);
HttpResponse response = request.execute();
Optional<HttpCookie> idCookie =
response.getHeaders().getHeaderStringValues("Set-Cookie").stream()
.flatMap(value -> HttpCookie.parse(value).stream())
.filter(cookie -> cookie.getName().equals(COOKIE_ID))
.findAny();
checkState(
idCookie.isPresent(),
"Didn't get the ID cookie from the login response. Code: %s, headers: %s",
response.getStatusCode(),
response.getHeaders());
return idCookie.get().getValue();
}
public static void dicomWebSearchStudies(String dicomStoreName) throws IOException {
// String dicomStoreName =
// String.format(
// DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");
// Initialize the client, which will be used to interact with the service.
CloudHealthcare client = createClient();
DicomStores.SearchForStudies request =
client
.projects()
.locations()
.datasets()
.dicomStores()
.searchForStudies(dicomStoreName, "studies")
// Refine your search by appending DICOM tags to the
// request in the form of query parameters. This sample
// searches for studies containing a patient's name.
.set("PatientName", "Sally Zhang");
// Execute the request and process the results.
HttpResponse response = request.executeUnparsed();
System.out.println("Studies found: \n" + response.toString());
}
/**
* Fetches the listing of the given bucket.
*
* @param bucketName the name of the bucket to list.
* @return the raw XML containing the listing of the bucket.
* @throws IOException if there's an error communicating with Cloud Storage.
* @throws GeneralSecurityException for errors creating https connection.
*/
public static String listBucket(final String bucketName)
throws IOException, GeneralSecurityException {
// [START snippet]
// Build an account credential.
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(STORAGE_SCOPE));
// Set up and execute a Google Cloud Storage request.
String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8");
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory requestFactory =
httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
GenericUrl url = new GenericUrl(uri);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
String content = response.parseAsString();
// [END snippet]
return content;
}
/**
* Update a Payslip
* Update lines on a single payslips
* <p><b>200</b> - A successful request - currently returns empty array for JSON
* @param xeroTenantId Xero identifier for Tenant
* @param payslipID Payslip id for single object
* @param payslipLines The payslipLines parameter
* @param accessToken Authorization token for user set in header of each request
* @return Payslips
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Payslips updatePayslip(String accessToken, String xeroTenantId, UUID payslipID, List<PayslipLines> payslipLines) throws IOException {
try {
TypeReference<Payslips> typeRef = new TypeReference<Payslips>() {};
HttpResponse response = updatePayslipForHttpResponse(accessToken, xeroTenantId, payslipID, payslipLines);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updatePayslip -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
if (e.getStatusCode() == 400 || e.getStatusCode() == 405) {
TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {};
com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef);
handler.validationError("Error", error.getMessage());
} else {
handler.execute(e);
}
} catch (IOException ioe) {
throw ioe;
}
return null;
}
/**
* Update a PayRun
* Update properties on a single PayRun
* <p><b>200</b> - A successful request
* @param xeroTenantId Xero identifier for Tenant
* @param payRunID PayRun id for single object
* @param payRun The payRun parameter
* @param accessToken Authorization token for user set in header of each request
* @return PayRuns
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayRuns updatePayRun(String accessToken, String xeroTenantId, UUID payRunID, List<PayRun> payRun) throws IOException {
try {
TypeReference<PayRuns> typeRef = new TypeReference<PayRuns>() {};
HttpResponse response = updatePayRunForHttpResponse(accessToken, xeroTenantId, payRunID, payRun);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updatePayRun -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
/**
* searches for an payslip by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param payslipID Payslip id for single object
* @param accessToken Authorization token for user set in header of each request
* @return PayslipObject
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayslipObject getPayslip(String accessToken, String xeroTenantId, UUID payslipID) throws IOException {
try {
TypeReference<PayslipObject> typeRef = new TypeReference<PayslipObject>() {};
HttpResponse response = getPayslipForHttpResponse(accessToken, xeroTenantId, payslipID);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayslip -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
public HttpResponse uploadFileWithRequiredFileForHttpResponse(Long petId, File requiredFile, String additionalMetadata) throws IOException {
// verify the required parameter 'petId' is set
if (petId == null) {
throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile");
}// verify the required parameter 'requiredFile' is set
if (requiredFile == null) {
throw new IllegalArgumentException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile");
}
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/{petId}/uploadImageWithRequiredFile");
String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = new EmptyContent();
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
/**
* Update a Superfund
* Update properties on a single Superfund
* <p><b>200</b> - A successful request
* @param xeroTenantId Xero identifier for Tenant
* @param superFundID Superfund id for single object
* @param superFund The superFund parameter
* @param accessToken Authorization token for user set in header of each request
* @return SuperFunds
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFunds updateSuperfund(String accessToken, String xeroTenantId, UUID superFundID, List<SuperFund> superFund) throws IOException {
try {
TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
HttpResponse response = updateSuperfundForHttpResponse(accessToken, xeroTenantId, superFundID, superFund);
return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
} catch (HttpResponseException e) {
if (logger.isDebugEnabled()) {
logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updateSuperfund -------------------");
logger.debug(e.toString());
}
XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
handler.execute(e);
} catch (IOException ioe) {
throw ioe;
}
return null;
}
public HttpResponse testEnumParametersForHttpResponse(Map<String, Object> params) throws IOException {
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake");
// Copy the params argument if present, to allow passing in immutable maps
Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params);
for (Map.Entry<String, Object> entry: allParams.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
if (value instanceof Collection) {
uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
} else if (value instanceof Object[]) {
uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
} else {
uriBuilder = uriBuilder.queryParam(key, value);
}
}
}
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = null;
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute();
}
public HttpResponse createAssetForHttpResponse(String accessToken, String xeroTenantId, Asset asset) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createAsset");
}// verify the required parameter 'asset' is set
if (asset == null) {
throw new IllegalArgumentException("Missing the required parameter 'asset' when calling createAsset");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createAsset");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets");
String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("POST " + genericUrl.toString());
}
HttpContent content = null;
content = apiClient.new JacksonJsonHttpContent(asset);
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
public HttpResponse fakeOuterBooleanSerializeForHttpResponse(java.io.InputStream body, String mediaType) throws IOException {
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/boolean");
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = body == null ?
apiClient.new JacksonJsonHttpContent(null) :
new InputStreamContent(mediaType == null ? Json.MEDIA_TYPE : mediaType, body);
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
static String makeRawPostRequest(HttpTransport httpTransport, String url, HttpContent httpContent)
throws IOException {
HttpRequestFactory factory = httpTransport.createRequestFactory();
HttpRequest postRequest = factory.buildPostRequest(new GenericUrl(url), httpContent);
HttpResponse response = postRequest.execute();
int statusCode = response.getStatusCode();
if (statusCode != 200) {
throw new IOException(
"Bad status code: " + statusCode + " error: " + response.getStatusMessage());
}
return CharStreams
.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
}
public HttpResponse getOrderByIdForHttpResponse(Long orderId, Map<String, Object> params) throws IOException {
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling getOrderById");
}
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("order_id", orderId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}");
// Copy the params argument if present, to allow passing in immutable maps
Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params);
for (Map.Entry<String, Object> entry: allParams.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
if (value instanceof Collection) {
uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
} else if (value instanceof Object[]) {
uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
} else {
uriBuilder = uriBuilder.queryParam(key, value);
}
}
}
String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = null;
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute();
}
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
request.setReadTimeout(60000); // 60 seconds is the max App Engine request time
HttpResponse response = request.execute();
if (response.getStatusCode() >= 300) {
throw new IOException("Client Generation failed at server side: " + response.getContent());
} else {
return response.getContent();
}
}
/**
* 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);
}
}
public HttpResponse testInlineAdditionalPropertiesForHttpResponse(Map<String, String> param) throws IOException {
// verify the required parameter 'param' is set
if (param == null) {
throw new IllegalArgumentException("Missing the required parameter 'param' when calling testInlineAdditionalProperties");
}
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/inline-additionalProperties");
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = apiClient.new JacksonJsonHttpContent(param);
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
public void testUploadAuthenticationError() throws Exception {
int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
MediaTransport fakeTransport = new MediaTransport(contentLength);
fakeTransport.testAuthenticationError = true;
InputStream is = new ByteArrayInputStream(new byte[contentLength]);
InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
mediaContent.setLength(contentLength);
MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
assertEquals(404, response.getStatusCode());
// There should be only 1 initiation request made with a 404.
assertEquals(1, fakeTransport.lowLevelExecCalls);
}
public HttpResponse fakeOuterStringSerializeForHttpResponse(String body, Map<String, Object> params) throws IOException {
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/outer/string");
// Copy the params argument if present, to allow passing in immutable maps
Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params);
for (Map.Entry<String, Object> entry: allParams.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
if (value instanceof Collection) {
uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
} else if (value instanceof Object[]) {
uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
} else {
uriBuilder = uriBuilder.queryParam(key, value);
}
}
}
String localVarUrl = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = apiClient.new JacksonJsonHttpContent(body);
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}