Skip to content

Commit

Permalink
Merge pull request #165 from Infosys/cron-job
Browse files Browse the repository at this point in the history
Cron job for auto upload
  • Loading branch information
jainhitesh9998 authored Oct 9, 2023
2 parents 9cb4338 + 057c569 commit d524132
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 83 deletions.
1 change: 1 addition & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ dependencies {
implementation "androidx.fragment:fragment:$fragment_version"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation 'com.cronutils:cron-utils:9.1.5'

androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
Expand Down
3 changes: 2 additions & 1 deletion android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<service android:name=".MyBackgroundService" />
<service android:name=".SyncBackgroundService" />
<service android:name=".UploadBackgroundService" />
<activity
android:name=".MainActivity"
android:exported="true"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.mosip.registration_client;

import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;

import java.time.ZonedDateTime;
import java.util.Date;

public class CronParserUtil {

public static long getNextExecutionTimeInMillis(String cronExpression) {
CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
Cron cron = parser.parse(cronExpression);

ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(cron);

Date nextExecution = Date.from(executionTime.nextExecution(now).get().toInstant());

return nextExecution.getTime();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import com.fasterxml.jackson.databind.ObjectWriter;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

import javax.inject.Inject;

Expand All @@ -34,11 +36,15 @@
import io.mosip.registration.clientmanager.config.AppModule;
import io.mosip.registration.clientmanager.config.NetworkModule;
import io.mosip.registration.clientmanager.config.RoomModule;
import io.mosip.registration.clientmanager.constant.PacketTaskStatus;
import io.mosip.registration.clientmanager.constant.PacketClientStatus;
import io.mosip.registration.clientmanager.dao.GlobalParamDao;
import io.mosip.registration.clientmanager.entity.GlobalParam;
import io.mosip.registration.clientmanager.entity.Registration;
import io.mosip.registration.clientmanager.entity.SyncJobDef;
import io.mosip.registration.clientmanager.repository.GlobalParamRepository;
import io.mosip.registration.clientmanager.repository.IdentitySchemaRepository;
import io.mosip.registration.clientmanager.repository.RegistrationCenterRepository;
import io.mosip.registration.clientmanager.repository.SyncJobDefRepository;
import io.mosip.registration.clientmanager.repository.UserDetailRepository;
import io.mosip.registration.clientmanager.service.LoginService;
import io.mosip.registration.clientmanager.spi.AuditManagerService;
Expand Down Expand Up @@ -147,94 +153,131 @@ public class MainActivity extends FlutterActivity {
@Inject
MasterDataSyncApi masterDataSyncApi;

@Inject
SyncJobDefRepository syncJobDefRepository;

@Inject
GlobalParamDao globalParamDao;

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("BACKGROUND_TASK_COMPLETE")) {
fetchRegistrationPackets(context);
if (intent.getAction().equals("REGISTRATION_PACKET_SYNC")) {
syncRegistrationPackets(context);
}
if (intent.getAction().equals("REGISTRATION_PACKET_UPLOAD")) {
uploadRegistrationPackets(context);
}
}
};

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createBackgroundTask();
IntentFilter intentFilter = new IntentFilter("BACKGROUND_TASK_COMPLETE");
registerReceiver(broadcastReceiver, intentFilter);

Intent serviceIntentSync = new Intent(this, SyncBackgroundService.class);
createBackgroundTask(serviceIntentSync, "registrationPacketSyncJob");
IntentFilter intentFilterSync = new IntentFilter("REGISTRATION_PACKET_SYNC");
registerReceiver(broadcastReceiver, intentFilterSync);

Intent serviceIntentUpload = new Intent(this, UploadBackgroundService.class);
createBackgroundTask(serviceIntentUpload, "registrationPacketUploadJob");
IntentFilter intentFilterUpload = new IntentFilter("REGISTRATION_PACKET_UPLOAD");
registerReceiver(broadcastReceiver, intentFilterUpload);
}

@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the BroadcastReceiver when the activity is destroyed
unregisterReceiver(broadcastReceiver);
Intent serviceIntent = new Intent(this, MyBackgroundService.class);
stopService(serviceIntent);
Log.d(getClass().getSimpleName(),"Background Service Stopped");
}

void createBackgroundTask(){
Intent serviceIntent = new Intent(this, MyBackgroundService.class);

// Create a PendingIntent with the appropriate flags
void createBackgroundTask(Intent intent, String api){
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getForegroundService(
this,
0, // Request code
serviceIntent,
intent,
PendingIntent.FLAG_IMMUTABLE
);
} else {
pendingIntent = PendingIntent.getService(
this,
0, // Request code
serviceIntent,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
}

// Get an instance of AlarmManager
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

// Set the alarm to trigger your PendingIntent after a certain interval
long delayMillis = 3600000; // Example delay of 60 seconds
long triggerAtMillis = SystemClock.elapsedRealtime() + delayMillis;
alarmManager.setRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerAtMillis,
delayMillis,
pendingIntent
);
if (alarmManager != null) {
long alarmTime = getIntervalMillis(api);
long currentTime = System.currentTimeMillis();
long delay = alarmTime > currentTime ? alarmTime - currentTime : alarmTime - currentTime;
Log.d(getClass().getSimpleName(), String.valueOf(delay)+ " Next Execution");

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pendingIntent);
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pendingIntent);
} else {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pendingIntent);
}
}
}

private void fetchRegistrationPackets(Context context) {
private void syncRegistrationPackets(Context context) {
if(NetworkUtils.isNetworkConnected(context)){
Log.d(getClass().getSimpleName(), "Fetching Packets in main activity");
List<Registration> registrationList = packetService.getAllRegistrations(1,5);
Log.e(getClass().getSimpleName(), "Registration : "+ registrationList);

registrationList = packetService.getRegistrationsByStatus("CREATED");
registrationList.forEach(value->{
Log.d(getClass().getSimpleName(), "Sync Packets in main activity");
Integer batchSize = getBatchSize();
List<Registration> registrationList = packetService.getRegistrationsByStatus(PacketClientStatus.APPROVED.name(), batchSize);
for (Registration value : registrationList) {
try {
Log.d(getClass().getSimpleName(), "Syncing " + value.getPacketId());
packetService.syncRegistration(value.getPacketId());
}catch (Exception e){
} catch (Exception e) {
Log.e(getClass().getSimpleName(), e.getMessage());
}
});
}
}
}

registrationList = packetService.getRegistrationsByStatus("SYNCED");
registrationList.forEach(value->{
private void uploadRegistrationPackets(Context context) {
if(NetworkUtils.isNetworkConnected(context)){
Log.d(getClass().getSimpleName(), "Upload Packets in main activity");
Integer batchSize = getBatchSize();
List<Registration> registrationList = packetService.getRegistrationsByStatus(PacketClientStatus.SYNCED.name(), batchSize);
for (Registration value : registrationList) {
try {
Log.d(getClass().getSimpleName(), "Uploading " + value.getPacketId());
packetService.uploadRegistration(value.getPacketId());
}catch (Exception e){
} catch (Exception e) {
Log.e(getClass().getSimpleName(), e.getMessage());
}
});
}
}
}

private Integer getBatchSize(){
List<GlobalParam> globalParams = globalParamDao.getGlobalParams();
for (GlobalParam value : globalParams) {
if (Objects.equals(value.getId(), "mosip.registration.packet_upload_batch_size")) {
return Integer.parseInt(value.getValue());
}
}
return 4;
}

private long getIntervalMillis(String api){
AtomicLong alarmTime = new AtomicLong(System.currentTimeMillis()+60000);
List<SyncJobDef> syncJobs = syncJobDefRepository.getAllSyncJobDefList();
for (SyncJobDef value : syncJobs) {
if (Objects.equals(value.getApiName(), api)) {
Log.d(getClass().getSimpleName(), String.valueOf(value.getSyncFreq()) + " Cron Expression");
alarmTime.set(CronParserUtil.getNextExecutionTimeInMillis(String.valueOf(value.getSyncFreq())));
}
}
return alarmTime.get();
}

public void initializeAppComponent() {
Expand Down Expand Up @@ -276,9 +319,7 @@ public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
case "masterDataSync":
new SyncActivityService().clickSyncMasterData(result,
auditManagerService, masterDataService);

break;

default:
result.notImplemented();
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import android.util.Log;


public class MyBackgroundService extends Service {
public class SyncBackgroundService extends Service {

private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "ForegroundServiceChannel";
Expand All @@ -26,9 +26,8 @@ public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Notification notification = createNotification();
startForeground(NOTIFICATION_ID, notification);

Log.d(getClass().getSimpleName(), "Fetching Packets in background activity");
Intent broadcastIntent = new Intent("BACKGROUND_TASK_COMPLETE");
Log.d(getClass().getSimpleName(), "Sync Packets in background activity");
Intent broadcastIntent = new Intent("REGISTRATION_PACKET_SYNC");
sendBroadcast(broadcastIntent);
return START_STICKY;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package io.mosip.registration_client;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;


public class UploadBackgroundService extends Service {

private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "ForegroundServiceChannel";

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Notification notification = createNotification();
startForeground(NOTIFICATION_ID, notification);
Log.d(getClass().getSimpleName(), "Upload Packets in background activity");
Intent broadcastIntent = new Intent("REGISTRATION_PACKET_UPLOAD");
sendBroadcast(broadcastIntent);
return START_STICKY;
}

private Notification createNotification() {
// Create a notification for the foreground service
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(this, CHANNEL_ID);
} else {
builder = new Notification.Builder(this);
}

return builder.setContentTitle("Foreground Service")
.setContentText("Running...")
.build();
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
}

@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public interface RegistrationDao {
@Query("SELECT * FROM registration order by cr_dtimes desc")
List<Registration> findAll();

@Query("SELECT * FROM registration where client_status = :status order by cr_dtimes desc ")
List<Registration> findRegistrationByStatus(String status);
@Query("SELECT * FROM registration where client_status = :status order by cr_dtimes desc limit :batchSize")
List<Registration> findRegistrationByStatus(String status, Integer batchSize);

@Query("SELECT * FROM registration where server_status in (:statuses) order by cr_dtimes desc")
List<Registration> findAllByServerStatus(List<String> statuses);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public class Registration {

@Override
public String toString() {
return packetId + " " + (serverStatus == null ? clientStatus : serverStatus);
return packetId + "\n" + (serverStatus == null ? clientStatus : serverStatus);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public List<Registration> getAllRegistrations() {
return this.registrationDao.findAll();
}

public List<Registration> getRegistrationsByStatus(String status) {
return this.registrationDao.findRegistrationByStatus(status);
public List<Registration> getRegistrationsByStatus(String status, Integer batchSize) {
return this.registrationDao.findRegistrationByStatus(status, batchSize);
}

public Registration getRegistration(String packetId) {
Expand All @@ -48,7 +48,7 @@ public Registration insertRegistration(String packetId, String containerPath, St
registration.setFilePath(containerPath);
registration.setRegType(registrationType);
registration.setCenterId(centerId);
registration.setClientStatus(PacketClientStatus.CREATED.name());
registration.setClientStatus(PacketClientStatus.APPROVED.name());
registration.setServerStatus(null);
registration.setCrDtime(System.currentTimeMillis());
registration.setCrBy("110006");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,8 @@ public List<Registration> getAllRegistrations(int page, int pageLimit) {
}

@Override
public List<Registration> getRegistrationsByStatus(String status) {
return this.registrationRepository.getRegistrationsByStatus(status);
public List<Registration> getRegistrationsByStatus(String status, Integer batchSize) {
return this.registrationRepository.getRegistrationsByStatus(status, batchSize);
}

@Override
Expand Down
Loading

0 comments on commit d524132

Please sign in to comment.