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(); } }
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)); }
private User getUserInfoJson(final String authCode) throws IOException { try { final GoogleTokenResponse response = flow.newTokenRequest(authCode) .setRedirectUri(getCallbackUri()) .execute(); final Credential credential = flow.createAndStoreCredential(response, null); final HttpRequest request = HTTP_TRANSPORT.createRequestFactory(credential) .buildGetRequest(new GenericUrl(USER_INFO_URL)); request.getHeaders().setContentType("application/json"); final JSONObject identity = new JSONObject(request.execute().parseAsString()); return new User( identity.getString("id"), identity.getString("email"), identity.getString("name"), identity.getString("picture")); } catch (JSONException ex) { Logger.getLogger(AuthenticationResource.class.getName()).log(Level.SEVERE, null, ex); return null; } }
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; }
@Override public JsonWebKeySet supply(String issuer) { Preconditions.checkNotNull(issuer); Optional<GenericUrl> jwksUri = this.keyUriSupplier.supply(issuer); if (!jwksUri.isPresent()) { String message = String.format("Cannot find the jwks_uri for issuer %s: " + "either the issuer is unknown or the OpenID discovery failed", issuer); throw new UnauthenticatedException(message); } String rawJson = retrieveJwksJson(jwksUri.get()); Map<String, Object> rawMap = parse(rawJson, new TypeReference<Map<String, Object>>() {}); if (rawMap.containsKey("keys")) { // De-serialize the JSON string as a JWKS object. return extractJwks(rawJson); } // Otherwise try to de-serialize the JSON string as a map mapping from key // id to X.509 certificate. return extractX509Certificate(rawJson); }
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; }
private OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, Map<? extends String, ?> params) { this.config = config; this.signerFactory = signerFactory; Url = new GenericUrl(config.getApiUrl() + resource); this.httpMethod = method; if(method.equals("POST") || method.equals("PUT")){ usePost = true; } if (params != null) { Url.putAll(params); } connectTimeout = config.getConnectTimeout() * 1000; readTimeout = config.getReadTimeout() * 1000; //Proxy Service Setup if(!"".equals(config.getProxyHost()) && config.getProxyHost() != null) { String host = config.getProxyHost(); boolean httpsEnabled = config.getProxyHttpsEnabled(); int port = (int) (config.getProxyPort() == 80 && httpsEnabled ? 443 : config.getProxyPort()); this.setProxy(host, port, httpsEnabled); } }
protected <E> E postRequest(String path, Object body, Class<E> responseType){ try { URI uri = uri(path); GenericUrl url = new GenericUrl(uri); if ( logger.isDebugEnabled() ){ logger.debug("Request POSTed into botframework api " + uri + ":"); logger.debug(JSON_FACTORY.toPrettyString(body)); } HttpContent content = new JsonHttpContent(JSON_FACTORY,body); HttpRequest request = requestFactory.buildPostRequest(url,content); E response = (E) request.execute().parseAs(responseType); if ( logger.isDebugEnabled() ){ logger.debug("Response back from botframework api:"); logger.debug(JSON_FACTORY.toPrettyString(response)); } return response; } catch (IOException e) { throw new RuntimeException(e); } }
protected Future<HttpResponse> postRequestAsync(String path, Object body){ try { URI uri = uri(path); GenericUrl url = new GenericUrl(); if ( logger.isDebugEnabled() ){ logger.debug("Request POSTed into botframework api " + uri + ":"); logger.debug(JSON_FACTORY.toPrettyString(body)); } HttpContent content = new JsonHttpContent(JSON_FACTORY,body); HttpRequest request = requestFactory.buildPostRequest(url,content); if ( this.executor != null ){ return request.executeAsync(this.executor); } else{ return request.executeAsync(); } } catch (IOException e) { throw new RuntimeException(e); } }
/** * Recupera le definizioni di thumbnail valide per il contenuto. * * @param pContentId * L'id del contenuto. * * @return La lista delle definizioni valide. * * @throws IOException */ public List<String> getThumbnailDefinitions(String pContentId) throws IOException { /* * GET <base>/content{property}/thumbnaildefinitions */ GenericUrl lUrl = getContentUrl(pContentId); lUrl.appendRawPath(URL_RELATIVE_THUMBNAIL_DEFINITIONS); HttpRequest lRequest = mHttpRequestFactory.buildGetRequest(lUrl); TypeReference<List<String>> lType = new TypeReference<List<String>>() {}; @SuppressWarnings("unchecked") List<String> lResponse = (List<String>) lRequest.execute().parseAs(lType.getType()); return lResponse; }
private GenericUrl buildUrl(String url, Map<String, Object> options) { if (options == null) { options = Collections.emptyMap(); } UrlBuilder urlBuilder = UrlBuilder.fromString(url); if (options.containsKey("filter")) { Filter filter = (Filter)options.remove("filter"); urlBuilder = urlBuilder.addParameter(filter.name, filter.value); } if (options.size() > 0) { for (Map.Entry<String, Object> kv : options.entrySet()) { urlBuilder = urlBuilder.addParameter(kv.getKey(), kv.getValue().toString()); } } return new GenericUrl(urlBuilder.toUrl()); }
public String executeStmt(String method, String urlString, String statement, List<NameValuePair> qparams) throws IOException { Check.notNull(statement); GenericUrl url = setParams(new GenericUrl(urlString), qparams); UrlEncodedContent urlEntity = setMediaType(getUrlEncodedSql(statement)); HttpRequestFactory rf = httpTransport.createRequestFactory(credential); HttpResponse response = rf.buildRequest(method, url, urlEntity).execute(); String result = readGoogleResponse(response); if (response.getStatusCode() != HttpServletResponse.SC_OK) throw new RuntimeException(result.toString() + statement); return result; }
private HttpRequest constructHttpRequest(final String content) throws IOException { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setContentType("application/json"); result.setContent(content); return result; } }; } }; return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")) .setParser(new JsonObjectParser(new JacksonFactory())); }
@SuppressWarnings("unchecked") @Override public <T> T post(String path, Object request, Type responseType) throws RepoException, ValidationException { HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials()); GenericUrl url = new GenericUrl(URI.create(API_URL + "/" + path)); try { HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(JSON_FACTORY, request)); HttpResponse response = httpRequest.execute(); return (T) response.parseAs(responseType); } catch (IOException e) { throw new RepoException("Error running GitHub API operation " + path, e); } }
public String get(String url) { try { HttpRequest request = new NetHttpTransport() .createRequestFactory() .buildGetRequest(new GenericUrl(url)); HttpResponse response = request.execute(); InputStream is = response.getContent(); StringBuilder sb = new StringBuilder(); int ch; while ((ch = is.read()) != -1) { sb.append((char) ch); } response.disconnect(); return sb.toString(); } catch (Exception e) { throw new RuntimeException(); } }
@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); } }
/** * Builds a HttpResponse with the given string response. * * @param header header value to provide or null if none. * @param uploadId upload id to provide in the url upload id param or null if none. * @param uploadType upload type to provide in url upload type param or null if none. * @return HttpResponse with the given parameters * @throws IOException */ private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType) throws IOException { MockHttpTransport.Builder builder = new MockHttpTransport.Builder(); MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse(); builder.setLowLevelHttpResponse(resp); resp.setStatusCode(200); GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL); if (header != null) { resp.addHeader("X-GUploader-UploadID", header); } if (uploadId != null) { url.put("upload_id", uploadId); } if (uploadType != null) { url.put("uploadType", uploadType); } return builder.build().createRequestFactory().buildGetRequest(url).execute(); }
public static String getClientEmail(String accessToken) throws IOException { /* * Get loggined user info as described in * https://developers.google.com/accounts/docs/OAuth2Login#userinfocall */ GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken); HttpRequest request = HTTP_REQUEST_FACTORY.buildGetRequest(url); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { throw new IOException(response.getStatusMessage()); } JsonElement jsonElement = new JsonParser().parse(new InputStreamReader(response.getContent(), "utf-8")); JsonObject jsonObj = jsonElement.getAsJsonObject(); return jsonObj.get("email").getAsString(); }
public Station getStationDetails(Station station) throws Exception { try { HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT); HttpRequest request = httpRequestFactory .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL)); request.getUrl().put("key", API_KEY); request.getUrl().put("reference", station.getReference()); request.getUrl().put("sensor", "false"); String place = request.execute().parseAsString(); return parser.stationFromJson(station, place); } catch (HttpResponseException e) { Log.e("ErrorDetails", e.getMessage()); throw e; } }
@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; } }
public Builder( Credential.AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { super( method, transport, jsonFactory, tokenServerUrl, clientAuthentication, clientId, authorizationServerEncodedUrl); }
public Credential authorize() { String authorizationUrl = new AuthorizationCodeRequestUrl(AUTHORIZATION_SERVER_URL, OAuth2ClientCredentials.CLIENT_ID).setRedirectUri(URN_IETF_WG_OAUTH_2_0_OOB).setScopes(SCOPES).build(); System.out.println("Please point your browser to the following URL and copy the access token provided after having authorized this application to access your Google Drive:"); System.out.println(authorizationUrl); String code = readCode(); AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl( TOKEN_SERVER_URL), new ClientParametersAuthentication(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET), OAuth2ClientCredentials.CLIENT_ID, AUTHORIZATION_SERVER_URL ).setScopes(SCOPES).build(); try { TokenResponse response = codeFlow.newTokenRequest(code).setScopes(SCOPES).setRedirectUri(URN_IETF_WG_OAUTH_2_0_OOB).execute(); return codeFlow.createAndStoreCredential(response, null); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute token request and store credentials: " + e.getMessage(), e); } }
private InputStream downloadFile(com.google.api.services.drive.Drive service, com.google.api.services.drive.model.File file) { if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { try { HttpResponse resp = service.getRequestFactory() .buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute(); return resp.getContent(); } catch (IOException e) { // An error occurred. e.printStackTrace(); return null; } } else { // The file doesn't have any content stored on Drive. return null; } }
public void putDroplets(String userName, List<Droplet> droplets) throws Exception { try { System.out.println("Perform droplet search ...."); HttpRequestFactory httpRequestFactory = createRequestFactory(transport); HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets); HttpRequest request = httpRequestFactory.buildPostRequest( new GenericUrl(DROPLET_POST_URL + userName), content); HttpResponse response = request.execute(); System.out.println(response.getStatusCode()); } catch (HttpResponseException e) { System.err.println(e.getStatusMessage()); throw e; } }
@Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); GenericUrl requestUrl = new GenericUrl(originalRequest.urlString()); oAuthParams.computeNonce(); oAuthParams.computeTimestamp(); try { oAuthParams.computeSignature("GET", requestUrl); Request compressedRequest = originalRequest.newBuilder() .header("Authorization", oAuthParams.getAuthorizationHeader()) .header("Accept","application/xml") .method(originalRequest.method(),originalRequest.body()) .build(); return chain.proceed(compressedRequest); } catch (GeneralSecurityException e) { } return chain.proceed(originalRequest); }
public String readFile(File file) throws Exception { String link = file.getDownloadUrl(); if (TextUtils.isEmpty(link)) { Log.w(TAG, "The file doesn't have any content stored on Drive."); return null; } Log.d(TAG, "Opening file " + file.getTitle()); HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(link)).execute(); InputStream inputStream = null; try { inputStream = resp.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) content.append(line).append("\n"); return content.toString(); } finally { if (inputStream != null) inputStream.close(); } }
private void getTokenFromCode(final String code) throws IOException { log.debug("Fetching authorisation token using authorisation code"); HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl("https://login.live.com/oauth20_token.srf") { @Key("client_id") private String id = clientId; @Key("client_secret") private String secret = clientSecret; @Key("code") private String authCode = code; @Key("grant_type") private String grantType = "authorization_code"; @Key("redirect_uri") private String redirect = "https://login.live.com/oauth20_desktop.srf"; }); request.setParser(new JsonObjectParser(JSON_FACTORY)); processResponse(request.execute()); }
private void getTokenFromRefreshToken(final String refreshToken) throws IOException { log.debug("Fetching authorisation token using refresh token"); HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl("https://login.live.com/oauth20_token.srf") { @Key("client_id") private String id = clientId; @Key("client_secret") private String secret = clientSecret; @Key("refresh_token") private String token = refreshToken; @Key("grant_type") private String grantType = "refresh_token"; @Key("redirect_uri") private String redirect = "https://login.live.com/oauth20_desktop.srf"; }); request.setParser(new JsonObjectParser(JSON_FACTORY)); processResponse(request.execute()); }
public OAuthApp(String clientID, String clientSecret, String redirectUri, String accessToken, String refreshToken, HttpTransport transport, JsonFactory jsonFactory) { this.redirectUri = redirectUri; this.flow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl(TOKEN_SERVER_URL), new ClientParametersAuthentication(clientID, clientSecret), clientID, AUTHORIZATION_SERVER_URL ).build(); if (accessToken != null) { credential = new Credential(BearerToken.authorizationHeaderAccessMethod()) .setAccessToken(accessToken) .setRefreshToken(refreshToken); } }
@Test public void testSimpleRequest_405_notSupported() throws IOException, Failure, TException { GenericUrl url = endpoint(); url.setRawPath("/does_not_exists"); TestService.Iface client = new TestService.Client(new HttpClientHandler( () -> url, factory(), provider, instrumentation)); try { client.test(new Request("request")); fail("No exception"); } catch (HttpResponseException ex) { assertThat(ex.getStatusCode(), is(405)); assertThat(ex.getStatusMessage(), is("HTTP method POST is not supported by this URL")); } verify(instrumentation).onTransportException(any(HttpResponseException.class), anyDouble(), any(PServiceCall.class), isNull()); verifyNoMoreInteractions(impl, instrumentation); }
@Test public void testProvidenceServlet() throws IOException, CalculateException { // This test is just to prove that the providence servlet can be used in dropwizard too. Calculator.Iface client = new Calculator.Client(new HttpClientHandler( () -> new GenericUrl(uri("test")), factory(), new DefaultSerializerProvider() )); Operand result = client.calculate( new Operation(Operator.ADD, list(withNumber(52d), withImaginary(new Imaginary(1d, -1d)), withNumber(15d)))); assertThat(debugString(result), is(equalTo( "{\n" + " imaginary = {\n" + " v = 68\n" + " i = -1\n" + " }\n" + "}"))); }
@Override public BitbucketUser getCurrentUser() throws IOException { if (authentication == null) { return null; } synchronized (this) { if (currentUser == null) { URI endpoint = getEndpoint(USER_ENDPOINT_PATH); HttpRequest request = requestFactory.buildGetRequest( new GenericUrl(endpoint.toString())); request.setInterceptor(authentication); currentUser = getUser(request.execute()); } } return currentUser; }
/** * Returns a authorization code flow for OAuth requests. * @param forTokenRequest <code>true</code> for token requests, or * <code>false</code> for authorization requests * @return {@link AuthorizationCodeFlow} object * @throws NullPointerException if this object has no client credentials */ protected AuthorizationCodeFlow getAuthorizationCodeFlow( boolean forTokenRequest) { if (!isConfiguredForOAuth()) { throw new NullPointerException("No OAuth client credentials"); } HttpExecuteInterceptor clientAuthenticator; if (forTokenRequest) { clientAuthenticator = getBasicAuthentication(); } else { clientAuthenticator = getClientParameters(); } return new AuthorizationCodeFlow( BearerToken.authorizationHeaderAccessMethod(), getHttpTransport(), JacksonFactory.getDefaultInstance(), new GenericUrl(TOKEN_ENDPOINT_URI), clientAuthenticator, getClientId(), AUTHORIZATION_ENDPOINT_URI); }
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; }
/** * @param method method of presenting the access token to the resource * server (for example * {@link BearerToken#authorizationHeaderAccessMethod}) * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerUrl token server URL * @param clientAuthentication client authentication or {@code null} for * none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)} * ) * @param clientId client identifier * @param authorizationServerEncodedUrl authorization server encoded URL */ public Builder(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { super(method, transport, jsonFactory, tokenServerUrl, clientAuthentication, clientId, authorizationServerEncodedUrl); }