Android Open Source - AndroidShoppingList Server Interface Service






From Project

Back to project page AndroidShoppingList.

License

The source code is released under:

Apache License

If you think the Android project AndroidShoppingList 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

/**
 * Copyright 2012 C. A. Fitzgerald//from   ww w. j  a  va 2  s .  co m
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.github.riotopsys.shoppinglist.server;

import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.github.riotopsys.shoppinglist.AppKeys;
import com.github.riotopsys.shoppinglist.Configurations;
import com.github.riotopsys.shoppinglist.IConfigurations;
import com.github.riotopsys.shoppinglist.model.DatabaseHelper;
import com.github.riotopsys.shoppinglist.model.DigestRecord;
import com.github.riotopsys.shoppinglist.model.PersistedRecord;
import com.github.riotopsys.shoppinglist.model.ShoppingList;
import com.github.riotopsys.shoppinglist.model.ShoppingListItem;
import com.github.riotopsys.shoppinglist.model.Work;
import com.github.riotopsys.shoppinglist.server.work.Operations;
import com.github.riotopsys.shoppinglist.server.work.WorkQueue;
import com.github.riotopsys.shoppinglist.utils.AccountUtils;
import com.google.gson.Gson;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public class ServerInterfaceService extends IntentService {

  private static String TAG = ServerInterfaceService.class.getSimpleName();

  private IConfigurations mConfigs = new Configurations();
  private UrlBuilder mUrlBuilder = new UrlBuilder(mConfigs);
  private AccountUtils mAccountUtils = new AccountUtils();

  public ServerInterfaceService() {
    super(ServerInterfaceService.class.getSimpleName());
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "recieved");

    ServerTask task = (ServerTask) intent.getSerializableExtra(AppKeys.SERVER_TASK_KEY);

    switch (task) {
      case PUSH_WORK:
        pushWork();
        break;
      case SYNC:
        syncData();
        break;
      case FETCH_OBJECT:
        fetchObject(intent);
        break;
      case SUBSCRIBE:
        subscribe(intent);
        break;
      case REGISTER:
        register(intent);
        break;
      case UNREGISTER:
        unregister(intent);
        break;
    }

  }
  
  private void unregister(Intent intent) {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        return;
      }

      URL url = mUrlBuilder.getRegisterUrl(intent.getStringExtra(AppKeys.REG_KEY));

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.delete(url);

      switch (resp.code) {
        case 200:
          break;
        case 406:
          AccountUtils.invalidate(this);
          startService(intent);
        default:
          Log.e(TAG, resp.result);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }
    
  }

  private void register(Intent intent) {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        startService(intent);
        return;
      }

      URL url = mUrlBuilder.getRegisterUrl(intent.getStringExtra(AppKeys.REG_KEY));

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.post(url, null);

      switch (resp.code) {
        case 200:
          break;
        case 406:
          AccountUtils.invalidate(this);
          startService(intent);
        default:
          Log.e(TAG, resp.result);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }
    
  }

  private void subscribe(Intent intent) {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        return;
      }

      URL url = mUrlBuilder.getSubmitWorkUrl();

      Work w = new Work();
      w.target = (UUID) intent.getSerializableExtra(AppKeys.GUID_KEY);
      w.operation = Operations.CREATE_LIST;

      List<Work> workQueue = new LinkedList<Work>();
      workQueue.add(w);

      Gson gson = new Gson();
      String work = gson.toJson(workQueue);
      

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.post(url, work);

      switch (resp.code) {
        case 200:
          syncData();
          break;
        case 406:
          AccountUtils.invalidate(this);
          startService(intent);
        default:
          Log.e(TAG, resp.result);
          WorkQueue.getInstance().reintegrateWork(workQueue);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }

  }

  private void fetchObject(Intent intent) {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        return;
      }

      UUID guid = (UUID) intent.getSerializableExtra(AppKeys.GUID_KEY);

      URL url = mUrlBuilder.getItemUrl(guid);

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.get(url);

      Log.i(TAG, resp.result);

      switch (resp.code) {
        case 200:
          DatabaseHelper databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);

          Gson gson = new Gson();
          PersistedRecord item;

          Intent broadcast;
          if (resp.result.contains("parent")) {
            item = gson.fromJson(resp.result, ShoppingListItem.class);
            broadcast = new Intent(AppKeys.ITEM_UPDATE_ACTION);
          } else {
            item = gson.fromJson(resp.result, ShoppingList.class);
            broadcast = new Intent(AppKeys.LIST_UPDATE_ACTION);
          }

          broadcast.putExtra(AppKeys.GUID_KEY, item.getGuid());
          sendBroadcast(broadcast);

          databaseHelper.createOrUpdate(item);
          OpenHelperManager.releaseHelper();

          break;
        case 406:
          AccountUtils.invalidate(this);
          startService(intent);
        default:
          Log.e(TAG, resp.result);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }
  }

  private void syncData() {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        return;
      }

      URL url = mUrlBuilder.getSubscriptionsUrl();

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.get(url);

      switch (resp.code) {
        case 200:
          Gson gson = new Gson();
          List<DigestRecord> externalDigest = gson.fromJson(resp.result, DigestCollection.class).subscriptions;

          Log.i(TAG, externalDigest.toString());

          DatabaseHelper databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
          List<DigestRecord> internalDigest = databaseHelper.getDigest();

          for (DigestRecord internal : internalDigest) {
            if (externalDigest.contains(internal)) {
              // the item exists in both sets
              DigestRecord external = externalDigest.get(externalDigest.indexOf(internal));
              if (external.timestamp > internal.timestamp) {
                // the internal timestamp is old get an update
                fetch(internal.guid);
              }
              // remove handled item
              externalDigest.remove(external);
            } else {
              // the internal item is not in external set
              // remove it
              PersistedRecord record = databaseHelper.getShoppingListItem(internal.guid);
              if (record == null) {
                record = databaseHelper.getShoppingList(internal.guid);
              }
              databaseHelper.delete(record);
              
              Intent broadcast;
              if (record instanceof ShoppingListItem) {
                broadcast = new Intent(AppKeys.ITEM_UPDATE_ACTION);
              } else {
                broadcast = new Intent(AppKeys.LIST_UPDATE_ACTION);
              }
              broadcast.putExtra(AppKeys.GUID_KEY, record.getGuid());
              sendBroadcast(broadcast);
            }
          }

          // process remaining external items
          for (DigestRecord external : externalDigest) {
            fetch(external.guid);
          }

          OpenHelperManager.releaseHelper();

          break;
        case 406:
          AccountUtils.invalidate(this);
          Intent i = new Intent(this, ServerInterfaceService.class);
          i.putExtra(AppKeys.SERVER_TASK_KEY, ServerTask.SYNC);
          startService(i);
        default:
          Log.e(TAG, resp.result);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }
  }

  private void fetch(UUID guid) {
    Intent i = new Intent(this, ServerInterfaceService.class);
    i.putExtra(AppKeys.SERVER_TASK_KEY, ServerTask.FETCH_OBJECT);
    i.putExtra(AppKeys.GUID_KEY, guid);
    startService(i);
  }

  private void pushWork() {
    String token;
    try {
      token = mAccountUtils.getToken(this);
      if (token == null) {
        return;
      }

      URL url = mUrlBuilder.getSubmitWorkUrl();

      List<Work> workQueue = WorkQueue.getInstance().getAvailableWork();

      Gson gson = new Gson();
      String work = gson.toJson(workQueue);

      RestHelper restHelper = new RestHelper(token);
      RestResult<String> resp = restHelper.post(url, work);

      switch (resp.code) {
        case 200:
          break;
        case 406:
          AccountUtils.invalidate(this);
          Intent i = new Intent(this, ServerInterfaceService.class);
          i.putExtra(AppKeys.SERVER_TASK_KEY, ServerTask.PUSH_WORK);
          startService(i);
        default:
          Log.e(TAG, resp.result);
          WorkQueue.getInstance().reintegrateWork(workQueue);
          break;
      }

    } catch (Exception e) {
      Log.e(TAG, "", e);
    }

  }

}




Java Source Code List

com.github.riotopsys.shoppinglist.AppKeys.java
com.github.riotopsys.shoppinglist.GCMIntentService.java
com.github.riotopsys.shoppinglist.IConfigurations.java
com.github.riotopsys.shoppinglist.activity.ListItemEdit.java
com.github.riotopsys.shoppinglist.activity.ShoppingListPreview.java
com.github.riotopsys.shoppinglist.adapter.ShoppingListAdapter.java
com.github.riotopsys.shoppinglist.adapter.ShoppingListCollectionAdapter.java
com.github.riotopsys.shoppinglist.comparator.ListItemNameComparator.java
com.github.riotopsys.shoppinglist.comparator.ListNameComparator.java
com.github.riotopsys.shoppinglist.fragment.ShoppingListFragment.java
com.github.riotopsys.shoppinglist.listener.CheckedChangeListener.java
com.github.riotopsys.shoppinglist.model.DatabaseHelper.java
com.github.riotopsys.shoppinglist.model.DigestRecord.java
com.github.riotopsys.shoppinglist.model.PersistedRecord.java
com.github.riotopsys.shoppinglist.model.ShoppingListCollection.java
com.github.riotopsys.shoppinglist.model.ShoppingListItem.java
com.github.riotopsys.shoppinglist.model.ShoppingList.java
com.github.riotopsys.shoppinglist.model.Work.java
com.github.riotopsys.shoppinglist.server.DigestCollection.java
com.github.riotopsys.shoppinglist.server.RestHelper.java
com.github.riotopsys.shoppinglist.server.RestResult.java
com.github.riotopsys.shoppinglist.server.ServerInterfaceService.java
com.github.riotopsys.shoppinglist.server.ServerTask.java
com.github.riotopsys.shoppinglist.server.UrlBuilder.java
com.github.riotopsys.shoppinglist.server.work.Operations.java
com.github.riotopsys.shoppinglist.server.work.WorkQueue.java
com.github.riotopsys.shoppinglist.utils.AccountUtils.java