retrofit.mime.TypedByteArray Java Examples

The following examples show how to use retrofit.mime.TypedByteArray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FetchSearchPage.java    From Mover with Apache License 2.0 6 votes vote down vote up
@Override
public Mover doBackgroundJob() {
    /**
     * NOTES
     *
     * if category page equals empty quotes("") it's means
     * that selected page is category_home page :)
     *
     */

    Response response = mService.search(mQuery, mPageNumber);

    if(response.getStatus() >= 200 && response.getStatus() <= 300) {

        byte[] data = ((TypedByteArray) response.getBody()).getBytes();
        String htmlSource = new String(data);

        return new Mover.SearchPage(mQuery, mPageNumber).from(htmlSource);
    }

    throw RetrofitError.httpError(response.getUrl(), response, null, Response.class);
}
 
Example #2
Source File: UseRxJavaRightWayActivity.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_use_rxjava_right_way);
    tvContent = findViewById(R.id.tv_content);
    Subscription subscriptionForUser = userApi.getUserInfo()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Response>() {
                @Override
                public void call(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    tvContent.setText("receiver data : " + content);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    tvContent.setText("receiver error : " + throwable.getMessage());
                }
            });

    compositeSubscription.add(subscriptionForUser);

}
 
Example #3
Source File: TryWhenFragment.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
        case R.id.btn_operator:
            tvLogs.setText("");
            userApi.getUserInfoNoToken()
                    .retryWhen(new RetryWithDelay(3, 3000))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Action1<Response>() {
                        @Override
                        public void call(Response response) {
                            String content = new String(((TypedByteArray) response.getBody()).getBytes());
                            printLog(tvLogs, "", content);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    });
    }
}
 
Example #4
Source File: GoogleCloudBuildArtifactExtractor.java    From echo with Apache License 2.0 6 votes vote down vote up
@Override
public List<Artifact> getArtifacts(String messagePayload) {
  TypedInput build =
      new TypedByteArray("application/json", messagePayload.getBytes(StandardCharsets.UTF_8));
  try {
    return retrySupport.retry(
        () ->
            AuthenticatedRequest.allowAnonymous(
                () -> igorService.extractGoogleCloudBuildArtifacts(account, build)),
        5,
        2000,
        false);
  } catch (Exception e) {
    log.error("Failed to fetch artifacts for build: {}", e);
    return Collections.emptyList();
  }
}
 
Example #5
Source File: RxJavaLeakFragment.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
public void doRetrofit() {
    if (otherApi == null) {
        otherApi = ApiServiceFactory.createService(OtherApi.class);
    }
    retrofitSubscription = otherApi.testTimeout("10000")
            .onTerminateDetach()
            .subscribe(new Action1<Response>() {
                @Override
                public void call(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    Log.d("RxJavaLeakFragment", RxJavaLeakFragment.this + ":" + content);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    throwable.printStackTrace();
                }
            });
}
 
Example #6
Source File: UseRxJavaRightWayActivity.java    From AndroidRxJavaSample with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_use_rxjava_right_way);
    tvContent = (TextView) findViewById(R.id.tv_content);
    subscriptionForUser = userApi.getUserInfo()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Response>() {
                @Override
                public void call(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    tvContent.setText("receiver data : " + content);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    tvContent.setText("receiver error : " + throwable.getMessage());
                }
            });

    compositeSubscription.add(subscriptionForUser);

}
 
Example #7
Source File: TryWhenFragment.java    From AndroidRxJavaSample with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
        case R.id.btn_operator:
            tvLogs.setText("");
            userApi.getUserInfoNoToken()
                    .retryWhen(new RetryWithDelay(3, 3000))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Action1<Response>() {
                        @Override
                        public void call(Response response) {
                            String content = new String(((TypedByteArray) response.getBody()).getBytes());
                            printLog(tvLogs, "", content);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    });
    }
}
 
Example #8
Source File: ParticleDevice.java    From spark-sdk-android with Apache License 2.0 6 votes vote down vote up
@WorkerThread
public float getCurrentDataUsage() throws ParticleCloudException {
    float maxUsage = 0;
    try {
        Response response = mainApi.getCurrentDataUsage(deviceState.lastIccid);
        JSONObject result = new JSONObject(new String(((TypedByteArray) response.getBody()).getBytes()));
        JSONArray usages = result.getJSONArray("usage_by_day");

        for (int i = 0; i < usages.length(); i++) {
            JSONObject usageElement = usages.getJSONObject(i);
            if (usageElement.has("mbs_used_cumulative")) {
                double usage = usageElement.getDouble("mbs_used_cumulative");
                if (usage > maxUsage) {
                    maxUsage = (float) usage;
                }
            }
        }
    } catch (JSONException | RetrofitError e) {
        throw new ParticleCloudException(e);
    }
    return maxUsage;
}
 
Example #9
Source File: ShareRest.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
private boolean loginAndGetData() {
    dexcomShareAuthorizeInterface().getSessionId(new ShareAuthenticationBody(password, login), new Callback() {
        @Override
        public void success(Object o, Response response) {
            Log.d("ShareRest", "Success!! got a response on auth.");
            String returnedSessionId = new String(((TypedByteArray) response.getBody()).getBytes()).replace("\"", "");

            getBg(returnedSessionId);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Log.e("RETROFIT ERROR: ", ""+retrofitError.toString());
        }
    });
    return true;
}
 
Example #10
Source File: ParticleCloud.java    From spark-sdk-android with Apache License 2.0 6 votes vote down vote up
/**
 * Sign up with new account credentials to Particle cloud
 *
 * @param signUpInfo Required sign up information, must contain a valid email address and password
 */
@WorkerThread
public void signUpWithUser(SignUpInfo signUpInfo) throws ParticleCloudException {
    try {
        Response response = identityApi.signUp(signUpInfo);
        String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
        JSONObject obj = new JSONObject(bodyString);

        //workaround for sign up bug - invalid credentials bug
        if (obj.has("ok") && !obj.getBoolean("ok")) {
            JSONArray arrJson = obj.getJSONArray("errors");
            String[] arr = new String[arrJson.length()];

            for (int i = 0; i < arrJson.length(); i++) {
                arr[i] = arrJson.getString(i);
            }
            if (arr.length > 0) {
                throw new ParticleCloudException(new Exception(arr[0]));
            }
        }
    } catch (RetrofitError error) {
        throw new ParticleCloudException(error);
    } catch (JSONException ignore) {
        //ignore - who cares if we're not getting error response
    }
}
 
Example #11
Source File: GoogleCloudBuildNotificationAgent.java    From echo with Apache License 2.0 6 votes vote down vote up
@Override
public void processEvent(Event event) {
  if (event.getDetails() != null && event.getDetails().getType().equals("googleCloudBuild")) {
    MessageDescription messageDescription =
        (MessageDescription) event.getContent().get("messageDescription");
    retrySupport.retry(
        () ->
            AuthenticatedRequest.allowAnonymous(
                () ->
                    igorService.updateBuildStatus(
                        messageDescription.getSubscriptionName(),
                        messageDescription.getMessageAttributes().get("buildId"),
                        messageDescription.getMessageAttributes().get("status"),
                        new TypedByteArray(
                            "application/json",
                            messageDescription
                                .getMessagePayload()
                                .getBytes(StandardCharsets.UTF_8)))),
        5,
        2000,
        false);
  }
}
 
Example #12
Source File: ShareRest.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
private boolean loginAndGetData() {
    dexcomShareAuthorizeInterface().getSessionId(new ShareAuthenticationBody(password, login), new Callback() {
        @Override
        public void success(Object o, Response response) {
            Log.d("ShareRest", "Success!! got a response on auth.");
            String returnedSessionId = new String(((TypedByteArray) response.getBody()).getBytes()).replace("\"", "");

            getBg(returnedSessionId);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Log.e("RETROFIT ERROR: ", ""+retrofitError.toString());
        }
    });
    return true;
}
 
Example #13
Source File: SignalFxRemoteServiceTest.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@Test
public void test_that_a_signalfx_signal_flow_response_can_be_parsed() throws Exception {
  InputStream response =
      getClass().getClassLoader().getResourceAsStream("signalfx-signalflow-response.text");
  SignalFxConverter converter = new SignalFxConverter();
  TypedInput typedInput = new TypedByteArray("text/plain", ByteStreams.toByteArray(response));
  SignalFlowExecutionResult signalFlowExecutionResult =
      (SignalFlowExecutionResult) converter.fromBody(typedInput, SignalFlowExecutionResult.class);

  assertNotNull(signalFlowExecutionResult);
  assertThat(
      "The signalFlowExecutionResult contains the channel messages",
      signalFlowExecutionResult.getChannelMessages().size(),
      greaterThan(1));
}
 
Example #14
Source File: FetchCategoryPage.java    From Mover with Apache License 2.0 5 votes vote down vote up
@Override
public Mover doBackgroundJob() {
    Response response;

    /**
     * NOTES
     *
     * if category page equals empty quotes("") it's means
     * that selected page is category_home page :)
     *
     */

    if(mCategory.equals("") && mPageNumber < 2){
        response = mService.home();
    }else if(mCategory.equals("") && mPageNumber >= 2){
        response = mService.home(mPageNumber);
    }else{
        response = mService.category(mCategory, mPageNumber);
    }

    if(response.getStatus() >= 200 && response.getStatus() <= 300) {

        byte[] data = ((TypedByteArray) response.getBody()).getBytes();
        String htmlSource = new String(data);

        if(mPageNumber > 1){
            return new Mover.PaginatedPage(mCategory, mPageNumber).from(htmlSource);
        }

        return new Mover.CategoryPage(mCategory).from(htmlSource);
    }

    throw RetrofitError.httpError(response.getUrl(), response, null, Response.class);
}
 
Example #15
Source File: DownloadingFragment.java    From ADP with MIT License 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View rootView = inflater.inflate(R.layout.fragment_loading, container, false);
    ButterKnife.inject(this, rootView);

    String id = getArguments().getString(ARG_FILE_ID);

    SharedPreferencesUtil preferences = new SharedPreferencesUtil(getActivity());
    API api = API.getInstance(preferences.getUrl(), preferences.getToken());

    bindFragment(DownloadingFragment.this, api.getAPK(id))
            .map(response -> ((TypedByteArray) response.getBody()).getBytes())
            .subscribe(bytes -> {
                try {
                    APKUtil.writeFile(bytes);

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new java.io.File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivityForResult(intent, CODE_INSTALLER);
                } catch (IOException e) {
                    finish(e);
                }
            }, this::finish);
    return rootView;
}
 
Example #16
Source File: RetrofitCurlClient.java    From libcurldroid with Artistic License 2.0 5 votes vote down vote up
private Response convertResult(Request request, Result result) throws IOException {
	Map<String, String> headerMap = result.getHeaders();
	TypedInput input = new TypedByteArray(headerMap.get("Content-Type"), result.getDecodedBody());
	List<Header> headers = new ArrayList<Header>(headerMap.size());
	for (Entry<String, String> entry : headerMap.entrySet()) {
		headers.add(new Header(entry.getKey(), entry.getValue()));
	}
	return new Response(request.getUrl(), result.getStatus(), result.getStatusLine(), headers, input);
}
 
Example #17
Source File: MockRestAdapter.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
public MockRestAdapter(final String responseString, final HashMap<String, String> headers) {
    this.exceptionReference = new AtomicReference<>();
    this.requestReference = new AtomicReference<>();
    this.resultReference = new AtomicReference<>();
    this.mockRestAdapter = new UpholdRestAdapter();
    this.restAdapter = new RestAdapter.Builder().setEndpoint(BuildConfig.API_SERVER_URL)
        .setRequestInterceptor(this.mockRestAdapter.getUpholdRequestInterceptor())
        .setClient(new Client() {
            @Override
            public Response execute(Request request) throws IOException {
                requestReference.set(request);

                return new Response("some/url", 200, "reason", new ArrayList<Header>() {{
                    if (headers != null) {
                        for (Map.Entry<String, String> entry : headers.entrySet()) {
                            String key = entry.getKey();
                            String value = entry.getValue();

                            add(new retrofit.client.Header(key, value));
                        }
                    }
                }}, new TypedByteArray("application/json", responseString == null ? new byte[0] : responseString.getBytes()));
            }
    }).build();

    this.mockRestAdapter.setAdapter(this.restAdapter);
}
 
Example #18
Source File: MockClient.java    From Mocktrofit with MIT License 5 votes vote down vote up
private Response serve(String filename) throws IOException {
    MockFile file = server.serve(filename);
    ArrayList<Header> headers = new ArrayList<Header>();
    for (String line : file.headers) {
        String[] header = line.split(":", 2);
        headers.add(new Header(header[0], header[1].trim()));
    }

    return new Response(file.name, file.code, file.reason, headers, 
        new TypedByteArray(file.contentType, file.body.getBytes()));
}
 
Example #19
Source File: HttpWithTokenFragment.java    From AndroidRxJavaSample with Apache License 2.0 5 votes vote down vote up
private void requestUserInfo() {
    appendText(tvLogs, "start to request user info");
    loading = true;
    Observable<Response> observable = userApi.getUserInfo();
    observable.onErrorResumeNext(refreshTokenAndRetry(observable))//also use retryWhen to implement it
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Response>() {
                @Override
                public void onCompleted() {
                    loading = false;
                    appendText(tvLogs, "task completed-----");
                    //hideLoadingDialog();
                }

                @Override
                public void onError(Throwable t) {
                    //hideLoadingDialog();
                    t.printStackTrace();
                    loading = false;

                    appendText(tvLogs, t.getClass().getName() + "\n" + t.getMessage());
                    NetErrorType.ErrorType error = NetErrorType.getErrorType(t);
                    appendText(tvLogs, error.msg);
                }

                public void onNext(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    appendText(tvLogs, "receiver data: " + content);
                }
            });
}
 
Example #20
Source File: HttpWithTokenFragment.java    From AndroidAll with Apache License 2.0 5 votes vote down vote up
private void requestUserInfo() {
    appendText(tvLogs, "start to request user info");
    loading = true;
    Observable<Response> observable = userApi.getUserInfo();
    observable.onErrorResumeNext(refreshTokenAndRetry(observable))//also use retryWhen to implement it
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Response>() {
                @Override
                public void onCompleted() {
                    loading = false;
                    appendText(tvLogs, "task completed-----");
                    //hideLoadingDialog();
                }

                @Override
                public void onError(Throwable t) {
                    //hideLoadingDialog();
                    t.printStackTrace();
                    loading = false;

                    appendText(tvLogs, t.getClass().getName() + "\n" + t.getMessage());
                    NetErrorType.ErrorType error = NetErrorType.getErrorType(t);
                    appendText(tvLogs, error.msg);
                }

                public void onNext(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    appendText(tvLogs, "receiver data: " + content);
                }
            });
}
 
Example #21
Source File: InfluxDbResponseConverterTest.java    From kayenta with Apache License 2.0 5 votes vote down vote up
@Test
public void deserialize() throws Exception {
  TypedInput input = new TypedByteArray(MIME_TYPE, JSON.getBytes());
  List<InfluxDbResult> result =
      (List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List.class);
  assertThat(result, is(results));
}
 
Example #22
Source File: MockApiService.java    From android-test-demo with MIT License 4 votes vote down vote up
private Response getMockResponse(int httpCode, String json) throws IOException {
    return new Response("url", httpCode, "", Collections.EMPTY_LIST,
            new TypedByteArray("application/json", json.getBytes()));
}
 
Example #23
Source File: MockApiClient.java    From uber-java-client with MIT License 4 votes vote down vote up
@Override
public Response execute(Request request) throws IOException {
    URI uri = URI.create(request.getUrl());
    String method = request.getMethod();
    String responseString = "{}";

    if (uri.getPath().equals("/v1/estimates/time") && "GET".equals(method)) {
        /**
         * {@link com.victorsima.uber.UberService#getTimeEstimates(double, double, String, String)}
         **/
        responseString = "{\"times\":[{\"localized_display_name\":\"uberX\",\"estimate\":140,\"display_name\":\"uberX\",\"product_id\":\"b8e5c464-5de2-4539-a35a-986d6e58f186\"},{\"localized_display_name\":\"uberXL\",\"estimate\":571,\"display_name\":\"uberXL\",\"product_id\":\"1e0ce2df-4a1e-4333-86dd-dc0c67aaabe1\"},{\"localized_display_name\":\"UberBLACK\",\"estimate\":224,\"display_name\":\"UberBLACK\",\"product_id\":\"0e9d8dd3-ffec-4c2b-9714-537e6174bb88\"},{\"localized_display_name\":\"UberSUV\",\"estimate\":224,\"display_name\":\"UberSUV\",\"product_id\":\"56487469-0d3d-4f19-b662-234b7576a562\"},{\"localized_display_name\":\"uberT\",\"estimate\":40,\"display_name\":\"uberT\",\"product_id\":\"ebe413ab-cf49-465f-8564-a71119bfa449\"}]}";
    } else if (uri.getPath().equals("/v1/estimates/price") && "GET".equals(method)) {
        /**
         * {@link com.victorsima.uber.UberService#getPriceEstimates(double, double, double, double)}
         */
        responseString = "{\"prices\":[{\"localized_display_name\":\"uberX\",\"duration\":1730,\"low_estimate\":\"31\",\"display_name\":\"uberX\",\"product_id\":\"b8e5c464-5de2-4539-a35a-986d6e58f186\",\"distance\":9.5,\"surge_multiplier\":1.0,\"estimate\":\"$31-42\",\"high_estimate\":\"42\",\"currency_code\":\"USD\"},{\"localized_display_name\":\"uberXL\",\"duration\":1730,\"low_estimate\":\"47\",\"display_name\":\"uberXL\",\"product_id\":\"1e0ce2df-4a1e-4333-86dd-dc0c67aaabe1\",\"distance\":9.5,\"surge_multiplier\":1.0,\"estimate\":\"$47-63\",\"high_estimate\":\"63\",\"currency_code\":\"USD\"},{\"localized_display_name\":\"UberBLACK\",\"duration\":1730,\"low_estimate\":\"55\",\"display_name\":\"UberBLACK\",\"product_id\":\"0e9d8dd3-ffec-4c2b-9714-537e6174bb88\",\"distance\":9.5,\"surge_multiplier\":1.0,\"estimate\":\"$55-72\",\"high_estimate\":\"72\",\"currency_code\":\"USD\"},{\"localized_display_name\":\"UberSUV\",\"duration\":1730,\"low_estimate\":\"73\",\"display_name\":\"UberSUV\",\"product_id\":\"56487469-0d3d-4f19-b662-234b7576a562\",\"distance\":9.5,\"surge_multiplier\":1.0,\"estimate\":\"$73-92\",\"high_estimate\":\"92\",\"currency_code\":\"USD\"},{\"localized_display_name\":\"uberT\",\"duration\":1730,\"low_estimate\":null,\"display_name\":\"uberT\",\"product_id\":\"ebe413ab-cf49-465f-8564-a71119bfa449\",\"distance\":9.5,\"surge_multiplier\":1.0,\"estimate\":\"Metered\",\"high_estimate\":null,\"currency_code\":null}]}";
    } else if (uri.getPath().equals("/v1/products") && "GET".equals(method)) {
        /**
         * {@link com.victorsima.uber.UberService#getProducts(double, double)}
         */
        responseString = "{\"products\":[{\"capacity\":4,\"image\":\"http:\\/\\/d1a3f4spazzrp4.cloudfront.net\\/car-types\\/mono\\/mono-uberx.png\",\"display_name\":\"uberX\",\"product_id\":\"b8e5c464-5de2-4539-a35a-986d6e58f186\",\"description\":\"The Low Cost Uber\"},{\"capacity\":6,\"image\":\"http:\\/\\/d1a3f4spazzrp4.cloudfront.net\\/car-types\\/mono\\/mono-uberxl2.png\",\"display_name\":\"uberXL\",\"product_id\":\"1e0ce2df-4a1e-4333-86dd-dc0c67aaabe1\",\"description\":\"low-cost rides for large groups\"},{\"capacity\":4,\"image\":\"http:\\/\\/d1a3f4spazzrp4.cloudfront.net\\/car-types\\/mono\\/mono-black.png\",\"display_name\":\"UberBLACK\",\"product_id\":\"0e9d8dd3-ffec-4c2b-9714-537e6174bb88\",\"description\":\"The original Uber\"},{\"capacity\":6,\"image\":\"http:\\/\\/d1a3f4spazzrp4.cloudfront.net\\/car-types\\/mono\\/mono-suv.png\",\"display_name\":\"UberSUV\",\"product_id\":\"56487469-0d3d-4f19-b662-234b7576a562\",\"description\":\"Room for everyone\"},{\"capacity\":1,\"image\":\"http:\\/\\/d1a3f4spazzrp4.cloudfront.net\\/car-types\\/mono\\/mono-nytaxi4.png\",\"display_name\":\"uberT\",\"product_id\":\"ebe413ab-cf49-465f-8564-a71119bfa449\",\"description\":\"Taxi and Boro-Taxi without the hassle\"}]}";
    } else if (uri.getPath().equals("/v1/promotions") && "GET".equals(method)) {
        /**
         * {@link com.victorsima.uber.UberService#getPromotions(double, double, double, double)}
         */
        responseString = "{\"display_text\":\"Free ride up to $30\",\"localized_value\":\"$30\",\"type\":\"trip_credit\"}";
    } else if (uri.getPath().equals("/v1/me") && "GET".equals(method)) {
        responseString = "{\n" +
                "  \"first_name\": \"Uber\",\n" +
                "  \"last_name\": \"Developer\",\n" +
                "  \"email\": \"[email protected]\",\n" +
                "  \"picture\": \"https://...\",\n" +
                "  \"promo_code\": \"teypo\",\n" +
                "  \"uuid\": \"91d81273-45c2-4b57-8124-d0165f8240c0\"\n" +
                "}";
    } else if (uri.getPath().equals("/v1/requests") && "POST".equals(method)) {
        responseString = "{\n" +
                "   \"request_id\": \"852b8fdd-4369-4659-9628-e122662ad257\",\n" +
                "   \"status\": \"processing\",\n" +
                "   \"vehicle\": {\n" +
                "      \"make\":\"Bugatti\",\n" +
                "      \"model\":\"Veyron\",\n" +
                "      \"license_plate\":\"I<3Uber\",\n" +
                "      \"picture_url\":\"https:\\/\\/d1w2poirtb3as9.cloudfront.net\\/car.jpeg\"\n" +
                "   }," +
                "   \"driver\": {\n" +
                "      \"phone_number\":\"(555)555-5555\",\n" +
                "      \"rating\":5,\n" +
                "      \"picture_url\":\"https:\\/\\/d1w2poirtb3as9.cloudfront.net\\/img.jpeg\",\n" +
                "      \"name\":\"Bob\"\n" +
                "   }," +
                "   \"location\": {\n" +
                "      \"latitude\":37.776033,\n" +
                "      \"longitude\":-122.418143\n" +
                "   }," +
                "   \"eta\": 5,\n" +
                "   \"surge_multiplier\": 1.0\n" +
                "}";
    }

        return new Response(uri.toString(), 200, "OK", new ArrayList<Header>(), new TypedByteArray("application/json", responseString.getBytes()));
}
 
Example #24
Source File: MockClient.java    From droidcon-android-espresso with Apache License 2.0 4 votes vote down vote up
@Override
public Response execute(Request request) throws IOException {
    return new Response(200, SUCCESS, Collections.EMPTY_LIST, new TypedByteArray(APPLICATION_JSON, MOCK_RESPONSE_JSON.getBytes()));
}
 
Example #25
Source File: MoverAuthenticator.java    From Mover with Apache License 2.0 4 votes vote down vote up
private String asString(Response body){
    return new String(((TypedByteArray) body.getBody()).getBytes());
}
 
Example #26
Source File: RestAdapter.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
/**
 * Log response headers and body. Consumes response body and returns identical replacement.
 */
private Response logAndReplaceResponse(String url, Response response, long elapsedTime) throws IOException {
    log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime));

    if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) {
        for (Header header : response.getHeaders()) {
            log.log(header.getName() + ": " + header.getValue());
        }

        long bodySize = 0;
        TypedInput body = response.getBody();
        if (body != null) {
            bodySize = body.length();

            if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) {
                if (!response.getHeaders().isEmpty()) {
                    log.log("");
                }

                if (!(body instanceof TypedByteArray)) {
                    // Read the entire response body to we can log it and replace the original response
                    response = Utils.readBodyToBytesIfNecessary(response);
                    body = response.getBody();
                }

                byte[] bodyBytes = ((TypedByteArray) body).getBytes();
                bodySize = bodyBytes.length;
                String bodyMime = body.mimeType();
                String bodyCharset = MimeUtil.parseCharset(bodyMime);
                String bodyString = new String(bodyBytes, bodyCharset);
                for (int i = 0, len = bodyString.length(); i < len; i += LOG_CHUNK_SIZE) {
                    int end = Math.min(len, i + LOG_CHUNK_SIZE);
                    log.log(bodyString.substring(i, end));
                }
            }
        }

        log.log(String.format("<--- END HTTP (%s-byte body)", bodySize));
    }

    return response;
}
 
Example #27
Source File: RestAdapter.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
/**
 * Log request headers and body. Consumes request body and returns identical replacement.
 */
private Request logAndReplaceRequest(Request request) throws IOException {
    log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl()));

    if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) {
        for (Header header : request.getHeaders()) {
            log.log(header.getName() + ": " + header.getValue());
        }

        long bodySize = 0;
        TypedOutput body = request.getBody();
        if (body != null) {
            bodySize = body.length();
            String bodyMime = body.mimeType();

            if (bodyMime != null) {
                log.log("Content-Type: " + bodyMime);
            }
            if (bodySize != -1) {
                log.log("Content-Length: " + bodySize);
            }

            if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) {
                if (!request.getHeaders().isEmpty()) {
                    log.log("");
                }
                if (!(body instanceof TypedByteArray)) {
                    // Read the entire response body to we can log it and replace the original response
                    request = Utils.readBodyToBytesIfNecessary(request);
                    body = request.getBody();
                }

                byte[] bodyBytes = ((TypedByteArray) body).getBytes();
                bodySize = bodyBytes.length;
                String bodyCharset = MimeUtil.parseCharset(bodyMime);
                String bodyString = new String(bodyBytes, bodyCharset);
                for (int i = 0, len = bodyString.length(); i < len; i += LOG_CHUNK_SIZE) {
                    int end = Math.min(len, i + LOG_CHUNK_SIZE);
                    log.log(bodyString.substring(i, end));
                }
            }
        }

        log.log(String.format("---> END HTTP (%s-byte body)", bodySize));
    }

    return request;
}
 
Example #28
Source File: MockClientUpholdRetrofitErrorHandlingTest.java    From uphold-sdk-android with MIT License 4 votes vote down vote up
@Override
public Response execute(Request request) throws IOException {
    return new Response(request.getUrl(), httpResponseCode, reason, httpResponseHeaders, new TypedByteArray("application/json", "foobar".getBytes()));
}
 
Example #29
Source File: WooCommerce.java    From Woocommerce-Android-Client with MIT License 4 votes vote down vote up
public Product getProduct(String id,final ObjectCallback fetched) {
        StringBuilder builder = new StringBuilder();
        builder.append(wcBuilder.isHttps() ? "https://" : "http://");
        builder.append(wcBuilder.getBaseUrl() + "/");
        builder.append("wc-api/v3");
        Log.i(TAG,builder.toString());
        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(builder.toString())
                .build();

        ProductsInterface api = adapter.create(ProductsInterface.class);
        LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
        options.put("id","3862");

        api.getProduct("3862", OAuthSigner.getSignature(options,RequestMethod.GET, Endpoints.PRODUCTS_ENDPOINT), new Callback<Response>() {
            @Override
            public void success(Response response1, Response response) {
//                System.out.println(response1.getBody());
//                System.out.println(response.getUrl());
//                System.out.println(response.getStatus());
//                System.out.println(response.getHeaders());
                String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
                try {
                    JSONObject object = new JSONObject(bodyString);
//                    System.out.println("JSON " + object);
                    Product product = new ProductParser(object).singleProductParser();
                    System.out.println(product);
                    fetched.Callback(product, null);
                    return;
                } catch (JSONException e) {
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void failure(RetrofitError error) {
                System.out.println(error.getUrl());
                fetched.Callback(null, error);
                return;
            }
        });

        return null;
    }
 
Example #30
Source File: WooCommerce.java    From Woocommerce-Android-Client with MIT License 4 votes vote down vote up
public List<Product> getAllCategories(final ListCallback fetched) {
        StringBuilder builder = new StringBuilder();
        builder.append(wcBuilder.isHttps() ? "https://" : "http://");
        builder.append(wcBuilder.getBaseUrl() + "/");
        builder.append("wc-api/v3");
        Log.i(TAG,builder.toString());
        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(builder.toString())
                .build();

        ProductsInterface api = adapter.create(ProductsInterface.class);

        api.getCategories(OAuthSigner.getSignature(RequestMethod.GET, Endpoints.CATEGORIES_ENDPOINT), new Callback<Response>() {
            @Override
            public void success(Response response1, Response response) {
//                System.out.println(response1.getBody());
//                System.out.println(response.getUrl());
//                System.out.println(response.getStatus());
//                System.out.println(response.getHeaders());
                String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
                try {
                    JSONObject object = new JSONObject(bodyString);
//                    System.out.println("JSON " + object);
                    ArrayList<Categories> categories = new CategoriesParser(bodyString).categoriesParser();
//                    System.out.println(products);
                    fetched.Callback(categories, null);
                    return;
                } catch (JSONException e) {
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void failure(RetrofitError error) {
                System.out.println(error);
                fetched.Callback(null, error);
                return;
            }
        });

        return null;
    }