Search in sources :

Example 6 with LinkedMap

use of org.apache.commons.collections4.map.LinkedMap in project cuba by cuba-platform.

the class CollectionDatasourceImpl method addItemFirst.

@Override
public void addItemFirst(T item) {
    checkNotNullArgument(item, "item is null");
    internalAddItem(item, () -> {
        LinkedMap tmpMap = (LinkedMap) data.clone();
        data.clear();
        data.put(item.getId(), item);
        data.putAll(tmpMap);
    });
}
Also used : LinkedMap(org.apache.commons.collections4.map.LinkedMap)

Example 7 with LinkedMap

use of org.apache.commons.collections4.map.LinkedMap in project MPW by shineangelic.

the class PoolDbHelper method getWalletHistoryData.

public LinkedMap<Date, Wallet> getWalletHistoryData(@NonNull BackToEnum cutoff) {
    LinkedMap<Date, Wallet> ret = new LinkedMap<>();
    int cnt = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    String limitCause = "";
    Calendar now = Calendar.getInstance();
    switch(cutoff) {
        case ONE_DAY:
            now.add(Calendar.DATE, -1);
            limitCause = DataBaseContract.Wallet_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_WEEK:
            now.add(Calendar.DATE, -7);
            limitCause = DataBaseContract.Wallet_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_MONTH:
            now.add(Calendar.MONTH, -1);
            limitCause = DataBaseContract.Wallet_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        default:
            Log.e("DB", "Unexpected switch ERROR");
            break;
    }
    // Cursor cursor = db.rawQuery(selectQuery, null);
    Cursor cursor = db.query(DataBaseContract.Wallet_.TABLE_NAME, new String[] { DataBaseContract.Wallet_._ID, DataBaseContract.Wallet_.COLUMN_NAME_DTM, DataBaseContract.Wallet_.COLUMN_NAME_JSON }, limitCause, // String[] selectionArgs
    null, null, // HAVING
    null, // ORDER BY
    DataBaseContract.Wallet_.COLUMN_NAME_DTM + " ASC");
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        Gson gson = builder.create();
        do {
            try {
                // Register an adapter to manage the date types as long values
                Wallet retrieved = gson.fromJson(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.Wallet_.COLUMN_NAME_JSON)), Wallet.class);
                cnt++;
                // Adding contact to list
                Date curDate = new Date(cursor.getLong(cursor.getColumnIndexOrThrow(DataBaseContract.Wallet_.COLUMN_NAME_DTM)));
                ret.put(curDate, retrieved);
            } catch (Exception ce) {
                Log.e(TAG, "Cant read WalletHistoryData entry: " + ce.getMessage());
            }
        } while (cursor.moveToNext());
    }
    Log.i(TAG, "SELECT DONE. WALLET HISTORY SIZE: " + cnt);
    cursor.close();
    return ret;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Wallet(it.angelic.mpw.model.jsonpojos.wallet.Wallet) Calendar(java.util.Calendar) Gson(com.google.gson.Gson) Cursor(android.database.Cursor) LinkedMap(org.apache.commons.collections4.map.LinkedMap) Date(java.util.Date)

Example 8 with LinkedMap

use of org.apache.commons.collections4.map.LinkedMap in project MPW by shineangelic.

the class PoolDbHelper method getHistoryData.

public LinkedMap<Date, HomeStats> getHistoryData(@NonNull BackToEnum cutoff) {
    int cnt = 0;
    LinkedMap<Date, HomeStats> ret = new LinkedMap<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String limitCause = "";
    Calendar now = Calendar.getInstance();
    switch(cutoff) {
        case ONE_DAY:
            now.add(Calendar.DATE, -1);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_WEEK:
            now.add(Calendar.DATE, -7);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_MONTH:
            now.add(Calendar.MONTH, -1);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        default:
            Log.e("DB", "Unexpected switch ERROR");
            break;
    }
    // Cursor cursor = db.rawQuery(selectQuery, null);
    Cursor cursor = db.query(DataBaseContract.HomeStats_.TABLE_NAME, new String[] { DataBaseContract.HomeStats_._ID, DataBaseContract.HomeStats_.COLUMN_NAME_DTM, DataBaseContract.HomeStats_.COLUMN_NAME_JSON }, limitCause, // String[] selectionArgs
    null, null, // HAVING
    null, // ORDER BY
    DataBaseContract.HomeStats_.COLUMN_NAME_DTM + " ASC");
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        Gson gson = builder.create();
        do {
            try {
                // Register an adapter to manage the date types as long values
                HomeStats retrieved = gson.fromJson(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.HomeStats_.COLUMN_NAME_JSON)), HomeStats.class);
                // Adding contact to list
                ret.put(retrieved.getNow().getTime(), retrieved);
                cnt++;
            } catch (Exception ce) {
                Log.e(TAG, "Cant read HistoryData entry: " + ce.getMessage());
            }
        } while (cursor.moveToNext());
    }
    Log.i(TAG, "SELECT DONE. HOME HISTORY SIZE: " + cnt);
    cursor.close();
    return ret;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Calendar(java.util.Calendar) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) Cursor(android.database.Cursor) LinkedMap(org.apache.commons.collections4.map.LinkedMap) Date(java.util.Date)

Example 9 with LinkedMap

use of org.apache.commons.collections4.map.LinkedMap in project MPW by shineangelic.

the class MainActivity method onCreate.

/* private static long getAverageBlockSecondsSincePoolsBirth(HomeStats lastHit) {
        final Date firstBlockDate = new Date();//2017/07/15
        firstBlockDate.setTime(1500099900000L);
        long datediffFirst = (new Date().getTime() - firstBlockDate.getTime()) / 1000;
        //meno uno perche` il conto parte dal secondo blocco. Il primo boh
        return datediffFirst / (lastHit.getMaturedTotal() - 1);
    }*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Locale current = getResources().getConfiguration().locale;
    mDbHelper = new PoolDbHelper(this, mPool, mCur);
    builder = new GsonBuilder();
    // gestione UNIX time lungo e non
    builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
    builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
    noobText = findViewById(R.id.textViewWalletTitle);
    hashText = findViewById(R.id.hashrateText);
    textViewNetDiffTitle = findViewById(R.id.textViewWalHashrateTitle);
    poolLastBeat = findViewById(R.id.textViewWalLastShareValue);
    textViewNetDiffValue = findViewById(R.id.textViewNetDiffValue);
    lastFoundTextLabel = findViewById(R.id.textViewLastBlock);
    lastFoundText = findViewById(R.id.textViewWalPaymentsValue);
    onlineMinersText = findViewById(R.id.textViewWalCurHashrateValue);
    textViewBlockChainHeightValue = findViewById(R.id.textViewBlockChainHeightValue);
    poolHashrateText = findViewById(R.id.textViewPoolHashrateValue);
    roundSharesText = findViewById(R.id.textViewRoundSharesValue);
    textViewVarianceValue = findViewById(R.id.textViewVarianceValue);
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Async Refresh Sent", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            issueRefresh(mDbHelper, builder);
        }
    });
    // i grafici hanno controlli globali
    RadioGroup radioGroupChartGranularity = findViewById(R.id.radioDifficultyGranularity);
    radioGroupBackTo = findViewById(R.id.radioBackto);
    final RadioButton radioDay = findViewById(R.id.radioButtonDay);
    final RadioButton radioMin = findViewById(R.id.radioButtonMinutes);
    final RadioGroup.OnCheckedChangeListener mescola = new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            radioGroupBackTo.post(new Runnable() {

                @Override
                public void run() {
                    GranularityEnum granoEnum = GranularityEnum.HOUR;
                    if (radioDay.isChecked())
                        granoEnum = GranularityEnum.DAY;
                    else if (radioMin.isChecked())
                        granoEnum = GranularityEnum.MINUTE;
                    int radioButtonID = radioGroupBackTo.getCheckedRadioButtonId();
                    View radioButton = findViewById(radioButtonID);
                    LinkedMap<Date, HomeStats> storia = mDbHelper.getHistoryData(BackToEnum.valueOf((String) radioButton.getTag()));
                    ChartUtils.drawDifficultyHistory(textViewNetDiffTitle, PoolQueryGrouper.groupAvgQueryResult(storia, granoEnum), (LineView) findViewById(R.id.line_view_difficulty), granoEnum);
                    ChartUtils.drawHashrateHistory(hashText, PoolQueryGrouper.groupAvgQueryResult(storia, granoEnum), (LineView) findViewById(R.id.line_view_hashrate), granoEnum);
                }
            });
        }
    };
    radioGroupBackTo.setOnCheckedChangeListener(mescola);
    radioGroupChartGranularity.setOnCheckedChangeListener(mescola);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    Job myJob = MPWCoinmarketcapService.getJobUpdate(dispatcher);
    dispatcher.schedule(myJob);
    // ADS
    AdView mAdView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
}
Also used : RadioGroup(android.widget.RadioGroup) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) LinkedMap(org.apache.commons.collections4.map.LinkedMap) AdRequest(com.google.android.gms.ads.AdRequest) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) FloatingActionButton(android.support.design.widget.FloatingActionButton) DrawerLayout(android.support.v4.widget.DrawerLayout) Job(com.firebase.jobdispatcher.Job) AdView(com.google.android.gms.ads.AdView) PoolDbHelper(it.angelic.mpw.model.db.PoolDbHelper) Toolbar(android.support.v7.widget.Toolbar) FirebaseJobDispatcher(com.firebase.jobdispatcher.FirebaseJobDispatcher) GsonBuilder(com.google.gson.GsonBuilder) GooglePlayDriver(com.firebase.jobdispatcher.GooglePlayDriver) RadioButton(android.widget.RadioButton) NavigationView(android.support.design.widget.NavigationView) LineView(im.dacer.androidcharts.LineView) View(android.view.View) AdView(com.google.android.gms.ads.AdView) TextView(android.widget.TextView) LineView(im.dacer.androidcharts.LineView) GranularityEnum(it.angelic.mpw.model.db.GranularityEnum)

Example 10 with LinkedMap

use of org.apache.commons.collections4.map.LinkedMap in project MPW by shineangelic.

the class MPWService method onStartJob.

@Override
public boolean onStartJob(JobParameters job) {
    final JobParameters jobC = job;
    Log.e(TAG, "SERVICE START");
    final Context ctx = MPWService.this;
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    try {
        final PoolEnum mPool = PoolEnum.valueOf(prefs.getString("poolEnum", ""));
        final CurrencyEnum mCur = CurrencyEnum.valueOf(prefs.getString("curEnum", ""));
        Log.i(TAG, "Miner Pool Watcher Service call:" + Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(ctx)));
        Log.i(TAG, "SERVICE working on:" + mPool.toString() + " - " + mCur.toString());
        final PoolDbHelper mDbHelper = new PoolDbHelper(ctx, mPool, mCur);
        final NotificationManager mNotifyMgr = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
        final GsonBuilder builder = new GsonBuilder();
        // gestione UNIX time lungo e non
        builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
        builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
        // load extra
        final String minerAddr = job.getExtras().getString("WALLETURL");
        final Boolean notifyBlock = job.getExtras().getBoolean("NOTIFY_BLOCK", false);
        final Boolean notifyOffline = job.getExtras().getBoolean("NOTIFY_OFFLINE", false);
        final Boolean notifyPayment = job.getExtras().getBoolean("NOTIFY_PAYMENT", false);
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(ctx)), null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                Gson gson = builder.create();
                // Register an adapter to manage the date types as long values
                HomeStats retrieved = gson.fromJson(response.toString(), HomeStats.class);
                mDbHelper.logHomeStats(retrieved);
                // dati semi grezzi
                LinkedMap<Date, HomeStats> ultimi = mDbHelper.getLastHomeStats(LAST_TWO);
                Log.d(TAG, "data size: " + ultimi.size() + " notifyOffline: " + ultimi.get(ultimi.get(0)).getMaturedTotal());
                // controllo se manca qualcuno
                if (notifyBlock && ultimi.size() > 1 && ultimi.get(ultimi.get(0)).getMaturedTotal().compareTo(ultimi.get(ultimi.get(1)).getMaturedTotal()) > 0) {
                    int diff = ultimi.get(ultimi.get(0)).getMaturedTotal() - ultimi.get(ultimi.get(1)).getMaturedTotal();
                    sendBlockNotification(getApplication(), diff + " new block. " + mPool.toString() + " has found " + ultimi.get(ultimi.get(0)).getMaturedTotal() + " blocks", mPool);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });
        if (minerAddr != null) {
            Log.i(TAG, "refreshing wallet " + minerAddr + " notify: " + notifyBlock);
            JsonObjectRequest jsonObjReqWallet = new JsonObjectRequest(Request.Method.GET, Utils.getWalletStatsUrl(PreferenceManager.getDefaultSharedPreferences(ctx)) + minerAddr, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    Gson gson = builder.create();
                    // Register an adapter to manage the date types as long values
                    Wallet retrieved = gson.fromJson(response.toString(), Wallet.class);
                    mDbHelper.logWalletStats(retrieved);
                    // dati semi grezzi
                    LinkedMap<Date, Wallet> ultimi = mDbHelper.getLastWallets(LAST_TWO);
                    // controllo se manca qualcuno
                    if (notifyOffline && ultimi.keySet().size() >= LAST_TWO) {
                        if (ultimi.get(ultimi.firstKey()).getWorkersOnline() < ultimi.get(ultimi.get(1)).getWorkersOnline()) {
                            sendOfflineNotification(ctx, "A Worker has gone OFFLINE. Online Workers: " + ultimi.get(ultimi.firstKey()).getWorkersOnline(), mPool);
                        } else if (ultimi.get(ultimi.firstKey()).getWorkersOnline() > ultimi.get(ultimi.get(1)).getWorkersOnline()) {
                            // togli notifiche di offline
                            mNotifyMgr.cancel(NOTIFICATION_MINER_OFFLINE);
                        }
                    // else uguali, fa nulla
                    }
                    if (notifyPayment && ultimi.keySet().size() >= LAST_TWO && ultimi.get(ultimi.firstKey()).getPayments().size() > ultimi.get(ultimi.get(1)).getPayments().size()) {
                        sendPaymentNotification(ctx, "You received a payment: " + Utils.formatEthCurrency(ctx, ultimi.get(ultimi.firstKey()).getPayments().get(0).getAmount()), mCur.toString() + " payment from " + mPool.toString());
                    }
                    Log.e(TAG, "SERVICE END Ok1");
                    MPWService.this.jobFinished(jobC, false);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "SERVICE END KO1");
                    MPWService.this.jobFinished(jobC, true);
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                // hide the progress dialog
                }
            });
            JSONClientSingleton.getInstance(ctx).addToRequestQueue(jsonObjReqWallet);
        } else {
            // job end tutto bene
            MPWService.this.jobFinished(job, false);
        }
        // Adding request to request queue
        JSONClientSingleton.getInstance(ctx).addToRequestQueue(jsonObjReq);
    } catch (Exception se) {
        Log.e(TAG, "SERVICE ERROR: " + se);
        Crashlytics.logException(se);
    }
    // Answers the question: "Is there still work going on?"
    return true;
}
Also used : Context(android.content.Context) VolleyError(com.android.volley.VolleyError) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) GsonBuilder(com.google.gson.GsonBuilder) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) Wallet(it.angelic.mpw.model.jsonpojos.wallet.Wallet) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) LinkedMap(org.apache.commons.collections4.map.LinkedMap) Response(com.android.volley.Response) PoolEnum(it.angelic.mpw.model.enums.PoolEnum) JSONObject(org.json.JSONObject) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) JobParameters(com.firebase.jobdispatcher.JobParameters) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) CurrencyEnum(it.angelic.mpw.model.enums.CurrencyEnum) PoolDbHelper(it.angelic.mpw.model.db.PoolDbHelper)

Aggregations

LinkedMap (org.apache.commons.collections4.map.LinkedMap)11 Date (java.util.Date)6 Gson (com.google.gson.Gson)5 Cursor (android.database.Cursor)4 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 HomeStats (it.angelic.mpw.model.jsonpojos.home.HomeStats)4 Wallet (it.angelic.mpw.model.jsonpojos.wallet.Wallet)4 Calendar (java.util.Calendar)4 GsonBuilder (com.google.gson.GsonBuilder)2 MyDateTypeAdapter (it.angelic.mpw.model.MyDateTypeAdapter)2 MyTimeStampTypeAdapter (it.angelic.mpw.model.MyTimeStampTypeAdapter)2 PoolDbHelper (it.angelic.mpw.model.db.PoolDbHelper)2 NotificationManager (android.app.NotificationManager)1 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 FloatingActionButton (android.support.design.widget.FloatingActionButton)1 NavigationView (android.support.design.widget.NavigationView)1 DrawerLayout (android.support.v4.widget.DrawerLayout)1 ActionBarDrawerToggle (android.support.v7.app.ActionBarDrawerToggle)1 Toolbar (android.support.v7.widget.Toolbar)1