/** * 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(); }
@Before public void setUpMocksAndFakes() throws IOException { fakeRequest = Request.builder() .setAccept(Arrays.asList("fake.accept", "another.fake.accept")) .setBody(new BlobHttpContent(Blobs.from("crepecake"), "fake.content.type")) .setAuthorization(Authorizations.withBasicToken("fake-token")) .build(); Mockito.when( mockHttpRequestFactory.buildRequest( Mockito.any(String.class), Mockito.eq(fakeUrl), Mockito.any(BlobHttpContent.class))) .thenReturn(mockHttpRequest); Mockito.when(mockHttpRequest.setHeaders(Mockito.any(HttpHeaders.class))) .thenReturn(mockHttpRequest); Mockito.when(mockHttpRequest.execute()).thenReturn(mockHttpResponse); }
private static boolean hasMetadataServer(HttpTransport transport) { try { HttpRequest request = transport.createRequestFactory() .buildGetRequest(new GenericUrl(METADATA_SERVER_URL)); HttpResponse response = request.execute(); HttpHeaders headers = response.getHeaders(); return "Google".equals(headers.getFirstHeaderStringValue("Metadata-Flavor")); } catch (IOException | RuntimeException expected) { // If an error happens, it's probably safe to say the metadata service isn't available where // the code is running. We have to catch ApiProxyException due to the new dev server returning // a different error for unresolvable hostnames. Due to not wanting to put a required // dependency on the App Engine SDK here, we catch the generic RuntimeException and do a // class name check. if (expected instanceof RuntimeException && !API_PROXY_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName()) && !REMOTE_API_EXCEPTION_CLASS_NAME.equals(expected.getClass().getName())) { throw (RuntimeException) expected; } } return false; }
public OAuthAccessToken build() throws IOException { Url = new GenericUrl(config.getAccessTokenUrl()); transport = new ApacheHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(); request = requestFactory.buildRequest(HttpMethods.GET, Url, null); HttpHeaders headers = new HttpHeaders(); headers.setUserAgent(config.getUserAgent()); headers.setAccept(config.getAccept()); request.setHeaders(headers); createRefreshParameters().intercept(request); return this; }
@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("Maximum number of keys on service account reached: " + SERVICE_ACCOUNT); sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT); }
@Test public void testGetTemplate() throws DnsimpleException, IOException { Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/templates/1", HttpMethods.GET, new HttpHeaders(), null, resource("getTemplate/success.http")); String accountId = "1010"; String templateId = "1"; GetTemplateResponse response = client.templates.getTemplate(accountId, templateId); Template template = response.getData(); assertEquals(1, template.getId().intValue()); assertEquals(1010, template.getAccountId().intValue()); assertEquals("Alpha", template.getName()); assertEquals("alpha", template.getShortName()); assertEquals("An alpha template.", template.getDescription()); assertEquals("2016-03-22T11:08:58Z", template.getCreatedAt()); assertEquals("2016-03-22T11:08:58Z", template.getUpdatedAt()); }
@Test public void testRegisterDomain() throws DnsimpleException, IOException { String accountId = "1010"; String name = "example.com"; HashMap<String, Object> attributes = new HashMap<String, Object>(); attributes.put("registrant_id", "10"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/registrar/domains/example.com/registrations", HttpMethods.POST, new HttpHeaders(), attributes, resource("registerDomain/success.http")); RegisterDomainResponse response = client.registrar.registerDomain(accountId, name, attributes); DomainRegistration registration = response.getData(); assertEquals(1, registration.getId().intValue()); assertEquals(999, registration.getDomainId().intValue()); assertEquals(2, registration.getRegistrantId().intValue()); assertEquals("new", registration.getState()); assertFalse(registration.hasAutoRenew()); assertFalse(registration.hasWhoisPrivacy()); assertEquals("2016-12-09T19:35:31Z", registration.getCreatedAt()); assertEquals("2016-12-09T19:35:31Z", registration.getUpdatedAt()); }
@Test public void testGetWhoisPrivacy() throws DnsimpleException, IOException { String accountId = "1010"; String domainId = "example.com"; Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/registrar/domains/example.com/whois_privacy", HttpMethods.GET, new HttpHeaders(), null, resource("getWhoisPrivacy/success.http")); GetWhoisPrivacyResponse response = client.registrar.getWhoisPrivacy(accountId, domainId); WhoisPrivacy whoisPrivacy = response.getData(); assertEquals(1, whoisPrivacy.getId().intValue()); assertEquals(2, whoisPrivacy.getDomainId().intValue()); assertEquals("2017-02-13", whoisPrivacy.getExpiresOn()); assertTrue(whoisPrivacy.getEnabled().booleanValue()); assertEquals("2016-02-13T14:34:50Z", whoisPrivacy.getCreatedAt()); assertEquals("2016-02-13T14:34:52Z", whoisPrivacy.getUpdatedAt()); }
@Test public void testChangeDomainDelegation() throws DnsimpleException, IOException { String accountId = "1010"; String domainId = "example.com"; List<String> nameServerNames = new ArrayList<String>(); nameServerNames.add("ns1.example.com"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/registrar/domains/example.com/delegation", HttpMethods.PUT, new HttpHeaders(), nameServerNames, resource("changeDomainDelegation/success.http")); ChangeDomainDelegationResponse response = client.registrar.changeDomainDelegation(accountId, domainId, nameServerNames); List<String> delegatedTo = response.getData(); assertEquals("ns1.dnsimple.com", delegatedTo.get(0)); assertEquals("ns2.dnsimple.com", delegatedTo.get(1)); assertEquals("ns3.dnsimple.com", delegatedTo.get(2)); assertEquals("ns4.dnsimple.com", delegatedTo.get(3)); }
@Test public void testChangeDomainDelegationToVanity() throws DnsimpleException, IOException { String accountId = "1010"; String domainId = "example.com"; List<String> nameServerNames = new ArrayList<String>(); nameServerNames.add("ns1.example.com"); nameServerNames.add("ns2.example.com"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/registrar/domains/example.com/delegation/vanity", HttpMethods.PUT, new HttpHeaders(), nameServerNames, resource("changeDomainDelegationToVanity/success.http")); ChangeDomainDelegationToVanityResponse response = client.registrar.changeDomainDelegationToVanity(accountId, domainId, nameServerNames); List<NameServer> delegatedTo = response.getData(); assertEquals(2, delegatedTo.size()); NameServer nameServer = delegatedTo.get(0); assertEquals("ns1.example.com", nameServer.getName()); assertEquals("127.0.0.1", nameServer.getIpv4()); assertEquals("::1", nameServer.getIpv6()); assertEquals("2016-07-11T09:40:19Z", nameServer.getCreatedAt()); assertEquals("2016-07-11T09:40:19Z", nameServer.getUpdatedAt()); }
@Test public void testGetTldExtendedAttributes() throws DnsimpleException, IOException { Client client = mockAndExpectClient("https://api.dnsimple.com/v2/tlds/uk/extended_attributes", HttpMethods.GET, new HttpHeaders(), null, resource("getTldExtendedAttributes/success.http")); String tldString = "uk"; GetTldExtendedAttributesResponse response = client.tlds.getTldExtendedAttributes(tldString); List<TldExtendedAttribute> extendedAttributes = response.getData(); assertEquals(4, extendedAttributes.size()); assertEquals("uk_legal_type", extendedAttributes.get(0).getName()); assertEquals("Legal type of registrant contact", extendedAttributes.get(0).getDescription()); assertEquals(false, extendedAttributes.get(0).getRequired().booleanValue()); List<TldExtendedAttributeOption> options = extendedAttributes.get(0).getOptions(); assertEquals(17, options.size()); assertEquals("UK Individual", options.get(0).getTitle()); assertEquals("IND", options.get(0).getValue()); assertEquals("UK Individual (our default value)", options.get(0).getDescription()); }
@Test public void testExchangeAuthorizationForToken() throws DnsimpleException, IOException { String clientId = "super-client-id"; String clientSecret = "super-client-secret"; String code = "super-code"; HashMap<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"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/oauth/access_token", HttpMethods.POST, new HttpHeaders(), attributes, resource("oauthAccessToken/success.http")); OauthToken token = client.oauth.exchangeAuthorizationForToken(code, clientId, clientSecret); assertEquals("zKQ7OLqF5N1gylcJweA9WodA000BUNJD", token.getAccessToken()); assertEquals("Bearer", token.getTokenType()); assertTrue(Data.isNull(token.getScope())); assertEquals(1, token.getAccountId().intValue()); }
@Test public void create_adminApiNotEnabled() throws IOException { ErrorInfo error = new ErrorInfo(); error.setReason(SslSocketFactory.ADMIN_API_NOT_ENABLED_REASON); GoogleJsonError details = new GoogleJsonError(); details.setErrors(ImmutableList.of(error)); when(adminApiInstancesGet.execute()) .thenThrow( new GoogleJsonResponseException( new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()), details)); SslSocketFactory sslSocketFactory = new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307); try { sslSocketFactory.create(INSTANCE_CONNECTION_STRING); fail("Expected RuntimeException"); } catch (RuntimeException e) { // TODO(berezv): should we throw something more specific than RuntimeException? assertThat(e.getMessage()).contains("Cloud SQL API is not enabled"); } }
@Test public void create_notAuthorizedToGetInstance() throws IOException { ErrorInfo error = new ErrorInfo(); error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON); GoogleJsonError details = new GoogleJsonError(); details.setErrors(ImmutableList.of(error)); when(adminApiInstancesGet.execute()) .thenThrow( new GoogleJsonResponseException( new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()), details)); SslSocketFactory sslSocketFactory = new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307); try { sslSocketFactory.create(INSTANCE_CONNECTION_STRING); fail("Expected RuntimeException"); } catch (RuntimeException e) { // TODO(berezv): should we throw something more specific than RuntimeException? assertThat(e.getMessage()).contains("not authorized"); } }
@Test public void create_notAuthorizedToCreateEphemeralCertificate() throws IOException { ErrorInfo error = new ErrorInfo(); error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON); GoogleJsonError details = new GoogleJsonError(); details.setErrors(ImmutableList.of(error)); when(adminApiSslCertsCreateEphemeral.execute()) .thenThrow( new GoogleJsonResponseException( new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()), details)); SslSocketFactory sslSocketFactory = new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307); try { sslSocketFactory.create(INSTANCE_CONNECTION_STRING); fail(); } catch (RuntimeException e) { // TODO(berezv): should we throw something more specific than RuntimeException? assertThat(e.getMessage()).contains("Unable to obtain ephemeral certificate"); } }
/** * 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)); }); }
public List<User> getUsersSince(int since) throws IOException { HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(API_ENDPOINT + "/users?since=" + since)); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("bearer " + tokenFactory.getToken()); request.setHeaders(headers); HttpResponse response = executeWithRetry(request); // TODO: Handle error status code List<JsonObject> userObjects = Json.createReader(new StringReader(response.parseAsString())).readArray().getValuesAs(JsonObject.class); List<User> users = new ArrayList<>(); for (JsonObject userObject : userObjects) { User user = new User(userObject.getInt("id"), userObject.getString("type")); user.setLogin(userObject.getString("login")); user.setAvatarUrl(userObject.getString("avatar_url")); users.add(user); } return users; }
private JsonObject graphql(String query) throws IOException { String payload = Json.createObjectBuilder() .add("query", query) .add("variables", "{}") .build().toString(); HttpRequest request = requestFactory.buildPostRequest( new GenericUrl(GRAPHQL_ENDPOINT), ByteArrayContent.fromString("application/json", payload)); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("bearer " + tokenFactory.getToken()); request.setHeaders(headers); HttpResponse response = executeWithRetry(request); // TODO: Handle error status code JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject(); if (responseObject.containsKey("errors")) { LOG.debug("errors with query:\n" + query); LOG.debug("response:\n" + responseObject.toString()); } return responseObject; }
@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); }
private <U, T extends ResponseEnvelope<U>> U execute(final HttpRequest httpRequest, final Class<T> responseType) throws IOException { httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff())); if (authToken != null) { HttpHeaders headers = httpRequest.getHeaders(); headers.set("X-Auth-Token", authToken); } HttpResponse httpResponse = httpRequest.execute(); T response = httpResponse.parseAs(responseType); // Update authToken, if necessary if (response.getAuthToken() != null) { authToken = response.getAuthToken(); } return response.getData(); }
/** * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then * checks if the event has been modified. */ private static void run() throws IOException { // Create a test event. Event event = Utils.createTestEvent(client, "Test Event"); System.out.println(String.format("Event created: %s", event.getHtmlLink())); // Pause while the user modifies the event in the Calendar UI. System.out.println("Modify the event's description and hit enter to continue."); System.in.read(); // Fetch the event again if it's been modified. Calendar.Events.Get getRequest = client.events().get("primary", event.getId()); getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag())); try { event = getRequest.execute(); System.out.println("The event was modified, retrieved latest version."); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 304) { // A 304 status code, "Not modified", indicates that the etags match, and the event has // not been modified since we last retrieved it. System.out.println("The event was not modified, using local version."); } else { throw e; } } }
/** * Retrieve part of the file. * * Example thing you may want to do with the result: * String str = new String( Arrays.copyOfRange(out.toByteArray() ); * * @throws IOException */ public ByteArrayOutputStream getPartialObjectData(String bucket, String fname, long start, long endIncl, @Nullable ByteArrayOutputStream optionalOldOutputToReuse) throws IOException { ByteArrayOutputStream out; if (null == optionalOldOutputToReuse) { out = new ByteArrayOutputStream((int) (endIncl - start + 1)); } else { out = optionalOldOutputToReuse; out.reset(); } Storage.Objects.Get getObject = storage.objects().get(bucket, fname); getObject.setRequestHeaders(new HttpHeaders().setRange( String.format("bytes=%d-%d", start, endIncl))); getObject.getMediaHttpDownloader().setDirectDownloadEnabled(!IS_APP_ENGINE); getObject.executeMediaAndDownloadTo(out); if (out.size() != (endIncl - start + 1)) { String err = "getPartialObjectData failed! Expected " + (endIncl - start + 1) + " bytes, got " + out.size(); LOGGER.log(Level.WARNING, err); throw new IOException(err); } return out; }
@Override public RESULT loadDataFromNetwork() throws Exception { HttpRequest request = getHttpRequestFactory().buildGetRequest( new GenericUrl(generateUrl()) ); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept("application/json") .setContentType("application/json"); String basicAuthName = getBasicAuthName(); String basicAuthPass = getBasicAuthPass(); if (basicAuthName != null && basicAuthPass != null){ httpHeaders.setBasicAuthentication(basicAuthName, basicAuthPass); } HttpResponse response = request.setHeaders(httpHeaders) .setParser(new JacksonFactory().createJsonObjectParser()) .execute(); Object res = response.parseAs(modelClass); return (RESULT) res; }
/** * Gets the cache TimeInMillis in seconds. "max-age" in "Cache-Control" header and "Age" header * are considered. * * @param httpHeaders the http header of the response * @return the cache TimeInMillis in seconds or zero if the response should not be cached */ long getExpirationDurationInSeconds(HttpHeaders httpHeaders) { long expirationDurationInSeconds = 0; if (httpHeaders.getCacheControl() != null) { for (String arg : httpHeaders.getCacheControl().split(",")) { Matcher m = MAX_AGE_PATTERN.matcher(arg); if (m.matches()) { expirationDurationInSeconds = Long.valueOf(m.group(1)); break; } } } if (httpHeaders.getAge() != null) { expirationDurationInSeconds -= httpHeaders.getAge(); } return Math.max(0, expirationDurationInSeconds); }
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) { StringBuilder messageBuilder = new StringBuilder(); if (headers != null) { appendMapAsString(messageBuilder, headers); } if (content != null) { messageBuilder.append(String.format("%nContent:%n")); if (content instanceof UrlEncodedContent) { UrlEncodedContent encodedContent = (UrlEncodedContent) content; appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData())); } else if (content != null) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { content.writeTo(byteStream); messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name())); } catch (IOException e) { messageBuilder.append("Unable to read request content due to exception: " + e); } } } return messageBuilder.toString(); }
/** * Gets the report HTTP URL connection given report URL and proper information needed to * authenticate the request. * * @param reportUrl the URL of the report response or download * @return the report HTTP URL connection * @throws AuthenticationException If OAuth authorization fails. */ @VisibleForTesting HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version) throws AuthenticationException { final HttpHeaders httpHeaders = createHeaders(reportUrl, version); return httpTransport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { request.setHeaders(httpHeaders); request.setConnectTimeout(reportDownloadTimeout); request.setReadTimeout(reportDownloadTimeout); request.setThrowExceptionOnExecuteError(false); request.setLoggingEnabled(true); request.setResponseInterceptor(responseInterceptor); } }); }
/** * Tests behavior when URL validation is disabled. */ @Test public void testUrlMismatch_verifyDisabled() throws IOException { MockResponse mockResponse = new MockResponse("test response"); mockResponse.setValidateUrlMatches(false); HttpRequest request = mockHttpServer .getHttpTransport() .createRequestFactory() .buildGetRequest( new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url")); request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8))); HttpHeaders headers = new HttpHeaders(); headers.set("one", "1"); headers.set("two", "2"); request.setHeaders(headers); mockHttpServer.setMockResponse(mockResponse); HttpResponse response = request.execute(); ActualResponse actualResponse = mockHttpServer.getLastResponse(); assertEquals("Incorrect response code", 200, response.getStatusCode()); assertEquals( "Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0)); assertEquals( "Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0)); }
private void checkRequestHeaders(TestResponseInterceptor interceptor) { HttpHeaders headers = interceptor.getResponse().getRequest().getHeaders(); String auth = "Bearer " + TEST_TOKEN; assertEquals(auth, headers.getFirstHeaderStringValue("Authorization")); String clientVersion = "Java/Admin/" + SdkUtils.getVersion(); assertEquals(clientVersion, headers.getFirstHeaderStringValue("X-Client-Version")); }
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); }
@Test public void notFoundResponseIsNotPermissionDenied() throws Exception { assertThat(GcpUtil.isPermissionDenied(new GoogleJsonResponseException( new Builder(404, "Not Found", new HttpHeaders()), new GoogleJsonError())), is(false)); assertThat(GcpUtil.isPermissionDenied(new GoogleJsonResponseException( new Builder(404, "Not Found", new HttpHeaders()), null)), is(false)); }
@Test public void notFoundResponseIsNotPResourceExhausted() throws Exception { assertThat(GcpUtil.isResourceExhausted(new GoogleJsonResponseException( new Builder(404, "Not Found", new HttpHeaders()), new GoogleJsonError())), is(false)); assertThat(GcpUtil.isResourceExhausted(new GoogleJsonResponseException( new Builder(404, "Not Found", new HttpHeaders()), null)), is(false)); }
/** * 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; }
public static boolean addChildToGroup(HttpRequestFactory pHttpRequestFactory, AlfrescoConfig pConfig, String pStrGroupId, String pStrChildId) { mLog.debug("START addChildToGroup(String, String)"); boolean lRet = false; GroupsUrl lUrl = new GroupsUrl(pConfig.getHost()); lUrl.addChild(pStrGroupId, pStrChildId); try { // FIXME (Alessio): bisognerebbe trasferire altrove questo codice ripetitivo HttpHeaders lRequestHeaders = new HttpHeaders().setContentType("application/json"); HttpRequest lRequest = pHttpRequestFactory.buildPostRequest(lUrl, new EmptyContent()).setHeaders(lRequestHeaders); // TODO (Alessio): la risposta è completamente ignorata! Vanno gestiti i diversi casi // possibili. // L'implementazione dovrebbe prima controllare se l'utente è già parte del gruppo, // quindi eventualmente effettuare l'aggiunta. int lStatusCode = lRequest.execute().getStatusCode(); if (200 <= lStatusCode && lStatusCode < 300) { lRet = true; } } catch (Exception e) { // TODO (Alessio): gestione decente delle eccezioni // mLog.error("Unexpected failure", e); lRet = false; } mLog.debug("END addChildToGroup(String, String)"); return lRet; }
@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() .map(GoogleDirectoryUserRolesProvider::toRole) .collect(Collectors.toSet()); emailGroupsMap.put(email, groupSet); }
@Test public void testAuthorizationHeader() throws DnsimpleException, IOException { HttpHeaders headers = getDefaultHeaders(); headers.setAuthorization("Bearer " + TEST_ACCESS_TOKEN); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/accounts", HttpMethods.GET, headers, null, resource("listAccounts/success-account.http")); client.accounts.listAccounts(); }
@Test public void testUserAgentHeader() throws DnsimpleException, IOException { HttpHeaders headers = getDefaultHeaders(); headers.setUserAgent("my-user-agent dnsimple-java/0.3.0 Google-HTTP-Java-Client/1.20.0 (gzip)"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/accounts", HttpMethods.GET, headers, null, resource("listAccounts/success-account.http")); client.setUserAgent("my-user-agent"); client.accounts.listAccounts(); }
@Test public void testCreateZoneRecordSendsCorrectRequest() throws DnsimpleException, IOException { String accountId = "1010"; String zoneId = "example.com"; HttpHeaders headers = new HttpHeaders(); headers.setContentType("application/json"); HashMap<String, Object> attributes = new HashMap<String, Object>(); attributes.put("name", "www"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1010/zones/example.com/records", HttpMethods.POST, headers, attributes, resource("createZoneRecord/created.http")); client.zones.createZoneRecord(accountId, zoneId, attributes); }
@Test public void testUpdateZoneRecordProducesZoneRecord() throws DnsimpleException, IOException { String accountId = "1"; String zoneId = "example.com"; String recordId = "2"; HashMap<String, Object> attributes = new HashMap<String, Object>(); attributes.put("name", "www"); Client client = mockAndExpectClient("https://api.dnsimple.com/v2/1/zones/example.com/records/2", HttpMethods.PATCH, new HttpHeaders(), attributes, resource("updateZoneRecord/success.http")); UpdateZoneRecordResponse response = client.zones.updateZoneRecord(accountId, zoneId, recordId, attributes); ZoneRecord record = response.getData(); assertEquals(5, record.getId().intValue()); }