use of com.google.appengine.api.utils.FutureWrapper in project appengine-gcs-client by GoogleCloudPlatform.
the class OauthRawGcsService method readObjectAsync.
/**
* Might not fill all of dst.
*/
@Override
public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename, long startOffsetBytes, long timeoutMillis) {
Preconditions.checkArgument(startOffsetBytes >= 0, "%s: offset must be non-negative: %s", this, startOffsetBytes);
final int n = dst.remaining();
Preconditions.checkArgument(n > 0, "%s: dst full: %s", this, dst);
final int want = Math.min(READ_LIMIT_BYTES, n);
final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);
req.setHeader(new HTTPHeader(RANGE, "bytes=" + startOffsetBytes + "-" + (startOffsetBytes + want - 1)));
final HTTPRequestInfo info = new HTTPRequestInfo(req);
return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {
@Override
protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {
long totalLength;
switch(resp.getResponseCode()) {
case 200:
totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);
break;
case 206:
totalLength = getLengthFromContentRange(resp);
break;
case 404:
throw new FileNotFoundException("Could not find: " + filename);
case 416:
throw new BadRangeException("Requested Range not satisfiable; perhaps read past EOF? " + URLFetchUtils.describeRequestAndResponse(info, resp));
default:
throw HttpErrorHandler.error(info, resp);
}
byte[] content = resp.getContent();
Preconditions.checkState(content.length <= want, "%s: got %s > wanted %s", this, content.length, want);
dst.put(content);
return getMetadataFromResponse(filename, resp, totalLength);
}
@Override
protected Throwable convertException(Throwable e) {
return OauthRawGcsService.convertException(info, e);
}
};
}
use of com.google.appengine.api.utils.FutureWrapper in project appengine-gcs-client by GoogleCloudPlatform.
the class OauthRawGcsService method putAsync.
/**
* Same as {@link #put} but is runs asynchronously and returns a future. In the event of an error
* the exception out of the future will be an ExecutionException with the cause set to the same
* exception that would have been thrown by put.
*/
private Future<RawGcsCreationToken> putAsync(final GcsRestCreationToken token, ByteBuffer chunk, final boolean isFinalChunk, long timeoutMillis) {
final int length = chunk.remaining();
HTTPRequest request = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);
final HTTPRequestInfo info = new HTTPRequestInfo(request);
return new FutureWrapper<HTTPResponse, RawGcsCreationToken>(urlfetch.fetchAsync(request)) {
@Override
protected Throwable convertException(Throwable e) {
return OauthRawGcsService.convertException(info, e);
}
@Override
protected GcsRestCreationToken wrap(HTTPResponse resp) throws Exception {
return handlePutResponse(token, isFinalChunk, length, info, resp);
}
};
}
use of com.google.appengine.api.utils.FutureWrapper in project appengine-java-standard by GoogleCloudPlatform.
the class URLFetchServiceImpl method fetchAsync.
@Override
public Future<HTTPResponse> fetchAsync(HTTPRequest request) {
final FetchOptions fetchOptions = request.getFetchOptions();
final URL url = request.getURL();
Future<byte[]> response = ApiProxy.makeAsyncCall(PACKAGE, "Fetch", convertToPb(request).toByteArray(), createApiConfig(fetchOptions));
// Request is not held onto after return to avoid holding more memory than needed.
return new FutureWrapper<byte[], HTTPResponse>(response) {
@Override
protected HTTPResponse wrap(byte @Nullable [] responseBytes) throws IOException {
URLFetchResponse responseProto = URLFetchResponse.newBuilder().mergeFrom(responseBytes).build();
if (!fetchOptions.getAllowTruncate() && responseProto.getContentWasTruncated()) {
throw new ResponseTooLargeException(url.toString());
}
return convertFromPb(responseProto);
}
@Override
protected Throwable convertException(Throwable cause) {
if (cause instanceof ApiProxy.ApplicationException) {
return convertApplicationException(url, (ApiProxy.ApplicationException) cause);
} else if (cause instanceof ApiProxy.ApiDeadlineExceededException) {
return new SocketTimeoutException("Timeout while fetching URL: " + url);
}
return cause;
}
};
}
use of com.google.appengine.api.utils.FutureWrapper in project appengine-java-standard by GoogleCloudPlatform.
the class AsyncDatastoreServiceImpl method allocateIds.
@Override
public Future<KeyRange> allocateIds(final Key parent, final String kind, long num) {
if (num <= 0) {
throw new IllegalArgumentException("num must be > 0");
}
if (num > 1000000000) {
throw new IllegalArgumentException("num must be < 1 billion");
}
// kind validation taken care of by the next call
final AppIdNamespace appIdNamespace = datastoreServiceConfig.getAppIdNamespace();
Reference allocateIdsRef = buildAllocateIdsRef(parent, kind, appIdNamespace);
AllocateIdsRequest req = new AllocateIdsRequest().setSize(num).setModelKey(allocateIdsRef);
AllocateIdsResponse resp = new AllocateIdsResponse();
Future<AllocateIdsResponse> future = makeAsyncCall(apiConfig, DatastoreService_3.Method.AllocateIds, req, resp);
return new FutureWrapper<AllocateIdsResponse, KeyRange>(future) {
@Override
protected KeyRange wrap(AllocateIdsResponse resp) throws Exception {
return new KeyRange(parent, kind, resp.getStart(), resp.getEnd(), appIdNamespace);
}
@Override
protected Throwable convertException(Throwable cause) {
return cause;
}
};
}
use of com.google.appengine.api.utils.FutureWrapper in project appengine-java-standard by GoogleCloudPlatform.
the class LogServiceImpl method fetchAsync.
Future<LogQueryResult> fetchAsync(LogQuery query) {
LogReadRequest.Builder request = LogReadRequest.newBuilder().setAppId(getCurrentEnvironmentOrThrow().getAppId());
Long startTimeUs = query.getStartTimeUsec();
if (startTimeUs != null) {
request.setStartTime(startTimeUs);
}
Long endTimeUs = query.getEndTimeUsec();
if (endTimeUs != null) {
request.setEndTime(endTimeUs);
}
int batchSize = requireNonNull(query.getBatchSize(), "Null batch size");
request.setCount(batchSize);
LogLevel minLogLevel = query.getMinLogLevel();
if (minLogLevel != null) {
request.setMinimumLogLevel(minLogLevel.ordinal());
}
request.setIncludeIncomplete(query.getIncludeIncomplete()).setIncludeAppLogs(query.getIncludeAppLogs());
// Use a set to de-dupe entries.
Set<LogQuery.Version> convertedModuleInfos = Sets.newTreeSet(LogQuery.VERSION_COMPARATOR);
// NOTE: LogQuery enforces that at most one of these lists is populated.
if (!query.getMajorVersionIds().isEmpty()) {
for (String versionId : query.getMajorVersionIds()) {
convertedModuleInfos.add(new LogQuery.Version("default", versionId));
}
} else if (!query.getVersions().isEmpty()) {
convertedModuleInfos.addAll(query.getVersions());
} else {
String currentVersionId = getCurrentEnvironmentOrThrow().getVersionId();
// Get just the major version id - for 1.2332 it is just '1'.
String versionId = currentVersionId.split("\\.")[0];
convertedModuleInfos.add(new LogQuery.Version(getCurrentEnvironmentOrThrow().getModuleId(), versionId));
}
for (LogQuery.Version moduleInfo : convertedModuleInfos) {
LogModuleVersion.Builder requestModuleVersion = request.addModuleVersionBuilder();
if (!moduleInfo.getModuleId().equals("default")) {
requestModuleVersion.setModuleId(moduleInfo.getModuleId());
}
requestModuleVersion.setVersionId(moduleInfo.getVersionId());
}
for (String requestId : query.getRequestIds()) {
request.addRequestId(ByteString.copyFromUtf8(requestId));
}
String offset = query.getOffset();
if (offset != null) {
request.setOffset(LogQueryResult.parseOffset(offset));
}
final LogQuery finalizedQuery = query;
ApiProxy.ApiConfig apiConfig = new ApiProxy.ApiConfig();
Future<byte[]> responseBytes = ApiProxy.makeAsyncCall(PACKAGE, READ_RPC_NAME, request.build().toByteArray(), apiConfig);
return new FutureWrapper<byte[], LogQueryResult>(responseBytes) {
@Override
protected LogQueryResult wrap(byte @Nullable [] responseBytes) {
try {
LogReadResponse response = LogReadResponse.parseFrom(responseBytes, ExtensionRegistry.getEmptyRegistry());
return new LogQueryResult(response, finalizedQuery);
} catch (InvalidProtocolBufferException | UninitializedMessageException e) {
throw new LogServiceException("Could not parse LogReadResponse", e);
}
}
@Override
protected Throwable convertException(Throwable cause) {
if (cause instanceof ApiProxy.ApplicationException) {
ApiProxy.ApplicationException e = (ApiProxy.ApplicationException) cause;
ErrorCode errorCode = LogServiceError.ErrorCode.forNumber(e.getApplicationError());
if (errorCode == LogServiceError.ErrorCode.INVALID_REQUEST) {
return new InvalidRequestException(e.getErrorDetail());
}
return new LogServiceException(e.getErrorDetail());
}
return cause;
}
};
}
Aggregations