Null pointer Exception when using volley - nullpointerexception

i am using volley to fetch data from database.I always get null pointer error. I don't know whats the error. it always executes onErrorResponse() (error.null) and shows this in my logcat
BasicNetwork.performRequest: Unexpected response code 301
here is my java method to fetch data from php file .
private void fetchChatThread() {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages=new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
Toast.makeText(Chat_Rooms.this, messages.getSender_id(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queue
addToRequestQueue(strReq);
}
here is my private that loads data from php to objects
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("id");
String commentText = commentObj.getString("message");
String createddate = commentObj.getString("date");
String commentuser_id = commentObj.getString("user_id_fk");
URL url;
Bitmap image, image1;
try {
url = new URL(Base_URL.BASE_URL_IMAGES + "user_profile_pictures" + commentuser_id + ".jpg");
image1 = BitmapFactory.decodeStream(url.openStream());
image = getResizedBitmap(image1, 50);
} catch (Exception e) {
image = null;
e.printStackTrace();
}
Users user;
user = new Users(commentuser_id, String_username.user_name, image);
Messages message = new Messages();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createddate);
message.setSender_id(commentuser_id);
message.setUser(user);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
#Override
protected void onPostExecute(ArrayList<Messages> messageArrayList) {
Collections.reverse(messageArrayList);
chatroom_adapter.notifyDataSetChanged();
if (chatroom_adapter.getItemCount() > 1) {
rec_chatBubble.getLayoutManager().smoothScrollToPosition(rec_chatBubble, null, chatroom_adapter.getItemCount() - 1);
}
}
}

TRY THIS
private void fetchChatThread(final String count) {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d("response error", response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages = new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
}
}) {
#Override
protected HashMap<String, String> getParams() {
HashMap<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
myparams.put("count", count);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queueok
addToRequestQueue(strReq);
}
AND THIS
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
messageArrayList.clear();
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String Id = commentObj.getString("id");
String Text = commentObj.getString("message");
String date = commentObj.getString("date");
String yuser_id = commentObj.getString("user_id");
Messages message = new Messages();
message.setId(Id);
message.setMessage(Text);
message.setCreatedAt(date);
message.setSender_id(yuser_id);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}

Related

onMessageReceived method is not called, when app is not open

I have implemented FCM in my app, and I need to pass some data from Firebase service to Activity. I have implemented the following code, which works fine, when the app is in foreground(open). When the app is killed or in background, onMessageReceived method is not called, and the launcher activity is loaded while click on the push notification. Also, when the app is open, push message is blank. Kindly advise what I have done wrong. FYI, from backend, they are sending data payload, not notification.
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public FirebaseMessagingService() {
}
private static final String TAG = com.google.firebase.messaging.FirebaseMessagingService.class.getSimpleName();
public static String CHAT_PUSH_NOTIFICATION_INTENT = "chatPushNotificationIntent";
private PreferencesManager preferencesManager;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("push token >>", s);
String reliableIdentifier = FirebaseInstanceId.getInstance().getId();
FCMPreferencesManager pref = FCMPreferencesManager.getInstance(this);
if (pref != null) {
pref.setStringValue(FCMPreferencesManager.FCM_KEY_VALUE, s);
pref.setStringValue(FCMPreferencesManager.DEVICE_ID, reliableIdentifier);
}
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
preferencesManager = PreferencesManager.getInstance(this);
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
Log.e("onMessage received >>", "inside service");
Log.e("userId >>", userId + "");
if (userId > 0) {
Log.e("remote message >>", remoteMessage.getNotification().getBody() + "");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void classApprovedNotification(int jobId, String stage) {
if (!Utils.isAppIsInBackground(getApplicationContext())) {
Intent pushNotification = new Intent(Constants.PUSH_NOTIFICATION_INTENT);
pushNotification.putExtra("jobId", jobId);
pushNotification.putExtra("stage", stage);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
private void handleDataMessage(JSONObject json) {
try {
Log.e("total json >> ", json.toString());
JSONObject data = json.optJSONObject("data");
Log.e("data >> ", data.toString());
String title = data.optString("title");
String message = data.optString("message");
Log.e("title >>", title);
Log.e("message >>", message);
localNotification(data, title, message, false);
} catch (Exception e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
}
}
private void localNotification(JSONObject data, String title, String message, boolean isSendBird) {
int type = 0, groupId = 0, classId = 0, jobId = 0;
String stage = "";
int notificationId = (int) System.currentTimeMillis();
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
String className = "", fileName = "";
if (data != null) {
jobId = data.optInt("job_id");
stage = data.optString("stage", "");
}
Log.e("jobId in service >>", jobId + "");
Log.e("stage in service >>", stage);
Intent intent = new Intent(FirebaseMessagingService.this, VendorHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("jobId", jobId);
intent.putExtra("stage","stage");
int requestID = (int) System.currentTimeMillis();
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
requestID,
intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
String channelId = "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.fyxt_logo)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);*/
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
try {
PowerManager.WakeLock screenLock = null;
if ((getSystemService(POWER_SERVICE)) != null) {
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "OOTUSER:WAKE");
screenLock.acquire(10 * 60 * 1000L /*10 minutes*/);
screenLock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
classApprovedNotification(jobId, stage);
}
}
In my Activity, I have the following code.
private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
jobIdFromNotification = intent.getIntExtra("jobId", 0);
stageFromNotification = intent.getStringExtra("stage");
Log.e("jobIdFromNotification >>", jobIdFromNotification + "");
Log.e("stageFromNotification >>", stageFromNotification);
prefManager.setIntValue(PreferencesManager.JOB_ID_IN_PREF, jobIdFromNotification);
prefManager.setStringValue(PreferencesManager.JOB_STAGE_IN_PREF, stageFromNotification);
classApprovedViewUpdate();
}
};
private void classApprovedViewUpdate() {
if (jobIdFromNotification > 0) {
fragmentInteractionCallback = (BaseFragment.FragmentInteractionCallback) this;
Log.e("inside push receiver update ", "sfs");
if (stageFromNotification.trim().equalsIgnoreCase(Constants.STAGE_TICKET_APPROVAL)) {
sendActionToActivity(ACTION_CREATE_MAINTENANCE_REQUEST, currentTab, true, fragmentInteractionCallback);
}
}
}
Edit:
data payload:
{
"data": {
"type": 0,
"job_id": 123,
"stage": "STAGE_TICKET_APPROVAL",
}

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

Google Play Sign in Failure Api Exception 4

Im trying to integrate google sign in and took the code from another project that it works on, but for the new app it goes thru the log in but the dialog to allow doesnt show up and instead I get sign in failure with Api Exception 4.
Here is all the applicable code:
//Create the client used to sign in to Google services
mGoogleSignInClient = GoogleSignIn.getClient(this,
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(getString(R.string.client_id))
.requestEmail()
.build());
private void signInSilently(){
Log.d(TAG, "signInSilently()");
mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInSilently(): success");
onConnected(task.getResult());
} else {
Log.d(TAG, "signInSilently(): failure", task.getException());
onDisconnected();
}
}
});
}
private void startSignInIntent() {
startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
onConnected(account);
} catch (ApiException apiException) {
String message = apiException.getMessage();
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error);
}
onDisconnected();
new AlertDialog.Builder(this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show();
}
}
}
private void onDisconnected() {
Log.d(TAG, "onDisconnected()");
mPlayersClient = null;
// Show sign-in button on main menu
if(game.user != null) {
game.user.setDisplayName(null);
game.user.setPlayerID(null);
}
}
private void onConnected(final GoogleSignInAccount googleSignInAccount) {
Log.d(TAG, "onConnected(): connected to Google APIs");
GamesClient gamesClient = Games.getGamesClient(AndroidLauncher.this, googleSignInAccount);
View view = ((AndroidGraphics) Gdx.graphics).getView();
gamesClient.setViewForPopups(view);
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);
// Set the greeting appropriately on main menu
mPlayersClient.getCurrentPlayer()
.addOnCompleteListener(new OnCompleteListener<Player>() {
#Override
public void onComplete(#NonNull Task<Player> task) {
String displayName;
if (task.isSuccessful()) {
user = new User();
user.setDisplayName(task.getResult().getDisplayName());
user.setPlayerID(task.getResult().getPlayerId());
game.user = user;
firebaseAuthWithPlayGames(googleSignInAccount);
} else {
Exception e = task.getException();
handleException(e, getString(R.string.players_exception));
displayName = "???";
}
}
});
}
private void handleException(Exception e, String details) {
int status = 0;
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
status = apiException.getStatusCode();
}
String message = getString(R.string.status_exception_error, details, status, e);
new AlertDialog.Builder(AndroidLauncher.this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show();
}

Dropbox Java Api Upload File

How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}

can not run multiple jobs with quartz

Hi i m trying to run two jobs using batch framework.
My problem is SimpleJobLauncher is running only one job which is last in the jobs list.
Here what i am doing:
I have two jobs in my database along with the steps for the jobs.
I read the job data from database and process it as following
public class BatchJobScheduler {
private static Log sLog = LogFactory.getLog(BatchJobScheduler.class);
private ApplicationContext ac;
private DataSourceTransactionManager mTransactionManager;
private SimpleJobLauncher mJobLauncher;
private JobRepository mJobRepository;
private SimpleStepFactoryBean stepFactory;
private MapJobRegistry mapJobRegistry;
private JobDetailBean jobDetail;
private CronTriggerBean cronTrigger;
private SimpleJob job;
private SchedulerFactoryBean schedulerFactory;
private static String mDriverClass;
private static String mConnectionUrl;
private static String mUser;
private static String mPassword;
public static JobMetaDataFeeder metadataFeeder;
static {
try {
loadProperties();
metadataFeeder = new JobMetaDataFeeder();
metadataFeeder.configureDataSource(mDriverClass, mConnectionUrl,
mUser, mPassword);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (SQLException e) {
} catch (ClassNotFoundException e) {
}
}
private static void loadProperties() throws FileNotFoundException,
IOException {
Properties properties = new Properties();
InputStream is;
if (BatchJobScheduler.class.getClassLoader() != null) {
is = BatchJobScheduler.class.getClassLoader().getResourceAsStream(
"batch.properties");
} else {
is = System.class.getClassLoader().getResourceAsStream(
"batch.properties");
}
properties.load(is);
mDriverClass = properties.getProperty("batch.jdbc.driver");
mConnectionUrl = properties.getProperty("batch.jdbc.url");
mUser = properties.getProperty("batch.jdbc.user");
mPassword = properties.getProperty("batch.jdbc.password");
}
public void start(WebApplicationContext wac) throws Exception {
try {
ac = new FileSystemXmlApplicationContext("batch-spring.xml");
mTransactionManager = (DataSourceTransactionManager) ac
.getBean("mTransactionManager");
mJobLauncher = (SimpleJobLauncher) ac.getBean("mJobLauncher");
mJobRepository = (JobRepository) ac.getBean("mRepositoryFactory");
mJobLauncher.afterPropertiesSet();
List<JobMetadata> jobsMetaData = getJobsData(mDriverClass,
mConnectionUrl, mUser, mPassword, null);
createAndRunScheduler(jobsMetaData);
} catch (Exception e) {
e.printStackTrace();
sLog.error("Exception while starting job", e);
}
}
#SuppressWarnings("unchecked")
public List<CronTriggerBean> getJobTriggers(List<JobMetadata> jobsMetaData)
throws Exception {
List<CronTriggerBean> triggers = new ArrayList<CronTriggerBean>();
for (JobMetadata jobMetadata : jobsMetaData) {
job = (SimpleJob) ac.getBean("job");
job.setName(jobMetadata.getJobName());
ArrayList<Step> steps = new ArrayList<Step>();
for (StepMetadata stepMetadata : jobMetadata.getSteps()) {
// System.err.println(ac.getBean("stepFactory").getClass());
stepFactory = new SimpleStepFactoryBean<String, Object>();
stepFactory.setTransactionManager(mTransactionManager);
stepFactory.setJobRepository(mJobRepository);
stepFactory.setCommitInterval(stepMetadata.getCommitInterval());
stepFactory.setStartLimit(stepMetadata.getStartLimit());
T5CItemReader itemReader = (T5CItemReader) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepReaderClass()));
itemReader
.setItems(getItemList(jobMetadata.getJobParameters()));
stepFactory.setItemReader(itemReader);
stepFactory.setItemProcessor((ItemProcessor) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepProcessorClass())));
stepFactory.setItemWriter((ItemWriter) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepWriterClass())));
stepFactory.setBeanName(stepMetadata.getStepName());
steps.add((Step) stepFactory.getObject());
}
job.setSteps(steps);
ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
mapJobRegistry = (MapJobRegistry) ac.getBean("jobRegistry");
mapJobRegistry.register(jobFactory);
jobDetail = (JobDetailBean) ac.getBean("jobDetail");
jobDetail.setJobClass(Class.forName(jobMetadata.getMJoblauncher()));
jobDetail.setGroup(jobMetadata.getJobGroupName());
jobDetail.setName(jobMetadata.getJobName());
Map<String, Object> jobDataMap = new HashMap<String, Object>();
jobDataMap.put("jobName", jobMetadata.getJobName());
jobDataMap.put("jobLocator", mapJobRegistry);
jobDataMap.put("jobLauncher", mJobLauncher);
jobDataMap.put("timestamp", new Date());
// jobDataMap.put("jobParams", jobMetadata.getJobParameters());
jobDetail.setJobDataAsMap(jobDataMap);
jobDetail.afterPropertiesSet();
cronTrigger = (CronTriggerBean) ac.getBean("cronTrigger");
cronTrigger.setJobDetail(jobDetail);
cronTrigger.setJobName(jobMetadata.getJobName());
cronTrigger.setJobGroup(jobMetadata.getJobGroupName());
cronTrigger.setCronExpression(jobMetadata.getCronExpression());
triggers.add(cronTrigger);
}
return triggers;
}
private void createAndRunScheduler(List<JobMetadata> jobsMetaData)
throws Exception {
// System.err.println(ac.getBean("schedulerFactory").getClass());
schedulerFactory = new SchedulerFactoryBean();
List<CronTriggerBean> triggerList = getJobTriggers(jobsMetaData);
Trigger[] triggers = new Trigger[triggerList.size()];
int triggerCount = 0;
for (CronTriggerBean trigger : triggerList) {
triggers[triggerCount] = trigger;
triggerCount++;
}
schedulerFactory.setTriggers(triggers);
schedulerFactory.afterPropertiesSet();
}
private List<JobMetadata> getJobsData(String driverClass,
String connectionURL, String user, String password, String query)
throws SQLException, ClassNotFoundException {
metadataFeeder.createJobMetadata(query);
return metadataFeeder.getJobsMetadata();
}
private List<String> getItemList(String jobParameterString) {
List<String> itemList = new ArrayList<String>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
itemList.add(mapKeyValue[0] + ":" + mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return itemList;
}
private Map<String, Object> getParameterMap(String jobParameterString) {
Map<String, Object> parameterMap = new HashMap<String, Object>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
parameterMap.put(mapKeyValue[0], mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return parameterMap;
}
}
public class MailJobLauncher extends QuartzJobBean {
/**
* Special key in job data map for the name of a job to run.
*/
static final String JOB_NAME = "jobName";
private static Log sLog = LogFactory.getLog(MailJobLauncher.class);
private JobLocator mJobLocator;
private JobLauncher mJobLauncher;
/**
* Public setter for the {#link JobLocator}.
*
* #param jobLocator
* the {#link JobLocator} to set
*/
public void setJobLocator(JobLocator jobLocator) {
this.mJobLocator = jobLocator;
}
/**
* Public setter for the {#link JobLauncher}.
*
* #param jobLauncher
* the {#link JobLauncher} to set
*/
public void setJobLauncher(JobLauncher jobLauncher) {
this.mJobLauncher = jobLauncher;
}
#Override
#SuppressWarnings("unchecked")
protected void executeInternal(JobExecutionContext context) {
Map<String, Object> jobDataMap = context.getMergedJobDataMap();
executeRecursive(jobDataMap);
}
private void executeRecursive(Map<String, Object> jobDataMap) {
String jobName = (String) jobDataMap.get(JOB_NAME);
JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);
sLog.info("Quartz trigger firing with Spring Batch jobName=" + jobName
+ jobDataMap + jobParameters);
try {
mJobLauncher.run(mJobLocator.getJob(jobName), jobParameters);
} catch (JobInstanceAlreadyCompleteException e) {
jobDataMap.remove("timestamp");
jobDataMap.put("timestamp", new Date());
executeRecursive(jobDataMap);
} catch (NoSuchJobException e) {
sLog.error("Could not find job.", e);
} catch (JobExecutionException e) {
sLog.error("Could not execute job.", e);
}
}
/*
* Copy parameters that are of the correct type over to {#link
* JobParameters}, ignoring jobName.
* #return a {#link JobParameters} instance
*/
private JobParameters getJobParametersFromJobMap(
Map<String, Object> jobDataMap) {
JobParametersBuilder builder = new JobParametersBuilder();
for (Entry<String, Object> entry : jobDataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String && !key.equals(JOB_NAME)) {
builder.addString(key, (String) value);
} else if (value instanceof Float || value instanceof Double) {
builder.addDouble(key, ((Number) value).doubleValue());
} else if (value instanceof Integer || value instanceof Long) {
builder.addLong(key, ((Number) value).longValue());
} else if (value instanceof Date) {
builder.addDate(key, (Date) value);
} else {
sLog
.debug("JobDataMap contains values which are not job parameters (ignoring).");
}
}
return builder.toJobParameters();
}
}
I couldnt figure it out why launcher is ignoring all other jobs please help me.
Regards
Make sure these properties are set:
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=3
org.quartz.threadPool.threadPriority=5
This will allow a few jobs to run at the same time. Adjust the settings as needed.