/** * Effettua una web request sincrona tramite Volley API, restituendo in risposta * l'oggetto JSON scaricato. */ public static JSONObject volleySyncRequest(Context c, String url) { // configurazione della webRequest RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest(url, null, future, future); RequestQueue requestQueue = Volley.newRequestQueue(c); requestQueue.add(request); // esecuzione sincrona della webRequest try { // limita la richiesta bloccante a un massimo di 10 secondi, quindi restituisci // la risposta. return future.get(10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException | ExecutionException e) { e.printStackTrace(); } return null; }
/** * Effettua una web request sincrona tramite Volley API, restituendo in risposta * l'oggetto JSON scaricato. */ static JSONObject volleySyncRequest(Context c, String url) { // configurazione della webRequest RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest(url, null, future, future); RequestQueue requestQueue = Volley.newRequestQueue(c); requestQueue.add(request); // esecuzione sincrona della webRequest try { // limita la richiesta bloccante a un massimo di 10 secondi, quindi restituisci // la risposta. return future.get(10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException | ExecutionException e) { e.printStackTrace(); } return null; }
static <T> RequestFuture<T> getRequestFuture(Request<T> request, String listernerField) { if (request == null) throw new NullPointerException("request can not be null"); RequestFuture<T> future = RequestFuture.newFuture(); String listenerFieldName = TextUtils.isEmpty(listernerField)? DEFAULT_LISTENER_FIELD: listernerField; String errorListenerFieldName = DEFAULT_ERROR_LISTENER_FIELD; try { Hack.HackedClass hackedClass = Hack.into(request.getClass()); hackedClass.field(listenerFieldName).set(request, future); hackedClass.field(errorListenerFieldName).set(request, future); } catch (Hack.HackDeclaration.HackAssertionException e) { throw new IllegalStateException("the field name of your class is not correct: " + e.getHackedFieldName()); } sRequestQueue.add(request); return future; }
protected <T> T invokeSignedSyncRequest(int method, String resourcePath, Map<String, String> headers, Map<String, Object> params, Object entity, Class<T> returnType) { RequestFuture<T> future = RequestFuture.newFuture(); ErrorListener error = onError(); boolean refreshJWT = !(method == GET && JWT_PATH.equals(resourcePath)); getRequestQueue().add(signer.invokeSignedRequest(accessKey, key(refreshJWT), method, getEndpoint(), getFullPath(resourcePath), null, params, entity, returnType, future, future)); try { return future.get(requestTimeout, TimeUnit.SECONDS); } catch (Exception e) { error.onErrorResponse(new VolleyError(e)); } return null; }
public static JSONObject requestJsonObject(Context context, int method, Map<String, String> headers, String url, JSONObject params, Response.ErrorListener errorListener) { RequestFuture<JSONObject> future = RequestFuture.newFuture(); final Map<String, String> reqHeaders = headers; JsonObjectRequest request = new JsonObjectRequest(method, url, params, future, future) { public Map<String, String> getHeaders() { return reqHeaders != null ? reqHeaders : new HashMap<String, String>(); } }; RequestManager.getInstance(context).addToRequestQueue(request); try { return future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS); } catch (Exception e) { errorListener.onErrorResponse(new VolleyError(e)); } return null; }
public static JSONArray requestJsonArray(Context context, int method, Map<String, String> headers, String url, JSONObject params, Response.ErrorListener errorListener) { RequestFuture<JSONArray> future = RequestFuture.newFuture(); final Map<String, String> reqHeaders = headers; JsonArrayRequest request = new JsonArrayRequest(method, url, params, future, future) { public Map<String, String> getHeaders() { return reqHeaders != null ? reqHeaders : new HashMap<String, String>(); } }; RequestManager.getInstance(context).addToRequestQueue(request); try { return future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS); } catch (Exception e) { errorListener.onErrorResponse(new VolleyError(e)); } return null; }
public final ContentFilters.ContentFilterSettingsResponse fetchOverNetwork$6f1d50b6() { Utils.ensureNotOnMainThread(); RequestFuture localRequestFuture = RequestFuture.newFuture(); fetchSettingsOverNetwork(localRequestFuture, localRequestFuture, true); try { ContentFilters.ContentFilterSettingsResponse localContentFilterSettingsResponse = (ContentFilters.ContentFilterSettingsResponse)localRequestFuture.get(); onResponse(localContentFilterSettingsResponse); return localContentFilterSettingsResponse; } catch (InterruptedException localInterruptedException) { logException(localInterruptedException); return null; } catch (ExecutionException localExecutionException) { for (;;) { logException(localExecutionException); } } }
private JSONObject fetchJsonObject(String paramString) { try { RequestFuture localRequestFuture = RequestFuture.newFuture(); JsonObjectWithHeadersRequest localJsonObjectWithHeadersRequest = new JsonObjectWithHeadersRequest(paramString, Collections.singletonMap("User-Agent", WalletRequestQueue.USER_AGENT_VALUE), localRequestFuture, localRequestFuture); this.mRequestQueue.add(localJsonObjectWithHeadersRequest); JSONObject localJSONObject = (JSONObject)localRequestFuture.get(5000L, TimeUnit.MILLISECONDS); return localJSONObject; } catch (TimeoutException localTimeoutException) { Log.w("GooglePlacesAddressSour", "TimeoutException while retrieving addresses from GooglePlaces", localTimeoutException); return null; } catch (InterruptedException localInterruptedException) { Log.w("GooglePlacesAddressSour", "InterruptedException while retrieving addresses from GooglePlaces", localInterruptedException); return null; } catch (ExecutionException localExecutionException) { Log.w("GooglePlacesAddressSour", "ExecutionException while retrieving addresses from GooglePlaces", localExecutionException); } return null; }
/** Obtain an OAuth request token. */ @TargetApi(21) public static Token blockingGetRequestToken(Context context, Object tag) throws VolleyError, InterruptedException { Util.assertNotOnMainThread(); RequestFuture<Token> future = RequestFuture.newFuture(); Map<String, String> extraHeaders = new HashMap<>(); extraHeaders.put(KEY_CALLBACK, BuildConfig.CALLBACK_URL); if (Build.VERSION.SDK_INT >= 21) { extraHeaders.put(KEY_LANG_PREF, context.getResources().getConfiguration().locale.toLanguageTag()); } // We use an empty token here because this is the initial request. OAuthTokenRequest request = new OAuthTokenRequest(ENDPOINT_GET_REQUEST_TOKEN, new Token.Builder().build(), extraHeaders, future, future); request.setTag(tag); return Volley.makeBlockingRequest(context, request, future); }
/** * Exchange a request token and an OAuth verifier (attached to the given callback uri) for an * auth token. */ public static Token blockingGetToken(Context context, Object tag, Token requestToken, String callbackUri) throws VolleyError, InterruptedException { Util.assertNotOnMainThread(); RequestFuture<Token> future = RequestFuture.newFuture(); Map<String, String> extraHeaders = new HashMap<>(); Uri uri = Uri.parse(callbackUri); String verifier = uri.getQueryParameter(KEY_VERIFIER); if (TextUtils.isEmpty(verifier)) { throw new AuthFailureError("Provided callbackUri has no verifier: " + callbackUri); } extraHeaders.put(KEY_VERIFIER, verifier); OAuthTokenRequest request = new OAuthTokenRequest( ENDPOINT_GET_TOKEN, requestToken, extraHeaders, future, future); request.setTag(tag); return Volley.makeBlockingRequest(context, request, future); }
/** * @param requestConfig Additional request configuration entity, used to provide some additional parameters * @param lock autogenerated object used to perform synchronized requests */ protected BaseRequest(RequestMethod requestMethod, String requestUrl, RequestConfig requestConfig, RequestFuture<ResponseData> lock) { super(requestMethod.methodCode, requestUrl, lock); this.requestFormat = requestConfig.getRequestFormat(); ResponseFormat responseFormatL = requestConfig.getResponseFormat(); if (responseFormatL == null) { responseFormatL = this.requestFormat.toResponse(); } this.responseFormat = responseFormatL; this.syncLock = lock; this.requestHandler = Handler.getRequestHandlerForFormat(this.requestFormat); this.responseHandler = Handler.getResponseHandlerForFormat(this.responseFormat); this.initRequestHeaders(); this.responseClasSpecifier = requestConfig.getResponseClassSpecifier(); this.errorResponseClasSpecifier = requestConfig.getErrorResponseClassSpecifier(); this.result = new ResponseData(); }
public Story getStory(String storyId) { String STORY_PATH = "/story"; String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId; RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future); request.setRetryPolicy(RetryPolicyFactory.build()); mRequestQueue.add(request); try { JSONObject response = future.get(); return StoryMarshaller.marshall(response); } catch (Exception e) { return null; } }
public List<Story> getStories(Collection collection) { String apiUrl = getUrlForCollection(collection); RequestFuture<JSONArray> future = RequestFuture.newFuture(); JsonArrayRequest request = new JsonArrayRequest(mApiBaseUrl + apiUrl, future, future); request.setRetryPolicy(RetryPolicyFactory.build()); mRequestQueue.add(request); try { JSONArray response = future.get(); return FrontPageMarshaller.marshall(response); } catch (Exception e) { return null; } }
private long postCheckIn(String attendeeId, String eventId, boolean revert, String cookie) { RequestQueue queue = GutenbergApplication.from(getContext()).getRequestQueue(); RequestFuture<JSONObject> future = RequestFuture.newFuture(); queue.add(new CheckInRequest(cookie, eventId, attendeeId, revert, future, future)); try { JSONObject object = future.get(); return object.getLong("checkinTime"); } catch (InterruptedException | ExecutionException | JSONException e) { Throwable cause = e.getCause(); if (cause instanceof ServerError) { ServerError error = (ServerError) cause; Log.e(TAG, "Server error: " + new String(error.networkResponse.data)); } Log.e(TAG, "Cannot sync checkin.", e); } return -1; }
private Object addToQueueSync(RequestCreator requestCreator) throws Exception { final RequestFuture<Object> future = RequestFuture.newFuture(); Request<Response> request = new VolleyRequest(getMethod(requestCreator.getMethod()), requestCreator.getUrl(), requestCreator, future) { @Override protected void deliverResponse(Response response) { super.deliverResponse(response); future.onResponse(response.getResponseObject()); } }; future.setRequest(request); addToQueue(request); int timeout = 30000; if (requestCreator.getRetryPolicy() != null) { timeout = requestCreator.getRetryPolicy().getCurrentTimeout(); } return future.get(timeout, TimeUnit.MILLISECONDS); }
/** * @param requestConfig Additional request configuration entity, used to provide some additional parameters * @param lock autogenerated object used to perform synchronized requests */ protected BaseRequest(RequestMethod requestMethod, String requestUrl,RequestConfig requestConfig, RequestFuture<ResponseData> lock) { super(requestMethod.methodCode, requestUrl, lock); this.requestFormat = requestConfig.getRequestFormat(); ResponseFormat responseFormatL = requestConfig.getResponseFormat(); if(responseFormatL == null) { responseFormatL = this.requestFormat.toResponse(); } this.responseFormat = responseFormatL; this.syncLock = lock; this.requestHandler = Handler.getRequestHandlerForFormat(this.requestFormat); this.responseHandler = Handler.getResponseHandlerForFormat(this.responseFormat); this.initRequestHeaders(); this.responseClasSpecifier = requestConfig.getResponseClassSpecifier(); this.errorResponseClasSpecifier = requestConfig.getErrorResponseClassSpecifier(); this.result = new ResponseData(); }
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { RequestFuture<String> future = RequestFuture.newFuture(); Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); if(request != null) { mRequestQueue.add(request); return future.get(connectionTimeout, TimeUnit.SECONDS); } else { return "no data"; } }
/** * 同步请求 * * @param method {@link Method#GET} , {@link Method#POST} * @param urlPath url+path * @param params 自定义参数 * @param isNeedCommonParam 是否需要公共参数 * @param type type * @param tag tag , 可用于取消请求 {@link #cancelRequest(String)} * @param priority 优先级 {@link com.android.volley.Request.Priority} * @param timeOutMills timeout , 毫秒 * @param <T> T * * @return BaseResponse<T> * * @throws InterruptedException * @throws ExecutionException * @throws TimeoutException */ @CheckResult @WorkerThread public <T> BaseResponse<T> requestSync(@REQUEST_METHOD int method, @NonNull final String urlPath, @Nullable Map<String, String> params, boolean isNeedCommonParam, @NonNull Type type, String tag, Request.Priority priority, long timeOutMills) throws InterruptedException, ExecutionException, TimeoutException { final String url; if (method == Method.GET) { url = new ApiParams().addCustomParam(params).buildUrl(urlPath, isNeedCommonParam); } else { url = urlPath; params = new ApiParams().addCustomParam(params).buildParam(isNeedCommonParam); mVolleyManager.removeCache(url); // POST 412 ? } RequestFuture<BaseResponse<T>> requestFuture = RequestFuture.newFuture(); GsonRequest<T> gsonRequest = new GsonRequest<>(method, params, url, type, requestFuture, requestFuture); if (priority == null) { priority = Request.Priority.NORMAL; } if (tag != null) { gsonRequest.setTag(tag); } gsonRequest.setPriority(priority); requestFuture.setRequest(mVolleyManager.getRequestQueue().add(gsonRequest)); // can be cancel BaseResponse<T> response = requestFuture.get(timeOutMills, TimeUnit.MILLISECONDS); return response; }
@Test public void getRequestFuture_customRequest() throws Exception { VolleyX.sInited = true; VolleyX.setRequestQueue(mockReqeustQueue); TestRequest2 testRequest = new TestRequest2(Request.Method.GET, "", null); VolleyX.getRequestFuture(testRequest, "mListener1"); assertThat(testRequest.mListener1, is(instanceOf(RequestFuture.class))); assertThat(testRequest.getErrorListener(), is(instanceOf(RequestFuture.class))); assertTrue(testRequest.getErrorListener() == testRequest.mListener1); verify(mockReqeustQueue, times(1)).add(testRequest); }
@Test public void getRequestFuture_Request() throws Exception { VolleyX.sInited = true; VolleyX.setRequestQueue(mockReqeustQueue); TestRequest testRequest = new TestRequest(Request.Method.GET, "", null); VolleyX.getRequestFuture(testRequest, null); assertThat(testRequest.mListener, is(instanceOf(RequestFuture.class))); assertThat(testRequest.getErrorListener(), is(instanceOf(RequestFuture.class))); assertTrue(testRequest.getErrorListener() == testRequest.mListener); verify(mockReqeustQueue, times(1)).add(testRequest); }
/** * execute request synchronous. * @param clazz response data type * @param <DATA> response data type * @return {@link RestVolleyResponse} */ public <DATA> RestVolleyResponse<DATA> syncExecute(Class<DATA> clazz) { bindOkHttpClient(); RequestFuture<RestVolleyResponse<DATA>> future = RequestFuture.newFuture(); mVolleyRequest = new VolleyRequest(mMethod, onBuildUrl(), clazz, future, future); mVolleyRequest.setTag(mTag) .setRetryPolicy(mRetryPolicy) .setSequence(mSequence) .setShouldCache(mShouldCache) .setCacheEntry(mCacheEntry) .setRequestQueue(mRequestEngine.requestQueue) .setRedirectUrl(mRedirectUrl); mVolleyRequest.addMarker(mMarker); future.setRequest(mVolleyRequest); mRequestEngine.requestQueue.add(mVolleyRequest); RestVolleyResponse<DATA> response = new RestVolleyResponse<DATA>(-1, null, null, false, 0, null); try { response = future.get(); } catch (Exception e) { Throwable cause = e.getCause(); if (cause instanceof VolleyError) { response.exception = (Exception) cause; response.message = cause.getMessage(); NetworkResponse networkResponse = ((VolleyError) cause).networkResponse; response.statusCode = networkResponse.statusCode; response.headers = networkResponse != null ? networkResponse.headers : response.headers; response.networkTimeMs = networkResponse != null ? networkResponse.networkTimeMs : response.networkTimeMs; response.notModified = networkResponse != null ? networkResponse.notModified : response.notModified; response.data = (DATA)mVolleyRequest.parseNetworkResponse2RVResponse(networkResponse).data; } } return response; }
/** * 同步请求 * * @param request Request * @param tag tag用于区分是否同一个请求 * @param <T> Request * @return JSONObject */ public <T> JSONObject addSyncRequest(Request<T> request, Object tag) { request.setTag(tag == null ? TAG : tag); RequestFuture<JSONObject> future = RequestFuture.newFuture(); getRequestQueue().add(request); try { return future.get(); } catch (InterruptedException | ExecutionException e) { Log.e(TAG, e.getMessage()); } return null; }
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { RequestFuture<String> future = RequestFuture.newFuture(); Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); if(request != null) { mRequestQueue.add(request); return future.get(connectionTimeout, TimeUnit.SECONDS); } else return "no data"; }
private static Restore.BackupDeviceInfo[] getBackupDevices(DfeApi paramDfeApi) { RequestFuture localRequestFuture = RequestFuture.newFuture(); long l = SystemClock.elapsedRealtime(); paramDfeApi.getBackupDeviceChoices(localRequestFuture, localRequestFuture); Throwable localThrowable; try { Restore.BackupDeviceInfo[] arrayOfBackupDeviceInfo = ((Restore.GetBackupDeviceChoicesResponse)localRequestFuture.get()).backupDeviceInfo; logBackgroundEvent(-1, null, paramDfeApi, l); Object[] arrayOfObject2 = new Object[1]; arrayOfObject2[0] = Integer.valueOf(arrayOfBackupDeviceInfo.length); FinskyLog.d("getBackupDeviceChoices returned with %d devices", arrayOfObject2); return arrayOfBackupDeviceInfo; } catch (InterruptedException localInterruptedException) { Object[] arrayOfObject1 = new Object[1]; arrayOfObject1[0] = localInterruptedException.getMessage(); FinskyLog.wtf("Unable to fetch backup devices, InterruptedException: %s", arrayOfObject1); logBackgroundEvent(1, localInterruptedException, paramDfeApi, l); return null; } catch (ExecutionException localExecutionException) { localThrowable = localExecutionException.getCause(); if (!(localThrowable instanceof DisplayMessageError)) {} } for (String str = ((DisplayMessageError)localThrowable).mDisplayErrorHtml;; str = null) { FinskyLog.e("Unable to fetch backup devices: %s (%s)", new Object[] { localThrowable, str }); logBackgroundEvent(1, localThrowable, paramDfeApi, l); return null; } }
public final List<PlaceAutocompletePrediction> getSuggestions(CharSequence paramCharSequence) { if ((paramCharSequence != null) && (this.mCountry != null)) { RequestFuture localRequestFuture = RequestFuture.newFuture(); PlacesService localPlacesService = this.mPlacesService; String str1 = paramCharSequence.toString(); Location localLocation = this.mLocation; String str2 = this.mCountry; StringBuilder localStringBuilder = new StringBuilder("/maps/api/place/autocomplete/json?input="); localStringBuilder.append(Utils.urlEncode(str1.trim())); localStringBuilder.append("&language=").append(localPlacesService.mLanguage); localStringBuilder.append("&types=address"); localStringBuilder.append("&components=country:").append(str2); if (localLocation != null) { localStringBuilder.append("&location=").append(localLocation.getLatitude()).append(',').append(localLocation.getLongitude()); localStringBuilder.append("&radius=").append(G.placesApiBiasRadiusMeters.get()); } PlaceAutocompleteRequest localPlaceAutocompleteRequest = new PlaceAutocompleteRequest(localPlacesService.buildRequestUrl(localStringBuilder), localRequestFuture, localRequestFuture); this.mRequestQueue.add(localPlaceAutocompleteRequest); try { List localList = ((PlaceAutocompleteResponse)localRequestFuture.get()).mPredictions; return localList; } catch (ExecutionException localExecutionException) { return null; } catch (InterruptedException localInterruptedException) { return null; } } return null; }
/** Get all active leagues for the given user. */ public static League[] blockingGetLeagues(Context context, Object tag, Account account) throws VolleyError, InterruptedException { Util.assertNotOnMainThread(); RequestFuture<League[]> future = RequestFuture.newFuture(); YahooApiRequest<League[]> request = new YahooApiRequest<League[]>(context, "users;use_login=1/games;is_available=1/leagues", account, future, future) { @Override protected League[] parseResponse(String response) throws ParseError { return LeagueParser.parseXml(new StringReader(response)); } }; request.setTag(tag); return Volley.makeBlockingRequest(context, request, future); }
/** Get the current matchup for the given user and league. */ public static Matchup blockingGetMatchup(Context context, Object tag, Account account, League league) throws VolleyError, InterruptedException { Util.assertNotOnMainThread(); RequestFuture<Matchup> future = RequestFuture.newFuture(); YahooApiRequest<Matchup> request = new YahooApiRequest<Matchup>(context, "league/" + league.league_key + "/scoreboard", account, future, future) { @Override protected Matchup parseResponse(String response) throws ParseError { return ScoreboardParser.parseXml(new StringReader(response)); } }; request.setTag(tag); return Volley.makeBlockingRequest(context, request, future); }
/** Refresh an expired auth token. */ public static Token blockingRefreshToken(Context context, Object tag, Token token) throws VolleyError, InterruptedException { Util.assertNotOnMainThread(); RequestFuture<Token> future = RequestFuture.newFuture(); Map<String, String> extraHeaders = new HashMap<>(); extraHeaders.put(KEY_SESSION_HANDLE, token.session_handle); OAuthTokenRequest request = new OAuthTokenRequest( ENDPOINT_GET_TOKEN, token, extraHeaders, future, future); request.setTag(tag); return Volley.makeBlockingRequest(context, request, future); }
public static <T> T makeBlockingRequest(Context context, Request<T> request, RequestFuture<T> future) throws VolleyError, InterruptedException { Volley.getInstance(context).getRequestQueue().add(request); try { return future.get(); } catch (ExecutionException e) { throw (VolleyError) e.getCause(); } }
public static <T> Observable<T> newRequest(@NonNull final RequestQueue queue, @NonNull final ListenableRequest<T> request) { return Observable.create(new Observable.OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { final RequestFuture<T> future = RequestFuture.newFuture(); subscriber.add(Subscriptions.from(future)); request.setListener(future); request.setErrorListener(future); future.setRequest(queue.add(request)); try { final T result = future.get(request.getTimeoutMs(), TimeUnit.MILLISECONDS); if (subscriber.isUnsubscribed()) { return; } subscriber.onNext(result); subscriber.onCompleted(); } catch (InterruptedException | TimeoutException | ExecutionException e) { if (subscriber.isUnsubscribed()) { return; } subscriber.onError(e); } } }); }
private static JSONArray getEvents(RequestQueue requestQueue, String cookie) throws ExecutionException, InterruptedException { RequestFuture<JSONArray> future = RequestFuture.newFuture(); requestQueue.add(new GaeJsonArrayRequest( BuildConfig.HOST + "/v1/event/list", cookie, future, future)); try { return future.get(); } catch (ExecutionException e) { if (didServerReturnNull(e)) { return new JSONArray(); } throw e; } }
private static JSONArray getAttendees(RequestQueue requestQueue, String eventId, String cookie) throws ExecutionException, InterruptedException { RequestFuture<JSONArray> future = RequestFuture.newFuture(); requestQueue.add(new GaeJsonArrayRequest( BuildConfig.HOST + "/v1/event/" + eventId + "/attendees", cookie, future, future)); try { return future.get(); } catch (ExecutionException e) { if (didServerReturnNull(e)) { return new JSONArray(); } throw e; } }
@Override public void setUp() { retryPolicy = new DefaultRetryPolicy(); requestFuture = RequestFuture.newFuture(); loginRequest = new TokenRequest("foobar", "1234", "https://user.gini.net/oauth/token?grant_type=client_credentials", null, requestFuture, requestFuture, retryPolicy); mockNetwork = new MockNetwork(); requestQueue = new RequestQueue(new NoCache(), mockNetwork); requestQueue.start(); }
private static String requestArticle( final String articleTitle, final Context context ) { String wikiArticle; Log.d( TAG, "Requesting Wiki Article..." ); final String baseUrl = "http://en.wikipedia.org"; final String articleQuery = "/w/api.php?action=parse&format=json&prop=wikitext§ion=0&contentformat=text%2Fx-wiki&contentmodel=wikitext&redirects=&page="; final String url = baseUrl + articleQuery + articleTitle; RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest( url, null, future, future ); request.setTag( context ); TMinusApplication.getRequestQueue().add( request ); try { JSONObject response = future.get(); wikiArticle = WikiArticleHandler.processWikiArticle( response ); } catch( InterruptedException | ExecutionException e ) { wikiArticle = null; } return wikiArticle; }
private static String requestImage( final String articleTitle, final Context context ) { String thumbnailUrl; Log.d( TAG, "Requesting Wiki Image..." ); // This gives the "page image" // Action: query // prop=pageimages final String baseUrl = "http://en.wikipedia.org"; final String imageQuery = "/w/api.php?action=query&prop=pageimages&format=json&piprop=thumbnail%7Cname&pithumbsize=512&pilimit=1&indexpageids=&redirects=&titles="; final String url = baseUrl + imageQuery + articleTitle; RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest( url, null, future, future ); request.setTag( context ); TMinusApplication.getRequestQueue().add( request ); try { JSONObject response = future.get(); thumbnailUrl = WikiImageHandler.processImage( response ); } catch( InterruptedException | ExecutionException e ) { thumbnailUrl = null; } return thumbnailUrl; }
void setFutureRequest(RequestFuture<HttpResponse.Builder> futureRequest) { this.futureRequest = futureRequest; }
private void initializeRequestHandler() { mCallbacks = RequestFuture.newFuture(); }
public RequestFuture getRequestFuture() { return mCallbacks; }
static <T> T generateData(Request<T> request, String listernerField) throws InterruptedException, ExecutionException { if (request == null) throw new NullPointerException("request can not be null"); RequestFuture<T> future = getRequestFuture(request, listernerField); return future.get(); }