How to publish multiple event using EventQueues.publish in zk - java

Hope your problem is resolved, but my problem is still there
and I thought that you can help me to get out of this problem.
actually I had multiple events to publish one by one as per user
selection for eg: user select Season, Service, DateFrom and
DateTo and then clicks on the refresh button.
When the refresh button is clicked I had used the above logic to
get all the datas using the below mentioned code
public void onClick$ref(Event event){
if(lbox_service.getSelectedIndex() != 0 || lbox_season.getSelectedIndex() != 0)
{
if(lbox_service.getSelectedIndex() == 0)
{
setService_id("0");
}
else
{
setService_id(lbox_service.getSelectedItem().getValue().toString());
}
if(lbox_season.getSelectedIndex() == 0)
{
setSeason_id("0");
}
else
{
setSeason_id(lbox_season.getSelectedItem().getValue().toString());
}
System.out.println("Service Index 11 : "+ lbox_service.getSelectedIndex());
System.out.println("Season Index 11 : "+ lbox_season.getSelectedIndex());
EventQueue evtQ = EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true);
//evtQ.publish(new Event("service_id", self, lbox_service.getSelectedItem().getValue().toString()));
//evtQ.publish(new Event("season_id", self, lbox_season.getSelectedItem().getValue().toString()));
evtQ.publish(new Event("service_id", self, getService_id()));
evtQ.publish(new Event("season_id", self, getSeason_id()));
//evtQ.publish(new Event("onClickRef", null, lbox_service.getSelectedItem().getValue().toString()));
//evtQ.publish(new Event("onClickRef", null, lbox_season.getSelectedItem().getValue().toString()));
/*.publish(new Event("onClickRef", null, lbox_service.getSelectedItem().getValue().toString()));
EventQueues.lookup("myEventQu", EventQueues.DESKTOP, true).publish(new Event(
"onClickRef", null, lbox_season.getSelectedItem().getValue().toString()));*/
}
else
{
setService_id("0");
setSeason_id("0");
EventQueue evtQ = EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true);
evtQ.publish(new Event("service_id", self, getService_id()));
evtQ.publish(new Event("season_id", self, getSeason_id()));
System.out.println("Service Index : "+ lbox_service.getSelectedIndex());
System.out.println("Season Index : "+ lbox_season.getSelectedIndex());
}
}
now i had publish all my value and after that my new Controller
run that will subscribe those published values. using the
below code
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
EventQueues.lookup("myEventQueue", EventQueues.APPLICATION, true).subscribe(new EventListener() {
public void onEvent(Event event) throws Exception {
/*String service = (String) event.getData();
logger.info("Servive $$$$$$$$$ " + service);
//String season = (String) event.getData();
//logger.info("Season $$$$$$$$$ " + season); */
if("service_id".equals(event.getName())) {
setService_id((String) event.getData());
baseController.setFilter_bar(true);
System.out.println("Service Id :" +event.getData());
}
else if("season_id".equals(event.getName())) {
setSeason_id((String) event.getData());
baseController.setFilter_bar(true);
System.out.println("Season Id :" +event.getData());
}
/*setService_id((String) event.getData());
setSeason_id((String) event.getData());*/
/*if("season_id".equals(event.getName())){
setSeason_id((String) event.getData());
}else
{
setSeason_id("0");
}*/
System.out.println("Filter bar :" +baseController.isFilter_bar());
if(baseController.isFilter_bar() == true)
{
String dateFrom = "";
String dateTo = "";
String order = "2";
List TDRetailers = verificationStoreHibernateDao.getTraditionalRetailers(
getService_id(), getSeason_id(), dateFrom, dateTo, order);
//VerificationStoreHibernateDao storeHibernateDao = new VerificationStoreHibernateDao();
//List TDRetailers = this.verificationStoreHibernateDao.getTraditionalRetailers(service_id);
//ListModel listModel = this.retailers.getModel();
ListModelList listModelList = (ListModelList) retailer.getModel();
listModelList.clear();
listModelList.addAll(TDRetailers);
baseController.setFilter_bar(true);
}
}
});
}
but actully my problem is with running the query and with
getting those published values. Based on them I will be able to
run my Traditional getTraditionalRetailers queries.
My problem is
how to publish multiple events values. Is it the right way
that I had done.
as I had done separate publish, everytime
I publish new value The query runs, the result is that i had
mutiple time query execution. for example If i will publish two
values the queries run's for the two times and if I publish
three values the query executes for three time.
I don't know what is their problem. Help me to solve my error.

The event object passed through EventQueue is where you put your payload there. You can just define an aggregate Event class and collect information and publish them in a whole.
If you can publish all information in a whole(using an aggregate Event), this is solved automatically.

Related

Discord JDA - getMembers() not working, returns 0 anyway

This is how my code is looking :
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
String channelId = event.getChannelJoined().getId();
if (channelId.equals("904375329764814870")) {
Member member = event.getMember();
String memberName = event.getMember().getEffectiveName();
Category category = event.getGuild().getCategoryById("904364634507706468");
event.getGuild().createVoiceChannel("Coaching " + memberName).setParent(category).complete();
List<VoiceChannel> channelList = event.getGuild().getVoiceChannelsByName("Coaching " + memberName, true);
VoiceChannel channel = channelList.get(0);
event.getGuild().moveVoiceMember(member, channel).queue();
while (true){
event.getGuild().getTextChannelById("904364671467929610").sendMessage(
"Number of people currently on the channel : " + channel.getMembers().size()
).queue();
wait(3000);
}
My goal is to get the number of people currently inside the channel.
I thought the getMembers() method was the good method, but it's not working
I use the infinite while to see if the channel.getMembers().size() changes when i join/leave the channel but it still return 0.
How can i fix this ? And get the correct amount of people inside the channel as return.
The final goal of my code is to delete the channel when he's empty of user
This can be achieved by just checking the member count in the GuildVoiceUpdateEvent:
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
if (channel.getName().startsWith("Coaching ")) { // check if name matches the desired name
if (channel.getMembers().isEmpty()) { // check if channel is empty
channel.delete().queue(); // delete channel
}
}
}

Java continue statement not allowed in anonymous inner class

I am threading a time consuming for-loop and executing them inside N number of threads. A continue statement is throwing error
Getting the error "Continue cannot be used outside of a loop"
for (final Message m : messagelistholder.getMessage()) {
Callable<Void> tasksToExecute = new Callable<Void>() {
public Void call() {
if (guidanceonly1 == true && !QuoteUtil.isECPQuote(list.get(0))) {
String msg = "Message From " + m.getSource() + " when retrieving Guidance values: "
+ m.getDescription();
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()}, msg);
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
} else if ("Error".equalsIgnoreCase(m.getSeverity())) {
if (m.getCode().indexOf("_NF") > 0) {
continue; // price not found due to private sku
}
if ("Eclipse".equalsIgnoreCase(m.getSource())) {
String msg1 = "Please check Sold To customer data. ";
String lcladdStatusMessages1 = CommonUtil
.getLoclizedMsg("PRCE_LNE_ITM_PLS_CHK_SLDTO_CUST_DTA", null, msg1);
String msg2 = "Discount information may not be returned from Optimus due to "
+ m.getSeverity() + " From " + m.getSource() + " " + m.getDescription();
String lcladdStatusMessages2 = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_DSCNT_INFO_MNT_RTRND_FRM_OPTMS_DUETO_FRM",
new String[]{m.getSeverity(), m.getSource(), m.getDescription()}, msg2);
list.get(0).addStatusMessages(m.getSeverity(),
(m.getDescription().contains("MDCP") ? lcladdStatusMessages1 : "")
+ lcladdStatusMessages2);
} else {
if (response1.getItems() == null) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg("PRCE_LNE_ITM_OPTMS_ERR",
new String[]{m.getSource(), m.getDescription()}, m.getDescription());
list.get(0).addStatusMessages("Error", lcladdStatusMessages);
list.get(0).setOptimusError(true);
} else {
if (!QuoteUtil.isECPQuote(list.get(0))) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()},
"Message From " + m.getSource() + " " + m.getDescription());
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
list.get(0).setOptimusError(true);
}
}
}
}
if (list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER) != null) {
list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER).setFlgVl(null);
}
if (m.getCode() != null) {
String pricingServiceMsgCode = m.getCode();
String pricingServiceSeverity = m.getSeverity();
Map<Integer, AutoEscalationScenario> categoryMap;
if (StringUtils.equals("ERROR", pricingServiceSeverity)) {
categoryMap = getScenario("SEVERITY", globalAccount1, null, true, null);
if (categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
if (partnerExclusivityAutoEscalation1) {
categoryMap = getScenario(pricingServiceMsgCode, globalAccount1, null, true, null);
if (categoryMap != null && categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
}
return null;
}
};
runnableTasks.add(tasksToExecute);
}
Can someone help me to skip the particular loop for the speicified condition but without using continue statement since it throws error.
What's happening is that you are actually calling continue outside of a loop because the call() function itself does not have a for loop, so it doesn't matter if are only calling call() from a loop.
What can you do to fix this is making the call function to return a boolean and replacing the continues with return true and return false if no return true has been reached.
Then replace the:
call()
on the loop(s) for
if(call()) continue
So the I'm not saying I fully understand you code, but it appears that you are using continue to break out of that thread. On a normal multi-threaded application, it looks like you are launching multiple threads from one one loop. The continue call is inside the new thread, not the loop. As soon as you start writing the call() method, you leave the loop to run it. Looking at the code, I would try replacing continue with return. Normally I would try running it myself before I suggest it, but without the rest of the code I cannot verify that it works.

Database insertion synchronization

I have a java code that generates a request number based on the data received from database, and then updates the database for newly generated
synchronized (this.getClass()) {
counter++;
System.out.println(counter);
System.out.println("start " + System.identityHashCode(this));
certRequest
.setRequestNbr(generateRequestNumber(certInsuranceRequestAddRq
.getAccountInfo().getAccountNumberId()));
System.out.println("outside funcvtion"+certRequest.getRequestNbr());
reqId = Utils.getUniqueId();
certRequest.setRequestId(reqId);
System.out.println(reqId);
ItemIdInfo itemIdInfo = new ItemIdInfo();
itemIdInfo.setInsurerId(certRequest.getRequestId());
certRequest.setItemIdInfo(itemIdInfo);
dao.insert(certRequest);
addAccountRel();
counter++;
System.out.println(counter);
System.out.println("end");
}
the output for System.out.println() statements is `
1
start 27907101
com.csc.exceed.certificate.domain.CertRequest#a042cb
inside function request number66
outside funcvtion66
AF88172D-C8B0-4DCD-9AC6-12296EF8728D
2
end
3
start 21695531
com.csc.exceed.certificate.domain.CertRequest#f98690
inside function request number66
outside funcvtion66
F3200106-6033-4AEC-8DC3-B23FCD3CA380
4
end
In my case I get a call from two threads for this code.
If you observe both the threads run independently. However the data for request number is same in both the cases.
is it possible that before the database updation for first thread completes the second thread starts execution.
`
the code for generateRequestNumber() is as follows:
public String generateRequestNumber(String accNumber) throws Exception {
String requestNumber = null;
if (accNumber != null) {
String SQL_QUERY = "select CERTREQUEST.requestNbr from CertRequest as CERTREQUEST, "
+ "CertActObjRel as certActObjRel where certActObjRel.certificateObjkeyId=CERTREQUEST.requestId "
+ " and certActObjRel.certObjTypeCd=:certObjTypeCd "
+ " and certActObjRel.certAccountId=:accNumber ";
String[] parameterNames = { "certObjTypeCd", "accNumber" };
Object[] parameterVaues = new Object[] {
Constants.REQUEST_RELATION_CODE, accNumber };
List<?> resultSet = dao.executeNamedQuery(SQL_QUERY,
parameterNames, parameterVaues);
// List<?> resultSet = dao.retrieveTableData(SQL_QUERY);
if (resultSet != null && resultSet.size() > 0) {
requestNumber = (String) resultSet.get(0);
}
int maxRequestNumber = -1;
if (requestNumber != null && requestNumber.length() > 0) {
maxRequestNumber = maxValue(resultSet.toArray());
requestNumber = Integer.toString(maxRequestNumber + 1);
} else {
requestNumber = Integer.toString(1);
}
System.out.println("inside function request number"+requestNumber);
return requestNumber;
}
return null;
}
Databases allow multiple simultaneous connections, so unless you write your code properly you can mess up the data.
Since you only seem to require a unique growing integer, you can easily generate one safely inside the database with for example a sequence (if supported by the database). Databases not supporting sequences usually provide some other way (such as auto increment columns in MySQL).

Storing all ParseFiles for a given ParseUser?

I'm new to Parse and was wondering if there is any way to store all the ParseFiles (in this case images) for a given ParseUser into something like an ArrayList?
Here's my code:
public ArrayList<ParseFile> getFiles() {
ArrayList<ParseFile> files = new ArrayList<ParseFile>();
//mUser is the current ParseUser
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> fileList, ParseException e) {
if (e == null) {
Log.d("FILES", "Retrieved " + fileList.size() + " files");
for(ParseObject ch:fileList) {
image = ch.getParseFile("image");
files.add(image);
#Override
public void done(byte[] arg0, ParseException arg1) {
//nothing to do here
}
});
}
Log.i("TAG", ": " + files.size());
} else {
Log.d("FILES", "Error: " + e.getMessage());
}
}
});
Log.i("DONE", ": " + files.size());
return files;
}
When I'm inside done(), the 3 images I have for this particular user are added and I get an ArrayList of size 3 which is to be expected. When I'm outside of done(), the size of the ArrayList goes back to 0, which I'm assuming is because it's being referenced outside of the query. And sure enough it returns an empty ArrayList (not too shocking).
I feel like this should be an easy solution but I can't seem to figure it out. I've tried to make a static ArrayList variable but that doesn't seem to work either. Any idea on how to return the desired ArrayList?
I believe the problem is that the outside thread still continues before your background process is completed. In other words..
1. query.findInBackground(....);
2. Log.i("DONE" ....);
.. 2. is executed before 1. completes. The whole point of Parse "inBackground" is that it completes actions that your thread is not dependent on. If you need to do something with the List, you should do it in the same thread as the background thread or not do it "inBackground".
Try like this
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
List<ParseObject>imageList=query.find();
try {
Arraylist<ParseFile> files = new Arraylist<ParseFile>files();
ParseFile image;
for(int i =0;i<imageList.size();i++)
{
image = imageList.get(i).getParseFile("image");
files.add(image);
}
}
catch()
{
}

How to retrieve new incoming data by polling and feed it back

Here the method reads the database which has an unique ID with the sequence number which keeps on increasing, since am a beginner in java,can I know how to implement this repetitive polling and check for new incoming message each time.
public void run() {
int seqId = 0;
while(true) {
List<KpiMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingMessages.addAll(list);
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
Thread.sleep(3000);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
//Method which defines polling of the database and also count the number of Queries
public List<KpiMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and SEQ >" + lastSeq + "order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
// return seqId;
return pojoCol;
}
My goal is to Poll the table from the database and also check for new incoming message, which I can find from the Header field SequenceID in table which is unique and keeps on increasing for new entries. Now my problem is
1.Lets say after I poll the first time, it reads all the entries and makes the thread to sleep for 6 seconds, by the mean time how can I get the new incoming data and Poll it again ?
2.Also how to add the new data ,when it does Polling for the second time and pass the new data to another class.
Poller calls fullPoll every 6 secs and passes lastSeq param to it. Initially lastSeq = 0. When Poller gets result list it replaces the lastSeq with max SEQ value. fullPoll retrieves only records with SEQ > lastSeq.
void run() throws Exception {
int seqId = 0;
while(true) {
List<KpiMessage> list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequene();
}
Thread.sleep(6000);
}
}
public List<KAMessage> fullPoll(int lastSeq) throws Exception {
...
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and SEQ > " + lastSeq + " order by SEQ
DESC");
..
}
Here is some code you may use to get working on. I tried to make it pretty flexible using the Observer pattern; this way you can connect multiple "message processors" to the same poller:
public class MessageRetriever implements Runnable {
private int lastID;
private List<MessageListener> listeners;
...
public void addMessageListener(MessageListener listener) {
this.listeners.add(listener)
}
public void removeMessageListener(MessageListener listener) {
this.listeners.remove(listener)
}
public void run() {
//code to repeat the polling process given some time interval
}
private void pollMessages() {
if (this.lastID == 0)
this.fullPoll()
else
this.partialPoll()
}
private void fullPoll() {
//your full poll code
//assuming they are ordered by ID and it haves the ID field - you should
//replace this code according to your structure
this.lastID = pojoCol.get(pojoCol.length() - 1).getID()
this.fireInitialMessagesSignal(pojoCol)
}
private void fireInitialMessagesSignal(List<KAMessage> messages) {
for (MessageListener listener : this.listeners)
listener.initialMessages(messages)
}
private void partialPoll() {
//code to retrieve messages *past* the lastID. You could do this by
//adding an extra condition on your where sentence e.g
//select * from msg_new_to_bde where ACTION = 804 AND SEQ > lastID order by SEQ DESC
//the same as before
this.lastID = pojoCol.get(pojoCol.length() - 1).getID()
this.fireNewMessagesListener(pojoCol)
}
private void fireNewMessagesListener(List<KAMessage> messages) {
for (MessageListener listener : this.listeners)
listener.newMessages(messages)
}
}
And the interface
public interface MessageListener {
public void initialMessages(List<KAMessage> messages);
public void newMessages(List<KAMessage> messages)
}
Basically, using this approach, the retriever is a runnable (can be executed on it's own thread) and takes care of the whole process: does an initial poll and continues doing "partial" polls on given intervals.
Different events fire different signals, sending the affected messages to the registered listeners, and those process the messages as they want.

Categories

Resources