Search in sources :

Example 1 with WPJsonPost

use of org.michenux.drodrolib.wordpress.json.WPJsonPost in project YourAppIdea by Michenux.

the class TutorialSyncAdapter method onPerformSync.

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    ((YourApplication) getContext().getApplicationContext()).setSyncAdapterRunning(true);
    LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(SYNC_STARTED));
    try {
        boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
        WPJsonPost newPost = retrievePosts(AppUsageUtils.getLastSync(this.getContext()), provider);
        if (BuildConfig.DEBUG) {
            Log.d(YourApplication.LOG_TAG, "tutorialSyncAdapter.onPerformSync() - manual:" + manualSync);
        }
        if (newPost != null) {
            // notification only if not manual sync
            if (!manualSync) {
                sendNotification(newPost);
            }
        } else {
            if (BuildConfig.DEBUG) {
                Log.d(YourApplication.LOG_TAG, "  no new post");
            }
        }
        if (!manualSync) {
            mSyncHelper.adjustSyncInterval(TutorialSyncAdapter.this.getContext());
        }
        AppUsageUtils.updateLastSync(TutorialSyncAdapter.this.getContext());
    } catch (ParseException e) {
        Log.e(YourApplication.LOG_TAG, "tutorialSyncAdapter.onPerformSync()", e);
        syncResult.stats.numParseExceptions++;
    } catch (InterruptedException | ExecutionException | RemoteException | OperationApplicationException e) {
        Log.e(YourApplication.LOG_TAG, "tutorialSyncAdapter.onPerformSync()", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(SYNC_FINISHED));
        ((YourApplication) getContext().getApplicationContext()).setSyncAdapterRunning(false);
    }
}
Also used : YourApplication(org.michenux.yourappidea.YourApplication) WPJsonPost(org.michenux.drodrolib.wordpress.json.WPJsonPost) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) ParseException(java.text.ParseException) ExecutionException(java.util.concurrent.ExecutionException) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 2 with WPJsonPost

use of org.michenux.drodrolib.wordpress.json.WPJsonPost in project YourAppIdea by Michenux.

the class TutorialSyncAdapter method retrievePosts.

private WPJsonPost retrievePosts(long lastSync, ContentProviderClient provider) throws InterruptedException, ExecutionException, ParseException, RemoteException, OperationApplicationException {
    if (BuildConfig.DEBUG) {
        Log.d(YourApplication.LOG_TAG, "tutorialSyncAdapter.retrievePosts()");
    }
    WordpressService wordpressService = WordpressServiceFactory.create(getContext());
    Observable<WPJsonResponse> observable = wordpressService.query("get_recent_posts", "android", "android_desc", "android", 9999);
    WPJsonResponse response = observable.toBlocking().first();
    WPJsonPost newPost = null;
    if (response.getStatus().equals(WPJsonResponse.STATUS_OK) && response.getPosts() != null && !response.getPosts().isEmpty()) {
        final WPJsonPost lastPost = response.getPosts().get(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.FRENCH);
        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
        Date lastPostDate = sdf.parse(lastPost.getDate());
        Date lastSyncDate = new Date(lastSync);
        if (BuildConfig.DEBUG) {
            Log.d(YourApplication.LOG_TAG, "title:" + lastPost.getTitle());
            Log.d(YourApplication.LOG_TAG, "date: " + lastPost.getDate());
            Log.d(YourApplication.LOG_TAG, "lastSync: " + sdf.format(lastSync));
        }
        if (lastPostDate.after(lastSyncDate)) {
            newPost = lastPost;
        }
        updateDatabase(response.getPosts(), provider);
    //if (ConnectivityUtils.isConnectedWifi(TutorialSyncAdapter.this.getContext()) &&
    //        BatteryUtils.isChargingOrFull(TutorialSyncAdapter.this.getContext())) {
    //load image
    //}
    } else if (BuildConfig.DEBUG) {
        Log.d(YourApplication.LOG_TAG, "result is null or empty");
    }
    return newPost;
}
Also used : WPJsonPost(org.michenux.drodrolib.wordpress.json.WPJsonPost) WPJsonResponse(org.michenux.drodrolib.wordpress.json.WPJsonResponse) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 3 with WPJsonPost

use of org.michenux.drodrolib.wordpress.json.WPJsonPost in project YourAppIdea by Michenux.

the class TutorialSyncAdapter method updateDatabase.

private void updateDatabase(List<WPJsonPost> posts, ContentProviderClient provider) throws RemoteException, OperationApplicationException, ParseException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.FRENCH);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
    for (WPJsonPost post : posts) {
        String thumbnail = "";
        if (post.getThumbnailImages() != null && post.getThumbnailImages().getFoundationFeaturedImage() != null) {
            thumbnail = post.getThumbnailImages().getFoundationFeaturedImage().getUrl();
        }
        Date postCreationDate = sdf.parse(post.getDate());
        Date postModifDate = sdf.parse(post.getDate());
        Cursor cursor = getContext().getContentResolver().query(// The content URI of the words table
        TutorialContentProvider.CONTENT_URI, // The columns to return for each row
        new String[] { TutorialContentProvider.DATEMODIFICATION_COLUMN }, // Selection criteria
        TutorialContentProvider.POSTID_COLUMN + "= ?", // Selection criteria
        new String[] { Integer.toString(post.getId()) }, null);
        boolean insertOrModified = false;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                long modificationDate = CursorUtils.getLong(TutorialContentProvider.DATEMODIFICATION_COLUMN, cursor);
                if (modificationDate != (postModifDate.getTime() / 1000)) {
                    if (BuildConfig.DEBUG) {
                        Log.d(YourApplication.LOG_TAG, "updated post: " + post.getId());
                    }
                    // delete the old one if modified
                    ops.add(ContentProviderOperation.newDelete(TutorialContentProvider.CONTENT_URI).withSelection(TutorialContentProvider.POSTID_COLUMN + " = ?", new String[] { Integer.toString(post.getId()) }).build());
                    insertOrModified = true;
                } else {
                    if (BuildConfig.DEBUG) {
                        Log.d(YourApplication.LOG_TAG, "unchanged post: " + post.getId() + ", not inserting.");
                    }
                }
            } else {
                if (BuildConfig.DEBUG) {
                    Log.d(YourApplication.LOG_TAG, "new post: " + post.getId());
                }
                insertOrModified = true;
            }
            cursor.close();
        }
        if (insertOrModified) {
            // insert if new or modified
            ops.add(ContentProviderOperation.newInsert(TutorialContentProvider.CONTENT_URI).withValue(TutorialContentProvider.POSTID_COLUMN, post.getId()).withValue(TutorialContentProvider.TITLE_COLUMN, post.getTitle()).withValue(TutorialContentProvider.DESCRIPTION_COLUMN, post.getExcerpt()).withValue(TutorialContentProvider.THUMBNAIL_COLMUN, thumbnail).withValue(TutorialContentProvider.URL_COLUMN, post.getUrl()).withValue(TutorialContentProvider.CONTENT_COLUMN, post.getContent()).withValue(TutorialContentProvider.AUTHOR_COLUMN, post.getAuthor().getName()).withValue(TutorialContentProvider.DATECREATION_COLUMN, postCreationDate.getTime() / 1000).withValue(TutorialContentProvider.DATEMODIFICATION_COLUMN, postModifDate.getTime() / 1000).withYieldAllowed(false).build());
        }
    }
    // Keep last 50 posts
    String deleteSelection = TutorialContentProvider.ID_COLUMN + " not in ( select " + TutorialContentProvider.ID_COLUMN + " from " + TutorialContentProvider.TABLE_NAME + " order by " + TutorialContentProvider.DATECREATION_COLUMN + " desc limit 50 )";
    String[] deleteParams = new String[] {};
    int actuToDelete = ContentProviderUtils.count(TutorialContentProvider.CONTENT_URI, deleteSelection, deleteParams, this.getContext().getContentResolver());
    if (BuildConfig.DEBUG) {
        Log.d(YourApplication.LOG_TAG, actuToDelete + " old posts to delete");
    }
    if (actuToDelete > 0) {
        ops.add(ContentProviderOperation.newDelete(TutorialContentProvider.CONTENT_URI).withSelection(deleteSelection, deleteParams).build());
    }
    if (!ops.isEmpty()) {
        if (BuildConfig.DEBUG) {
            Log.d(YourApplication.LOG_TAG, "execute batch");
        }
        provider.applyBatch(ops);
    } else {
        if (BuildConfig.DEBUG) {
            Log.d(YourApplication.LOG_TAG, "ignore batch, empty");
        }
    }
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) WPJsonPost(org.michenux.drodrolib.wordpress.json.WPJsonPost) Cursor(android.database.Cursor) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 4 with WPJsonPost

use of org.michenux.drodrolib.wordpress.json.WPJsonPost in project YourAppIdea by Michenux.

the class WordpressServiceTest method testQuery.

@Test
public void testQuery() throws Exception {
    WordpressService wordpressService = WordpressServiceFactory.create(mContext);
    Observable<WPJsonResponse> observable = wordpressService.query("get_recent_posts", "android", "android_desc", "android", 9999);
    TestSubscriber<WPJsonResponse> testSubscriber = new TestSubscriber<>();
    observable.subscribe(testSubscriber);
    testSubscriber.assertNoErrors();
    List<WPJsonResponse> jsonPosts = testSubscriber.getOnNextEvents();
    Assert.assertNotNull(jsonPosts);
    Assert.assertFalse(jsonPosts.isEmpty());
    WPJsonResponse response = jsonPosts.get(0);
    Assert.assertEquals(response.getStatus(), "ok");
    List<WPJsonPost> posts = response.getPosts();
    Assert.assertNotNull(posts);
    Assert.assertFalse(posts.isEmpty());
}
Also used : WPJsonPost(org.michenux.drodrolib.wordpress.json.WPJsonPost) TestSubscriber(rx.observers.TestSubscriber) WPJsonResponse(org.michenux.drodrolib.wordpress.json.WPJsonResponse) WordpressService(org.michenux.yourappidea.tutorial.sync.WordpressService) Test(org.junit.Test)

Aggregations

WPJsonPost (org.michenux.drodrolib.wordpress.json.WPJsonPost)4 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 WPJsonResponse (org.michenux.drodrolib.wordpress.json.WPJsonResponse)2 PendingIntent (android.app.PendingIntent)1 ContentProviderOperation (android.content.ContentProviderOperation)1 Intent (android.content.Intent)1 OperationApplicationException (android.content.OperationApplicationException)1 Cursor (android.database.Cursor)1 RemoteException (android.os.RemoteException)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 Test (org.junit.Test)1 YourApplication (org.michenux.yourappidea.YourApplication)1 WordpressService (org.michenux.yourappidea.tutorial.sync.WordpressService)1 TestSubscriber (rx.observers.TestSubscriber)1