private Task<Void> deleteInstanceId(final String instanceId) { checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty"); return ImplFirebaseTrampolines.submitCallable(app, new Callable<Void>(){ @Override public Void call() throws Exception { String url = String.format( "%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId); HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url)); request.setParser(new JsonObjectParser(jsonFactory)); request.setResponseInterceptor(interceptor); HttpResponse response = null; try { response = request.execute(); ByteStreams.exhaust(response.getContent()); } catch (Exception e) { handleError(instanceId, e); } finally { if (response != null) { response.disconnect(); } } return null; } }); }
/** * * @return * @throws IOException */ private JsonObject getPublicKeysJson() throws IOException { // get public keys URI uri = URI.create(pubKeyUrl); GenericUrl url = new GenericUrl(uri); HttpTransport http = new NetHttpTransport(); HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute(); // store json from request String json = response.parseAsString(); // disconnect response.disconnect(); // parse json to object JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); return jsonObject; }
/** * Initiate a resumable upload direct to the cloud storage API. Providing an origin will enable * CORS requests to the upload URL from the specified origin. * * @param bucket the cloud storage bucket to upload to * @param name the name of the resource that will be uploaded * @param contentType the resource's content/mime type * @param origin the origin to allow for CORS requests * @return the upload URL * @see <a href="https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload">Performing a Resumable Upload</a> */ public String initiateResumableUpload(String bucket, String name, String contentType, String origin) { String uploadUrl = String.format("%s/upload/storage/v1/b/%s/o", BASE_GOOGLE_API_URL, bucket); GenericUrl url = new GenericUrl(uploadUrl); url.put("uploadType", "resumable"); url.put("name", name); HttpHeaders headers = new HttpHeaders(); headers.put("X-Upload-Content-Type", contentType); if (origin != null) { headers.put("Origin", origin); // Add origin header for CORS support } HttpResponse response; try { response = httpRequestFactory .buildPostRequest(url, null) .setHeaders(headers) .execute(); } catch (IOException e) { throw new GoogleCloudStorageException(e, "Cannot initiate upload: %s", e.getMessage()); } return response.getHeaders().getLocation(); }
private String signInWithCustomToken(String customToken) throws IOException { GenericUrl url = new GenericUrl(ID_TOOLKIT_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "token", customToken, "returnSecureToken", true); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
@Test public void registerMetric_fetchesStackdriverDefinition() throws Exception { // Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to // register a metric that's already been registered, so we fake one here. ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8)); HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream); HttpResponseException.Builder httpResponseExceptionBuilder = new HttpResponseException.Builder(response); httpResponseExceptionBuilder.setStatusCode(400); httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS"); GoogleJsonResponseException exception = new GoogleJsonResponseException(httpResponseExceptionBuilder, null); when(metricDescriptorCreate.execute()).thenThrow(exception); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); writer.registerMetric(metric); verify(client.projects().metricDescriptors().get("metric")).execute(); }
@Test public void registerMetric_rethrowsException() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8)); HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream); HttpResponseException.Builder httpResponseExceptionBuilder = new HttpResponseException.Builder(response); httpResponseExceptionBuilder.setStatusCode(404); GoogleJsonResponseException exception = new GoogleJsonResponseException(httpResponseExceptionBuilder, null); when(metricDescriptorCreate.execute()).thenThrow(exception); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric)); assertThat(exception.getStatusCode()).isEqualTo(404); }
@Test public void getEncodedTimeSeries_nullLabels_encodes() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8)); HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream); HttpResponseException.Builder httpResponseExceptionBuilder = new HttpResponseException.Builder(response); httpResponseExceptionBuilder.setStatusCode(400); httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS"); GoogleJsonResponseException exception = new GoogleJsonResponseException(httpResponseExceptionBuilder, null); when(metricDescriptorCreate.execute()).thenThrow(exception); when(metricDescriptorGet.execute()) .thenReturn(new MetricDescriptor().setName("foo").setLabels(null)); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); writer.registerMetric(metric); TimeSeries timeSeries = writer.getEncodedTimeSeries( MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L)); assertThat(timeSeries.getMetric().getLabels()).isEmpty(); }
public void testSimpleRetry() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3); MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder() .build(); MockSleeper mockSleeper = new MockSleeper(); RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5)); Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null) .setHttpRequestInitializer(retryHttpInitializerWrapper) .setApplicationName("test") .build(); HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null); HttpResponse response = request.execute(); assertThat(mockSleeper.getCount(), equalTo(3)); assertThat(response.getStatusCode(), equalTo(200)); }
public void testIOExceptionRetry() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true); MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder() .build(); MockSleeper mockSleeper = new MockSleeper(); RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueMillis(500)); Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null) .setHttpRequestInitializer(retryHttpInitializerWrapper) .setApplicationName("test") .build(); HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null); HttpResponse response = request.execute(); assertThat(mockSleeper.getCount(), equalTo(1)); assertThat(response.getStatusCode(), equalTo(200)); }
protected ByteArrayInputStream getInputStream(String endPoint, Date modifiedAfter, Map<String, String> params, String accept) throws IOException { OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "GET", null, params, accept); req.setToken(token); req.setTokenSecret(tokenSecret); if (modifiedAfter != null) { req.setIfModifiedSince(modifiedAfter); } try { HttpResponse resp = req.execute(); InputStream is = resp.getContent(); byte[] bytes = IOUtils.toByteArray(is); is.close(); return new ByteArrayInputStream(bytes); } catch (IOException ioe) { throw convertException(ioe); } }
protected Response delete(String endPoint) throws IOException { HttpResponse resp = null; OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "DELETE", null, null); req.setToken(token); req.setTokenSecret(tokenSecret); try { resp = req.execute(); // No-Content Returned from Xero API if (resp.getStatusCode() == 204) { return unmarshallResponse("<Response><Status>DELETED</Status></Response>", Response.class); } return unmarshallResponse(resp.parseAsString(), Response.class); } catch (IOException ioe) { throw xeroExceptionHandler.convertException(ioe); } }
/** * 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).execute(); verify(mockLowLevelResponse).getStatusCode(); expectedLogs.verifyWarn("Request failed with code 403"); }
@Test public void testBasicOperation() throws IOException { when(mockLowLevelRequest.execute()) .thenReturn(mockLowLevelResponse); when(mockLowLevelResponse.getStatusCode()) .thenReturn(200); Storage.Buckets.Get result = storage.buckets().get("test"); HttpResponse response = result.executeUnparsed(); assertNotNull(response); verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); verify(mockLowLevelRequest, atLeastOnce()) .addHeader(anyString(), anyString()); verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt()); verify(mockLowLevelRequest).execute(); verify(mockLowLevelResponse).getStatusCode(); expectedLogs.verifyNotLogged("Request failed"); }
public String processStatusCheck(String modelId) throws IOException, GeneralSecurityException { HttpResponse httpResponse = client.trainedmodels().get(Constants.PROJECT_NAME, modelId).executeUnparsed(); int status = httpResponse.getStatusCode(); System.out.println("HTTP Status : " + status); String trainingStatus = null; if (status == 200) { Insert2 res = responseToObject(httpResponse.parseAsString()); trainingStatus = res.getTrainingStatus(); System.out.println("Training Status : " + trainingStatus); if (trainingStatus.compareTo("DONE") == 0) { System.out.println("training complete"); System.out.println(res.getModelInfo()); } } else { httpResponse.ignore(); } return trainingStatus; }
@Override public void interceptResponse(HttpResponse response) throws IOException { if (!LOG.isDebugEnabled()) { return; } String uploadId = response.getHeaders().getFirstHeaderStringValue(UPLOAD_HEADER); if (uploadId == null) { return; } GenericUrl url = response.getRequest().getUrl(); // The check for no upload id limits the output to one log line per upload. // The check for upload type makes sure this is an upload and not a read. if (url.get(UPLOAD_ID_PARAM) == null && url.get(UPLOAD_TYPE_PARAM) != null) { LOG.debug( "Upload ID for url {} on worker {} is {}", url, System.getProperty("worker_id"), uploadId); } }
@Converter public static InputStream download(com.google.api.services.drive.model.File fileMetadata, Exchange exchange) throws Exception { if (fileMetadata.getDownloadUrl() != null && fileMetadata.getDownloadUrl().length() > 0) { try { // TODO maybe separate this out as custom drive API ex. google-drive://download... HttpResponse resp = getClient(exchange).getRequestFactory().buildGetRequest(new GenericUrl(fileMetadata.getDownloadUrl())).execute(); return resp.getContent(); } catch (IOException e) { LOG.debug("Could not download file.", e); return null; } } else { // The file doesn't have any content stored on Drive. return null; } }
@Test public void testETagIsNotTheSameWhenExecuteMedia() throws Exception { // Given File file = createTextFile("myFile.txt", "the contents"); // When HttpResponse responseExecute = gdriveConnectionRule.getDrive().files().get(file.getId()).executeUnparsed(); // when using the preferred method to download a file, URL parameter // "alt" is set to "media" HttpResponse responseExecuteMedia = gdriveConnectionRule.getDrive().files().get(file.getId()).executeMedia(); // Then // unfortunately ... assertNotEquals(responseExecute.getHeaders().getETag(), responseExecuteMedia.getHeaders().getETag()); }
public static HttpResponse createHttpResponse(int statusCode, InputStream content) throws IOException { FakeHttpTransport transport = new FakeHttpTransport(statusCode, content); HttpRequestFactory factory = transport.createRequestFactory(); HttpRequest request = factory.buildRequest( "foo", new GenericUrl("http://example.com/bar"), new EmptyHttpContent()); request.setThrowExceptionOnExecuteError(false); return request.execute(); }
private InputStream getFileContent(File driveFile, Drive driveService) throws IOException { if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) { GenericUrl downloadUrl = new GenericUrl(driveFile.getDownloadUrl()); HttpResponse resp = driveService.getRequestFactory().buildGetRequest(downloadUrl).execute(); return resp.getContent(); } else { //return an empty input stream return new ByteArrayInputStream("".getBytes()); } }
protected JSONObject queryApi() { String baseUrl = apiAccess.getApiUrl() + requestUrl; log.info("Sending API request [ Method: " + requestMethod + " ] [ URL: " + baseUrl + " ] [ Arguments: " + requiredArgs + " ]"); JSONObject responseJson = null; Stopwatch timer = Stopwatch.createStarted(); try { HttpResponse response = null; if(requestMethod == ERequestMethod.GET) { String url = HttpHelpers.appendUrlParameters(baseUrl, requiredArgs); response = httpClient.doGet(url); } else if(requestMethod == ERequestMethod.POST) { JSONObject postBody = new JSONObject(requiredArgs); response = httpClient.doPost(baseUrl, MediaType.JSON_UTF_8, postBody.toString(), null); } responseJson = HttpClient.getResponseAsJson(response); } catch (HttpClientRequestFailedException e) { log.error("Failed to send request! Error - " + e.getMessage(), e); responseJson = new JSONObject() .put("success", false) .put("exception", e.getMessage()); } log.info("API response received [ Method: " + requestMethod + " ] [ URL: " + baseUrl + " ] [ In Flight: " + timer.stop() + " ]"); return responseJson; }
/** * An annoying workaround to the issue that some github APi calls * are not exposed by egit library * * @param url * @return * @throws IOException */ private Map<String, Object> lowLevelGetRequest(String url) throws IOException { NetHttpTransport transport = new NetHttpTransport.Builder().build(); HttpRequestFactory requestFactory = transport.createRequestFactory(); HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url)); HttpResponse execute = httpRequest.execute(); InputStream content = execute.getContent(); String s = IOUtils.toString(content, StandardCharsets.UTF_8); Gson gson = new Gson(); Type stringStringMap = new TypeToken<Map<String, Object>>() { }.getType(); return gson.fromJson(s, stringStringMap); }
public Pong execute() throws IOException { HttpResponse response = this.httpRequest.execute(); HttpHeaders headers = response.getHeaders(); String version = headers.getFirstHeaderStringValue("X-Rqlite-Version"); return new Pong(version); }
public static DatabaseImport createFromGoogleDriveBackup(Context context, DatabaseAdapter dbAdapter, Drive drive, com.google.api.services.drive.model.File file) throws IOException { HttpResponse response = drive.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute(); InputStream inputStream = response.getContent(); InputStream in = new GZIPInputStream(inputStream); return new DatabaseImport(context, dbAdapter, in); }
/** * Fetches the service configuration with the given service name and service version. * * @param serviceName the given service name * @param serviceVersion the given service version * @return a {@link Service} object generated by the JSON response from Google Service Management. */ private Service fetch(String serviceName, @Nullable String serviceVersion) { Preconditions.checkArgument( !Strings.isNullOrEmpty(serviceName), "service name must be specified"); if (serviceVersion == null) { serviceVersion = fetchLatestServiceVersion(serviceName); } final HttpResponse httpResponse; try { httpResponse = serviceManagement.services().configs().get(serviceName, serviceVersion) .setFields(FIELD_MASKS) .executeUnparsed(); } catch (IOException exception) { throw new ServiceConfigException(exception); } int statusCode = httpResponse.getStatusCode(); if (statusCode != HttpStatusCodes.STATUS_CODE_OK) { String message = MessageFormat.format( "Failed to fetch service config (status code {0})", statusCode); throw new ServiceConfigException(message); } Service service = parseHttpResponse(httpResponse); validateServiceConfig(service, serviceName, serviceVersion); return service; }
private static Service parseHttpResponse(HttpResponse httpResponse) { try { Builder builder = Service.newBuilder(); JsonFormat.parser().merge(httpResponse.parseAsString(), builder); return builder.build(); } catch (IOException exception) { throw new ServiceConfigException( "Failed to parse the HTTP response as service configuration", exception); } }
<T> T executeAndParse(HttpRequest request, Class<T> cls) throws IOException { if (log.isDebugEnabled()) { log.debug("Calling {} on {}", request.getRequestMethod(), request.getUrl()); } HttpResponse response = request.execute(); if (response.isSuccessStatusCode()) { return response.parseAs(cls); } else { SalesforceException exception = response.parseAs(SalesforceException.class); throw exception; } }
@Test public void testExecuteMediaETagIsNotRevisionETag() throws Exception { // Given File file = createTextFile("myFile.txt", "the contents"); Revision revision = gdriveConnectionRule.getDrive().revisions().get(file.getId(), "head").execute(); // When HttpResponse responseExecuteMedia = gdriveConnectionRule.getDrive().files().get(file.getId()).executeMedia(); // Then assertNotEquals(revision.getEtag(), responseExecuteMedia.getHeaders().getETag()); }
private String retrieveJwksJson(GenericUrl jwksUri) { try { HttpResponse response = this.httpRequestFactory.buildGetRequest(jwksUri).execute(); return response.parseAsString(); } catch (IOException exception) { String message = String.format("Cannot retrive the JWKS json from %s", jwksUri.build()); throw new UnauthenticatedException(message, exception); } }
@Override public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException { // We will retry if the request supports retry and the status code requires a backoff // and the backoff was successful. Note that the order of these checks is important since // backOffWasSuccessful will perform a sleep. boolean willRetry = supportsRetry && retryOnStatusCode(response.getStatusCode()) && backOffWasSuccessful(unsuccessfulResponseBackOff); if (willRetry) { unsuccessfulResponseRetries += 1; LOG.debug("Request failed with code {}, will retry: {}", response.getStatusCode(), request.getUrl()); } else { String message = "Request failed with code {}, " + "performed {} retries due to IOExceptions, " + "performed {} retries due to unsuccessful status codes, " + "HTTP framework says request {} be retried, " + "(caller responsible for retrying): {}"; if (ignoredResponseCodes.contains(response.getStatusCode())) { // Log ignored response codes at a lower level LOG.debug(message, response.getStatusCode(), ioExceptionRetries, unsuccessfulResponseRetries, supportsRetry ? "can" : "cannot", request.getUrl()); } else { LOG.warn(message, response.getStatusCode(), ioExceptionRetries, unsuccessfulResponseRetries, supportsRetry ? "can" : "cannot", request.getUrl()); } } return willRetry; }
protected Response put(String endPoint, JAXBElement<?> object, Map<String, String> params) { String contents = marshallRequest(object); OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "PUT", contents, params); req.setToken(token); req.setTokenSecret(tokenSecret); try { HttpResponse resp = req.execute(); return unmarshallResponse(resp.parseAsString(), Response.class); } catch (IOException ioe) { throw xeroExceptionHandler.convertException(ioe); } }
@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(); } }
protected Response post(String endPoint, JAXBElement<?> object) throws IOException { String contents = marshallRequest(object); OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "POST", contents, null); req.setToken(token); req.setTokenSecret(tokenSecret); try { HttpResponse resp = req.execute(); return unmarshallResponse(resp.parseAsString(), Response.class); } catch (IOException ioe) { throw xeroExceptionHandler.convertException(ioe); } }
protected Response post(String endPoint, JAXBElement<?> object, Map<String, String> params) throws IOException { String contents = marshallRequest(object); OAuthRequestResource req = new OAuthRequestResource(config, signerFactory, endPoint, "POST", contents, params); req.setToken(token); req.setTokenSecret(tokenSecret); try { HttpResponse resp = req.execute(); return unmarshallResponse(resp.parseAsString(), Response.class); } catch (IOException ioe) { throw convertException(ioe); } }
public static int sendPostMultipart(String urlString, Map<String, String> parameters) throws IOException { MultipartContent postBody = new MultipartContent() .setMediaType(new HttpMediaType("multipart/form-data")); postBody.setBoundary(MULTIPART_BOUNDARY); for (Map.Entry<String, String> entry : parameters.entrySet()) { HttpContent partContent = ByteArrayContent.fromString( // uses UTF-8 internally null /* part Content-Type */, entry.getValue()); HttpHeaders partHeaders = new HttpHeaders() .set("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""); postBody.addPart(new MultipartContent.Part(partHeaders, partContent)); } GenericUrl url = new GenericUrl(new URL(urlString)); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody); request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT)); request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS); request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS); HttpResponse response = request.execute(); return response.getStatusCode(); }
public HttpResponse get() { try { final HttpRequest request = httpTransport.createRequestFactory().buildGetRequest(genericUrl); request.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); return request.execute(); } catch (final IOException e) { throw new RuntimeException(e); } }
private HttpBackOffUnsuccessfulResponseHandler getHttpBackOffUnsuccessfulResponseHandler() { HttpBackOffUnsuccessfulResponseHandler backOffHandler = new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff.Builder().setInitialIntervalMillis(200).setMaxElapsedTimeMillis(60000).build()); backOffHandler.setBackOffRequired( (HttpResponse response) -> response.getStatusCode() / 100 == 5 || isRateLimitExceeded(response)); return backOffHandler; }
/** * Richiede ad Alfresco la creazione di una <i>thumbnail</i>. * <p> * Si tenga presente che in caso di creazione asincrona la <i>thumbnail</i> potrebbe non essere * subito disponibile anche se il metodo ha restituito informazioni valide. * * @param pContentId * L'id del contenuto. * @param pThumbDefinition * Il nome della <i>thumbnail</i> di cui si richiede la crezione. * @param pAsync * Se la crazione deve essere sincrona ({@code true} o asincrona ({@false}). * * @return La <i>thumbnail</i> richiesta o {@code null} se il tipo di <i>thumbnail</i> di cui si * è richiesta la creazione non è valido per il contenuto specificato. * * @throws IOException */ public Thumbnail createThumbnail(String pContentId, String pThumbDefinition, boolean pAsync) throws IOException { /* * POST <base>/content{property}/thumbnails?as={async?} * * { * "thumbnailName": <name> * } */ GenericUrl lUrl = getContentUrl(pContentId); lUrl.appendRawPath(URL_RELATIVE_THUMBNAILS); lUrl.set("as", pAsync); // Recupero delle definizioni valide // Purtroppo Alfresco restituisce successo anche se viene richiesta la generazione di una // thumbnail non possibile. Controllando preventivamente si può restituire null. List<String> lThumbDefinitions = getThumbnailDefinitions(pContentId); if (!lThumbDefinitions.contains(pThumbDefinition)) { return null; } JsonHttpContent lContent = new JsonHttpContent(JSON_FACTORY, new Thumbnail(pThumbDefinition)); HttpHeaders lRequestHeaders = new HttpHeaders().setContentType("application/json"); HttpRequest lRequest = mHttpRequestFactory.buildPostRequest(lUrl, lContent).setHeaders(lRequestHeaders); HttpResponse lResponse = lRequest.execute(); Thumbnail lThumbnail = lResponse.parseAs(Thumbnail.class); return lThumbnail; }
@Override public boolean handleResponse( HttpRequest httpRequest, HttpResponse httpResponse, boolean supportsRetry) throws IOException { if (!httpResponse.isSuccessStatusCode() && httpResponse.getStatusCode() == ACCESS_DENIED) { throwNullCredentialException(); } return supportsRetry; }
public OauthToken exchangeAuthorizationForToken(String code, String clientId, String clientSecret, Map<String, Object> options) throws DnsimpleException, IOException { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("code", code); attributes.put("client_id", clientId); attributes.put("client_secret", clientSecret); attributes.put("grant_type", "authorization_code"); if (options.containsKey("state")) { attributes.put("state", options.remove("state")); } if (options.containsKey("redirect_uri")) { attributes.put("redirect_uri", options.remove("redirect_uri")); } HttpResponse response = client.post("oauth/access_token", attributes); InputStream in = response.getContent(); if (in == null) { throw new DnsimpleException("Response was empty", null, response.getStatusCode()); } else { try { JsonParser jsonParser = GsonFactory.getDefaultInstance().createJsonParser(in); return jsonParser.parse(OauthToken.class); } finally { in.close(); } } }