Search in sources :

Example 1 with Retrofit

use of retrofit.Retrofit in project nmid-headline by miao1007.

the class RetrofitUtils method getCachedAdapter.

public static Retrofit getCachedAdapter(String endpoint) {
    Cache cache = null;
    OkHttpClient okHttpClient = null;
    Retrofit adapter;
    try {
        File cacheDir = new File(GlobalContext.getInstance().getCacheDir().getPath(), "pictures.json");
        cache = new Cache(cacheDir, 10 * 1024 * 1024);
        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
    } catch (Exception e) {
        e.printStackTrace();
    }
    adapter = new Retrofit.Builder().baseUrl(endpoint).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
    return adapter;
}
Also used : Retrofit(retrofit.Retrofit) OkHttpClient(com.squareup.okhttp.OkHttpClient) File(java.io.File) Cache(com.squareup.okhttp.Cache)

Example 2 with Retrofit

use of retrofit.Retrofit in project microservices by pwillhan.

the class ServiceClient method createClient.

static ServiceClient createClient(String baseUri) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUri).addConverterFactory(JacksonConverterFactory.create()).build();
    ServiceClient service = retrofit.create(ServiceClient.class);
    return service;
}
Also used : Retrofit(retrofit.Retrofit)

Example 3 with Retrofit

use of retrofit.Retrofit in project xDrip by NightscoutFoundation.

the class FollowerListAdapter method getView.

@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_follower, null);
    }
    TextView followerName = (TextView) view.findViewById(R.id.follwerName);
    Button deleteButton = (Button) view.findViewById(R.id.deleteFollower);
    final ExistingFollower follower = list.get(position);
    followerName.setText(follower.ContactName);
    deleteButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() {

                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                        Toast.makeText(context, "Follower deleted succesfully", Toast.LENGTH_LONG).show();
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                }
            };
            shareRest.deleteContact(follower.ContactId, deleteFollowerListener);
        }
    });
    return view;
}
Also used : TextView(android.widget.TextView) View(android.view.View) ResponseBody(com.squareup.okhttp.ResponseBody) ExistingFollower(com.eveningoutpost.dexdrip.ShareModels.Models.ExistingFollower) Retrofit(retrofit.Retrofit) Callback(retrofit.Callback) Button(android.widget.Button) LayoutInflater(android.view.LayoutInflater) TextView(android.widget.TextView)

Example 4 with Retrofit

use of retrofit.Retrofit in project xDrip-plus by jamorham.

the class FollowerListAdapter method getView.

@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_follower, null);
    }
    TextView followerName = (TextView) view.findViewById(R.id.follwerName);
    Button deleteButton = (Button) view.findViewById(R.id.deleteFollower);
    final ExistingFollower follower = list.get(position);
    followerName.setText(follower.ContactName);
    deleteButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() {

                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                        Toast.makeText(context, "Follower deleted succesfully", Toast.LENGTH_LONG).show();
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                }
            };
            shareRest.deleteContact(follower.ContactId, deleteFollowerListener);
        }
    });
    return view;
}
Also used : TextView(android.widget.TextView) View(android.view.View) ResponseBody(com.squareup.okhttp.ResponseBody) ExistingFollower(com.eveningoutpost.dexdrip.ShareModels.Models.ExistingFollower) Retrofit(retrofit.Retrofit) Callback(retrofit.Callback) Button(android.widget.Button) LayoutInflater(android.view.LayoutInflater) TextView(android.widget.TextView)

Example 5 with Retrofit

use of retrofit.Retrofit in project xDrip-plus by jamorham.

the class NightscoutUploader method doRESTtreatmentDownload.

private synchronized boolean doRESTtreatmentDownload(SharedPreferences prefs) {
    final String baseURLSettings = prefs.getString("cloud_storage_api_base", "");
    final ArrayList<String> baseURIs = new ArrayList<>();
    boolean new_data = false;
    Log.d(TAG, "doRESTtreatmentDownload() starting run");
    try {
        for (String baseURLSetting : baseURLSettings.split(" ")) {
            String baseURL = baseURLSetting.trim();
            if (baseURL.isEmpty())
                continue;
            baseURIs.add(baseURL + (baseURL.endsWith("/") ? "" : "/"));
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to process API Base URL: " + e);
        return false;
    }
    // process a list of base uris
    for (String baseURI : baseURIs) {
        try {
            int apiVersion = 0;
            URI uri = new URI(baseURI);
            if ((uri.getHost().startsWith("192.168.")) && prefs.getBoolean("skip_lan_uploads_when_no_lan", true) && (!JoH.isLANConnected())) {
                Log.d(TAG, "Skipping Nighscout download from: " + uri.getHost() + " due to no LAN connection");
                continue;
            }
            if (uri.getPath().endsWith("/v1/"))
                apiVersion = 1;
            String baseURL;
            String secret = uri.getUserInfo();
            if ((secret == null || secret.isEmpty()) && apiVersion == 0) {
                baseURL = baseURI;
            } else if ((secret == null || secret.isEmpty())) {
                throw new Exception("Starting with API v1, a pass phase is required");
            } else if (apiVersion > 0) {
                baseURL = baseURI.replaceFirst("//[^@]+@", "//");
            } else {
                throw new Exception("Unexpected baseURI: " + baseURI);
            }
            final Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL).client(client).build();
            final NightscoutService nightscoutService = retrofit.create(NightscoutService.class);
            final String checkurl = retrofit.baseUrl().url().toString();
            if (!isNightscoutCompatible(checkurl)) {
                Log.e(TAG, "Nightscout version: " + getNightscoutVersion(checkurl) + " on " + checkurl + " is not compatible with the Rest-API download feature!");
                continue;
            }
            if (apiVersion == 1) {
                final String hashedSecret = Hashing.sha1().hashBytes(secret.getBytes(Charsets.UTF_8)).toString();
                final Response<ResponseBody> r;
                if (hashedSecret != null) {
                    // update status if needed
                    doStatusUpdate(nightscoutService, retrofit.baseUrl().url().toString(), hashedSecret);
                    // per uri marker
                    final String LAST_MODIFIED_KEY = LAST_SUCCESS_TREATMENT_DOWNLOAD + CipherUtils.getMD5(uri.toString());
                    String last_modified_string = PersistentStore.getString(LAST_MODIFIED_KEY);
                    if (last_modified_string.equals(""))
                        last_modified_string = JoH.getRFC822String(0);
                    final long request_start = JoH.tsl();
                    r = nightscoutService.downloadTreatments(hashedSecret, last_modified_string).execute();
                    if ((r != null) && (r.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)) {
                        Log.d(TAG, "Treatments on " + uri.getHost() + ":" + uri.getPort() + " not modified since: " + last_modified_string);
                        // skip further processing of this url
                        continue;
                    }
                    if ((r != null) && (r.isSuccess())) {
                        last_modified_string = r.raw().header("Last-Modified", JoH.getRFC822String(request_start));
                        final String this_etag = r.raw().header("Etag", "");
                        if (this_etag.length() > 0) {
                            // older versions of nightscout don't support if-modified-since so check the etag for duplication
                            if (this_etag.equals(PersistentStore.getString(ETAG + LAST_MODIFIED_KEY))) {
                                Log.d(TAG, "Skipping Treatments on " + uri.getHost() + ":" + uri.getPort() + " due to etag duplicate: " + this_etag);
                                continue;
                            }
                            PersistentStore.setString(ETAG + LAST_MODIFIED_KEY, this_etag);
                        }
                        final String response = r.body().string();
                        if (d)
                            Log.d(TAG, "Response: " + response);
                        final JSONArray jsonArray = new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            final JSONObject tr = (JSONObject) jsonArray.get(i);
                            final String etype = tr.has("eventType") ? tr.getString("eventType") : "<null>";
                            // TODO if we are using upsert then we should favour _id over uuid!?
                            final String uuid = (tr.has("uuid") && (tr.getString("uuid") != null)) ? tr.getString("uuid") : UUID.nameUUIDFromBytes(tr.getString("_id").getBytes("UTF-8")).toString();
                            final String nightscout_id = (tr.getString("_id") == null) ? uuid : tr.getString("_id");
                            if (bad_uuids.contains(nightscout_id)) {
                                Log.d(TAG, "Skipping previously baulked uuid: " + nightscout_id);
                                continue;
                            }
                            if (d)
                                Log.d(TAG, "event: " + etype + "_id: " + nightscout_id + " uuid:" + uuid);
                            boolean from_xdrip = false;
                            try {
                                if (tr.getString("enteredBy").startsWith(Treatments.XDRIP_TAG)) {
                                    from_xdrip = true;
                                    if (d)
                                        Log.d(TAG, "This record came from xDrip");
                                }
                            } catch (JSONException e) {
                            // 
                            }
                            // extract blood test data if present
                            try {
                                if (!from_xdrip) {
                                    if (tr.getString("glucoseType").equals("Finger")) {
                                        if (bad_bloodtest_uuids.contains(nightscout_id)) {
                                            Log.d(TAG, "Skipping baulked bloodtest nightscout id: " + nightscout_id);
                                            continue;
                                        }
                                        final BloodTest existing = BloodTest.byUUID(uuid);
                                        if (existing == null) {
                                            final long timestamp = DateUtil.tolerantFromISODateString(tr.getString("created_at")).getTime();
                                            double mgdl = JoH.tolerantParseDouble(tr.getString("glucose"));
                                            if (tr.getString("units").equals("mmol"))
                                                mgdl = mgdl * Constants.MMOLL_TO_MGDL;
                                            final BloodTest bt = BloodTest.create(timestamp, mgdl, tr.getString("enteredBy") + " " + VIA_NIGHTSCOUT_TAG);
                                            if (bt != null) {
                                                // override random uuid with nightscout one
                                                bt.uuid = uuid;
                                                bt.saveit();
                                                new_data = true;
                                                Log.ueh(TAG, "Received new Bloodtest data from Nightscout: " + BgGraphBuilder.unitized_string_with_units_static(mgdl) + " @ " + JoH.dateTimeText(timestamp));
                                            } else {
                                                Log.d(TAG, "Error creating bloodtest record: " + mgdl + " mgdl " + tr.toString());
                                                bad_bloodtest_uuids.add(nightscout_id);
                                            }
                                        } else {
                                            if (d)
                                                Log.d(TAG, "Already a bloodtest with uuid: " + uuid);
                                        }
                                    } else {
                                        if (JoH.quietratelimit("blood-test-type-finger", 2)) {
                                            Log.e(TAG, "Cannot use bloodtest which is not type Finger: " + tr.getString("glucoseType"));
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            // extract treatment data if present
                            double carbs = 0;
                            double insulin = 0;
                            String notes = null;
                            try {
                                carbs = tr.getDouble("carbs");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            try {
                                insulin = tr.getDouble("insulin");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            try {
                                notes = tr.getString("notes");
                            } catch (JSONException e) {
                            // Log.d(TAG, "json processing: " + e);
                            }
                            if ((notes != null) && ((notes.equals("AndroidAPS started") || notes.equals("null") || (notes.equals("Bolus Std")))))
                                notes = null;
                            if ((carbs > 0) || (insulin > 0) || (notes != null)) {
                                final long timestamp = DateUtil.tolerantFromISODateString(tr.getString("created_at")).getTime();
                                if (timestamp > 0) {
                                    if (d)
                                        Log.d(TAG, "Treatment: Carbs: " + carbs + " Insulin: " + insulin + " timestamp: " + timestamp);
                                    Treatments existing = Treatments.byuuid(nightscout_id);
                                    if (existing == null)
                                        existing = Treatments.byuuid(uuid);
                                    if ((existing == null) && (!from_xdrip)) {
                                        // check for close timestamp duplicates perhaps
                                        existing = Treatments.byTimestamp(timestamp, 60000);
                                        if (!((existing != null) && (JoH.roundDouble(existing.insulin, 2) == JoH.roundDouble(insulin, 2)) && (JoH.roundDouble(existing.carbs, 2) == JoH.roundDouble(carbs, 2)) && ((existing.notes == null && notes == null) || ((existing.notes != null) && existing.notes.equals(notes != null ? notes : ""))))) {
                                            Log.ueh(TAG, "New Treatment from Nightscout: Carbs: " + carbs + " Insulin: " + insulin + " timestamp: " + JoH.dateTimeText(timestamp) + ((notes != null) ? " Note: " + notes : ""));
                                            final Treatments t;
                                            if ((carbs > 0) || (insulin > 0)) {
                                                t = Treatments.create(carbs, insulin, timestamp, nightscout_id);
                                                if (notes != null)
                                                    t.notes = notes;
                                            } else {
                                                t = Treatments.create_note(notes, timestamp, -1, nightscout_id);
                                                if (t == null) {
                                                    Log.d(TAG, "Create note baulked and returned null, so skipping");
                                                    bad_uuids.add(nightscout_id);
                                                    continue;
                                                }
                                            }
                                            // t.uuid = nightscout_id; // replace with nightscout uuid
                                            try {
                                                t.enteredBy = tr.getString("enteredBy") + " " + VIA_NIGHTSCOUT_TAG;
                                            } catch (JSONException e) {
                                                t.enteredBy = VIA_NIGHTSCOUT_TAG;
                                            }
                                            t.save();
                                            // pushTreatmentSync(t, false);
                                            if (Home.get_show_wear_treatments())
                                                pushTreatmentSyncToWatch(t, true);
                                            new_data = true;
                                        } else {
                                            Log.e(TAG, "Skipping treatment as it appears identical to one we already have: " + JoH.dateTimeText(timestamp) + " " + insulin + " " + carbs + " " + notes);
                                        }
                                    } else {
                                        if (existing != null) {
                                            if (d)
                                                Log.d(TAG, "Treatment with uuid: " + uuid + " / " + nightscout_id + " already exists");
                                            if (notes == null)
                                                notes = "";
                                            if (existing.notes == null)
                                                existing.notes = "";
                                            if ((existing.carbs != carbs) || (existing.insulin != insulin) || ((existing.timestamp / Constants.SECOND_IN_MS) != (timestamp / Constants.SECOND_IN_MS)) || (!existing.notes.contains(notes))) {
                                                Log.ueh(TAG, "Treatment changes from Nightscout: " + carbs + " Insulin: " + insulin + " timestamp: " + JoH.dateTimeText(timestamp) + " " + notes + " " + " vs " + existing.carbs + " " + existing.insulin + " " + JoH.dateTimeText(existing.timestamp) + " " + existing.notes);
                                                existing.carbs = carbs;
                                                existing.insulin = insulin;
                                                existing.timestamp = timestamp;
                                                existing.created_at = DateUtil.toISOString(timestamp);
                                                if (existing.notes.length() > 0) {
                                                    existing.notes += " \u2192 " + notes;
                                                } else {
                                                    existing.notes = notes;
                                                }
                                                existing.save();
                                                if (Home.get_show_wear_treatments())
                                                    pushTreatmentSyncToWatch(existing, false);
                                                new_data = true;
                                            }
                                        } else {
                                            Log.d(TAG, "Skipping record creation as original source is xDrip");
                                        }
                                    }
                                }
                            }
                        }
                        PersistentStore.setString(LAST_MODIFIED_KEY, last_modified_string);
                        checkGzipSupport(r);
                    } else {
                        Log.d(TAG, "Failed to get treatments from: " + baseURI);
                    }
                } else {
                    Log.d(TAG, "Old api version not supported");
                }
            }
        } catch (Exception e) {
            String msg = "Unable to do REST API Download " + e + " " + e.getMessage() + " url: " + baseURI;
            handleRestFailure(msg);
        }
    }
    Log.d(TAG, "doRESTtreatmentDownload() finishing run");
    return new_data;
}
Also used : BloodTest(com.eveningoutpost.dexdrip.Models.BloodTest) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) URI(java.net.URI) MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) ResponseBody(com.squareup.okhttp.ResponseBody) Retrofit(retrofit.Retrofit) JSONObject(org.json.JSONObject) Treatments(com.eveningoutpost.dexdrip.Models.Treatments)

Aggregations

Retrofit (retrofit.Retrofit)10 View (android.view.View)4 Button (android.widget.Button)4 MongoClientURI (com.mongodb.MongoClientURI)4 ResponseBody (com.squareup.okhttp.ResponseBody)4 IOException (java.io.IOException)4 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 ArrayList (java.util.ArrayList)4 JSONException (org.json.JSONException)4 Callback (retrofit.Callback)4 Dialog (android.app.Dialog)2 LayoutInflater (android.view.LayoutInflater)2 WindowManager (android.view.WindowManager)2 EditText (android.widget.EditText)2 ListView (android.widget.ListView)2 TextView (android.widget.TextView)2 BloodTest (com.eveningoutpost.dexdrip.Models.BloodTest)2 Treatments (com.eveningoutpost.dexdrip.Models.Treatments)2 ExistingFollower (com.eveningoutpost.dexdrip.ShareModels.Models.ExistingFollower)2