View Javadoc
1   package com.srv4pos.server.api.sync.sample;
2   
3   import com.srv4pos.server.api.commodity.CommodityInfo;
4   import com.srv4pos.server.api.sync.EntitySyncAdapter;
5   import com.srv4pos.server.api.sync.Uploader;
6   
7   import java.util.List;
8   
9   public class CommoditySyncAdapter implements EntitySyncAdapter<CommodityInfo> {
10      private final MemoryLocalStorage storage;
11  
12      public CommoditySyncAdapter(MemoryLocalStorage storage) {
13          this.storage = storage;
14      }
15  
16      public void upload(Uploader<CommodityInfo> uploader) {
17          List<SyncCommodity> commodities = storage.getCommodities();
18          for (SyncCommodity commodity : commodities) {
19              if (!commodity.isSynced()) {
20                  doUpload(uploader, commodity);
21              }
22          }
23      }
24  
25      private void doUpload(Uploader<CommodityInfo> uploader, SyncCommodity commodity) {
26          final CommodityInfo commodityInfo = commodity.getInfo();
27  
28          // syncing entity only if it was already synced at least once (has identifier) OR is not deleted
29          //if (commodityInfo.getIdentifier() != null || !commodityInfo.isDeleted()) {
30  
31          commodityInfo.setProduct(commodity.getProduct().getInfo().getIdentifier());
32          commodityInfo.setCategory(commodity.getCategory().getInfo().getIdentifier());
33  
34          final String newIdentifier = uploader.upload(commodityInfo, null);
35          if (newIdentifier != null && newIdentifier.length() > 0) {
36              commodityInfo.setIdentifier(newIdentifier);
37          }
38          //}
39          commodity.setSynced(true);
40      }
41  
42      public void createOrUpdateEntityFromInfo(CommodityInfo info) {
43          SyncCategory category = storage.getCategoryByIdentifier(info.getCategory());
44          SyncProduct product = storage.getProductByIdentifier(info.getProduct());
45  
46          if (category == null) {
47              info.setCategory(null);
48          }
49          if (product == null) {
50              info.setProduct(null);
51          }
52  
53          SyncCommodity commodity = storage.getCommodityByIdentifier(info.getIdentifier());
54  
55          if (commodity == null) {
56              // adding even if info is in "deleted" state (info.isDeleted() == true)
57              commodity = new SyncCommodity(info, product, category);
58              storage.add(commodity);
59          } else {
60              commodity.setInfo(info);
61              commodity.setProduct(product);
62              commodity.setCategory(category);
63          }
64          commodity.setSynced(true);
65      }
66  }