Android Open Source - digital-ocean-swimmer Image Service






From Project

Back to project page digital-ocean-swimmer.

License

The source code is released under:

MIT License

If you think the Android project digital-ocean-swimmer listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.yassirh.digitalocean.service;
//from  w w  w  .  ja v  a2  s.c om
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.yassirh.digitalocean.R;
import com.yassirh.digitalocean.data.DatabaseHelper;
import com.yassirh.digitalocean.data.ImageDao;
import com.yassirh.digitalocean.model.Account;
import com.yassirh.digitalocean.model.Image;
import com.yassirh.digitalocean.utils.ApiHelper;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class ImageService {

  private Context context;
  private boolean isRefreshing;
  
  public ImageService(Context context) {
    this.context = context;
  }
  
  public void getAllImagesFromAPI(final boolean showProgress){
    Account currentAccount = ApiHelper.getCurrentAccount(context);
    if(currentAccount == null){
      return;
    }
    isRefreshing = true;
    String url = String.format(Locale.US ,"%s/images?per_page=%d", ApiHelper.API_URL, Integer.MAX_VALUE);
    AsyncHttpClient client = new AsyncHttpClient();
    client.addHeader("Authorization", String.format("Bearer %s", currentAccount.getToken()));
    client.get(url, new AsyncHttpResponseHandler() {
      NotificationManager notifyManager;
      NotificationCompat.Builder builder;
      
      @Override
      public void onStart() {
        if(showProgress){
          notifyManager =
                  (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
          builder = new NotificationCompat.Builder(context);
          builder.setContentTitle(context.getResources().getString(R.string.synchronising))
              .setContentText(context.getResources().getString(R.string.synchronising_images))
              .setSmallIcon(R.drawable.ic_launcher);
          builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
          notifyManager.notify(NotificationsIndexes.NOTIFICATION_GET_ALL_IMAGES, builder.build());
        }
      }
      
      @Override
      public void onFinish() {
        isRefreshing = false;
        if(showProgress){
          notifyManager.cancel(NotificationsIndexes.NOTIFICATION_GET_ALL_IMAGES);
        }
      }
      
      @Override
      public void onProgress(int bytesWritten, int totalSize) {
        if(showProgress){
          builder.setProgress(100, 100 * bytesWritten / totalSize, false);
          notifyManager.notify(NotificationsIndexes.NOTIFICATION_GET_ALL_IMAGES, builder.build());
        }
      }
      
      @Override
      public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        if(statusCode == 401){
          ApiHelper.showAccessDenied();
        }
      }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(responseBody));
                    List<Image> images = new ArrayList<Image>();
                    JSONArray imageJSONArray = jsonObject.getJSONArray("images");
                    for(int i = 0; i < imageJSONArray.length(); i++){
                        JSONObject imageJSONObject = imageJSONArray.getJSONObject(i);
                        Image image = jsonObjectToImage(imageJSONObject);
                        image.setInUse(true);
                        images.add(image);
                    }
                    ImageService.this.deleteAll();
                    ImageService.this.saveAll(images);
                    ImageService.this.setRequiresRefresh(true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
  }

  public static Image jsonObjectToImage(JSONObject imageJSONObject)
      throws JSONException {
    Image image = new Image();
    image.setId(imageJSONObject.getLong("id"));
    image.setName(imageJSONObject.getString("name"));
    image.setDistribution(imageJSONObject.getString("distribution"));
    if(imageJSONObject.getString("slug").equals("null"))
      image.setSlug("");
    else
      image.setSlug(imageJSONObject.getString("slug"));
        image.setInUse(true);
    image.setPublic(imageJSONObject.getBoolean("public"));
        if(imageJSONObject.has("min_disk_size")) {
            image.setMinDiskSize(imageJSONObject.getInt("min_disk_size"));
        }
        String regions = "";
        for (int i = 0; i < imageJSONObject.getJSONArray("regions").length(); i++) {
            regions += ";" + imageJSONObject.getJSONArray("regions").getString(i);
        }
        image.setRegions(regions.replaceFirst(";", ""));
    return image;
  }
  
  protected void saveAll(List<Image> images) {
    ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
    for (Image image : images) {
      imageDao.create(image);
    }
  }

    public Image findImageById(Long id){
        ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
        return imageDao.findById(id);
    }
  
  /*public List<Image> getAllImages(){
    ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
        return imageDao.getAll(null);
  }*/

  public void deleteAll() {
    ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
    imageDao.deleteAll();  
  }

  public void setRequiresRefresh(Boolean requireRefresh){
    SharedPreferences settings = context.getSharedPreferences("prefrences", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("image_require_refresh", requireRefresh);
    editor.commit();
  }

    public void transferImage(long imageId, String regionSlug){
        Account currentAccount = ApiHelper.getCurrentAccount(context);
        if(currentAccount == null){
            return;
        }
        String url = String.format(Locale.US,"%s/images/%d/actions", ApiHelper.API_URL, imageId);

        HashMap<String,Object> options = new HashMap<String, Object>();
        options.put("type", "transfer");
        options.put("region", regionSlug);

        JSONObject jsonObject = new JSONObject(options);

        AsyncHttpClient client = new AsyncHttpClient();
        client.addHeader("Authorization", String.format("Bearer %s", currentAccount.getToken()));
        ByteArrayEntity entity;
        try {
            entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            client.post(context, url, entity, "application/json", new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    if(statusCode == 401){
                        ApiHelper.showAccessDenied();
                    }
                }
            });
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ActionService.trackActions(context);
    }

    public void updateImage(long imageId, String name){
        Account currentAccount = ApiHelper.getCurrentAccount(context);
        if(currentAccount == null){
            return;
        }
        String url = String.format(Locale.US,"%s/images/%d", ApiHelper.API_URL, imageId);

        HashMap<String,Object> options = new HashMap<String, Object>();
        options.put("name", name);

        JSONObject jsonObject = new JSONObject(options);

        AsyncHttpClient client = new AsyncHttpClient();
        client.addHeader("Authorization", String.format("Bearer %s", currentAccount.getToken()));
        ByteArrayEntity entity;
        try {
            entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            client.put(context, url, entity, "application/json", new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    if(statusCode == 401){
                        ApiHelper.showAccessDenied();
                    }
                }
            });
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ActionService.trackActions(context);
    }
  
  public Boolean requiresRefresh(){
    SharedPreferences settings = context.getSharedPreferences("prefrences", 0);
    return settings.getBoolean("image_require_refresh", true);
  }

  public List<Image> getSnapshotsOnly() {
    ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
        return imageDao.getSnapshotsOnly();
  }
  
  public List<Image> getImagesOnly() {
    ImageDao imageDao = new ImageDao(DatabaseHelper.getInstance(context));
        return imageDao.getImagesOnly();
  }

  public boolean isRefreshing() {
    return isRefreshing;
  }

    public void destroySnapshot(long imageId) {
        Account currentAccount = ApiHelper.getCurrentAccount(context);
        if(currentAccount == null){
            return;
        }
        String url = String.format(Locale.US,"%s/images/%d", ApiHelper.API_URL, imageId);

        AsyncHttpClient client = new AsyncHttpClient();
        client.addHeader("Authorization", String.format("Bearer %s", currentAccount.getToken()));
        try {
            client.delete(context, url, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    if(statusCode == 401){
                        ApiHelper.showAccessDenied();
                    }
                }
            });
        }catch (Exception e) {
            e.printStackTrace();
        }
        ActionService.trackActions(context);
    }
}




Java Source Code List

android.support.v4.preference.PreferenceFragment.java
android.support.v4.preference.PreferenceManagerCompat.java
com.yassirh.digitalocean.data.AccountDao.java
com.yassirh.digitalocean.data.AccountTable.java
com.yassirh.digitalocean.data.DatabaseHelper.java
com.yassirh.digitalocean.data.DomainDao.java
com.yassirh.digitalocean.data.DomainTable.java
com.yassirh.digitalocean.data.DropletDao.java
com.yassirh.digitalocean.data.DropletTable.java
com.yassirh.digitalocean.data.ImageDao.java
com.yassirh.digitalocean.data.ImageTable.java
com.yassirh.digitalocean.data.NetworkDao.java
com.yassirh.digitalocean.data.NetworkTable.java
com.yassirh.digitalocean.data.RecordDao.java
com.yassirh.digitalocean.data.RecordTable.java
com.yassirh.digitalocean.data.RegionDao.java
com.yassirh.digitalocean.data.RegionTable.java
com.yassirh.digitalocean.data.SSHKeyDao.java
com.yassirh.digitalocean.data.SSHKeyTable.java
com.yassirh.digitalocean.data.SizeDao.java
com.yassirh.digitalocean.data.SizeTable.java
com.yassirh.digitalocean.data.SqlDao.java
com.yassirh.digitalocean.data.TableHelper.java
com.yassirh.digitalocean.model.Account.java
com.yassirh.digitalocean.model.Action.java
com.yassirh.digitalocean.model.Domain.java
com.yassirh.digitalocean.model.Droplet.java
com.yassirh.digitalocean.model.Image.java
com.yassirh.digitalocean.model.Network.java
com.yassirh.digitalocean.model.Record.java
com.yassirh.digitalocean.model.Region.java
com.yassirh.digitalocean.model.SSHKey.java
com.yassirh.digitalocean.model.Size.java
com.yassirh.digitalocean.service.AccountService.java
com.yassirh.digitalocean.service.ActionService.java
com.yassirh.digitalocean.service.DomainService.java
com.yassirh.digitalocean.service.DropletService.java
com.yassirh.digitalocean.service.ImageService.java
com.yassirh.digitalocean.service.NotificationsIndexes.java
com.yassirh.digitalocean.service.RecordService.java
com.yassirh.digitalocean.service.RegionService.java
com.yassirh.digitalocean.service.SSHKeyService.java
com.yassirh.digitalocean.service.SizeService.java
com.yassirh.digitalocean.ui.AccountAdapter.java
com.yassirh.digitalocean.ui.AddAccountActivity.java
com.yassirh.digitalocean.ui.DomainAdapter.java
com.yassirh.digitalocean.ui.DomainDetailsDialogFragment.java
com.yassirh.digitalocean.ui.DomainsFragment.java
com.yassirh.digitalocean.ui.DrawerPositions.java
com.yassirh.digitalocean.ui.DropletAdapter.java
com.yassirh.digitalocean.ui.DropletDetailsDialogFragment.java
com.yassirh.digitalocean.ui.DropletResizeDialogFragment.java
com.yassirh.digitalocean.ui.DropletsFragment.java
com.yassirh.digitalocean.ui.ImageAdapter.java
com.yassirh.digitalocean.ui.ImagesFragment.java
com.yassirh.digitalocean.ui.MainActivity.java
com.yassirh.digitalocean.ui.NavigationDrawerAdapter.java
com.yassirh.digitalocean.ui.NewDropletActivity.java
com.yassirh.digitalocean.ui.PrefsFragment.java
com.yassirh.digitalocean.ui.RecordAdapter.java
com.yassirh.digitalocean.ui.RecordCreateDialogFragment.java
com.yassirh.digitalocean.ui.RecordTypeAdapter.java
com.yassirh.digitalocean.ui.RegionAdapter.java
com.yassirh.digitalocean.ui.RegionsFragment.java
com.yassirh.digitalocean.ui.SSHKeyAdapter.java
com.yassirh.digitalocean.ui.SSHKeyCreateDialogFragment.java
com.yassirh.digitalocean.ui.SSHKeyFragment.java
com.yassirh.digitalocean.ui.SettingsActivity.java
com.yassirh.digitalocean.ui.SizeAdapter.java
com.yassirh.digitalocean.ui.SizesFragment.java
com.yassirh.digitalocean.ui.SwitchAccountDialogFragment.java
com.yassirh.digitalocean.ui.Updatable.java
com.yassirh.digitalocean.ui.widget.MultiSelectSpinner.java
com.yassirh.digitalocean.utils.ApiHelper.java
com.yassirh.digitalocean.utils.AppRater.java
com.yassirh.digitalocean.utils.MyApplication.java
com.yassirh.digitalocean.utils.MyBroadcastReceiver.java
com.yassirh.digitalocean.utils.PreferencesHelper.java