1.Problem on emulator:
I am launching my midlet app at first time is to store some data and then I am restarting it at second time is to read the stored data. It is working well in first two cases without any exception.
However I am restarting it second time on the same way then It gives exception: "Uncaught exception java/lang/NumberFormatException:" it is processing only char and total data is less than 64 kb.
2.Problem on real device:
RMS is not working at all. I don't know if I need to give a permission for the handset (nokia n95).
Thanks.
In app, it is only storing charity companies into rms according to a selected country. So if a country is already selected, it must skip country list and then display company list in every restart.
In below code, rms_Check() method is to check the data in order to open country or company list frame.
public class X {
private static RecordStore rs =null;
private static Vector rms_Vector = new Vector();
static final String REC_STORE ="db_1";
public X() {
}
public void openRecStore(){
try {
rs = RecordStore.openRecordStore(REC_STORE, true);
System.out.println("open record store");
} catch (Exception e)
{
db(e.toString()+" in openRecStore");
}
}
public void closeRecStore(){
try {
rs.closeRecordStore();
} catch (Exception e) {
db(e.toString()+" in closeRecStore");
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores()!=null){
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString()+" in deleteRecStore");
}
}
}
public void writeRecord(String str) throws UnsupportedEncodingException
{
byte[] rec = str.getBytes("UTF-8");
try {
rs.addRecord(rec, 0, rec.length);
System.out.println("write record store");
} catch (Exception e) {
db(e.toString()+" in writeRecord");
}
}
public void readRecord()
{
try {
// Intentionally it is too small to test code
byte[] m_enc = new byte[5];
byte[] recData = new String(m_enc).getBytes("UTF-8");
int len;
for(int i =1; i<= rs.getNumRecords(); i++){
if(rs.getRecordSize(i)> recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
System.out.println("Record #"+i+":"+new String(recData, 0, len));
System.out.println("------------------------");
rms_Vector.addElement(new String(recData, 0, len));
}
} catch (Exception e) {
db(e.toString() +" in readStore");
}
}
private void db(String str)
{
System.out.println("Msg:"+str);
}
public Vector rms_Array(){
return this.rms_Vector;
}
public boolean rms_Check(){
if(this.rms_Vector.size()>0){
System.out.print("rms_check: true");
// if true it will display company list every time
return true;
}else{
System.out.print("rms_check: false");
//if false it will display country list then company list
return false;
}
}
}
Use this
private RecordStore rs = null; // Record store
public String REC_STORE = "RSM name"; // Name of record store
public int record_max=0;
public void openRecStore(){
try{
rs = RecordStore.openRecordStore(REC_STORE, true );
}catch (Exception e){}
}
public void closeRecStore(){
try{
rs.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(REC_STORE);
}catch (Exception e){}
}
}
public void writeRecord(String str){
byte[] rec = str.getBytes();
try{
rs.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void readRecords(){
try{
byte[] recData = new byte[5];
int len;
record_max=rs.getNumRecords();
for(int i = 1; i <= record_max; i++){
if(rs.getRecordSize(i) > recData.length){
recData = new byte[rs.getRecordSize(i)];
}
len = rs.getRecord(i, recData, 0);
file_name[i]=new String(recData, 0, len);
}
}catch (Exception e){}
}
you have file_name[] array of save data
for load actin commad use :
openRecStore();
readRecords();
for(int j=1;j<=record_max;j++ ) {
System.out.println("Record " + j + " : " + file_name[j]);
}
closeRecStore();
and save this :
openRecStore();
writeRecord(textField.getString());
closeRecStore();
Related
I'm trying to create an object in one class then use that object in another class but each time I try to use it it just says the value is null
Customer cus = new Customer();
ServerSocket s = null;
public AddCustomer() {
}
public void getCustomerDetail() {
String back = " ";
{
try {
s = new ServerSocket(5433);
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
System.exit(0);
}
while (back.equals(" ")) {
try {
Socket s1 = s.accept();
System.out.println("Connection established at port 5433");
InputStream is = s1.getInputStream();
ObjectInputStream dis = new ObjectInputStream(is);
System.out.println("Getting data...");
cus = (Customer)dis.readObject();
System.out.println(cus.toString());
System.out.println(cus.getName());
dis.close();
s1.close();
System.out.println("Connection closed.");
} catch (ConnectException connExcep) {
System.out.println("1Error: " + connExcep.getMessage());
} catch (IOException ioExcep) {
System.out.println("2Error: " + ioExcep.getMessage());
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
}
}
}
public void addCustomerToDB() {
System.out.println("start ");
Connection connection = null;
Statement statement = null;
int check = 1;
System.out.println(cus.getName()+"dadawd");
}
When I print out the value of cus.getName() it just gives me null but when I print it out in getCustomerDetail it gives me the correct value.
dis.readObject returns an object with the values in it.
Depends on what you are doing in the getName function and in the constructor.
Maybe in getCustomerDetails() you are setting the values in the input stream. But the default constructor doesn't do anything with name variable.
It looks like the issue of packaging. Try below code.
public class AddCustomer {
public static void main(String[] args) {
new AddCustomer().getCustomerDetail();
}
Customer cus = new Customer();
public void getCustomerDetail() {
String back = " ";
{
while (back.equals(" ")) {
try {
System.out.println(cus.toString());
System.out.println(cus.getName());
System.out.println("Connection closed.");
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
break;
}
}
}
public void addCustomerToDB() {
System.out.println(cus.getName()+"dadawd");
}
}
class Customer{
private String name="ABC";
String getName() {
return name;
}
}
We found here one issue you have to create "Customer cus = new Customer();" this object under main() function like as
public class AddCustomer {
public static void main(String[] args) {
Customer cus = new Customer();
new AddCustomer().getCustomerDetail();
}
how can I search a data using binary search? When if statement begins, the program goes to IOException block. It seems that it doesn't try to read the file.
public void busquedaDicotomica1(String clave)
{
String lectura1=null, lectura2=null ;
long posicion;
long tamaño;
long midValue;
boolean valido = true;
try
{
rafObj = new RandomAccessFile("indice1.ind","r");
tamaño = rafObj.length();
midValue = tamaño/2;
rafObj.seek(midValue);
if(clave.equalsIgnoreCase(rafObj.readUTF()))
{
System.out.println("ok");
}
else
{
System.out.println("no");
}
}
catch(EOFException eoe)
{}
catch(FileNotFoundException nfe)
{
VentanaPrincipal.setErrorText(dialogo);
}
catch(IOException ioe)
{
VentanaPrincipal.setErrorText(ioe.getMessage());
}
}
}
I have created a game in Android. I have written a class for input/ouput with prefer install location external. I want to make some basic questions. First of all the file I use is a .txt (I know that its not the best way to save your data but I use it for testing). The strange part is that when the the game is over it should automatically save the user highscores but it does not, so when I close the app and restart it the highscores have disappeared. I would also like to learn what the prefered file type for saving settings/highscores/coins etc (hopefully secured) is. Lastly I debug the game using a Nexus 5 whitch does not have external storage (it should be stored locally though). This is my code, thanks in advance :).
public class AndroidFileIO implements FileIO {
Context context;
AssetManager assets;
String externalStoragePath;
public AndroidFileIO(Context context) {
this.context = context;
this.assets = context.getAssets();
this.externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator;
}
public InputStream readAsset(String fileName) throws IOException {
return assets.open(fileName);
}
public InputStream readFile(String fileName) throws IOException {
return new FileInputStream(externalStoragePath + fileName);
}
public OutputStream writeFile(String fileName) throws IOException {
return new FileOutputStream(externalStoragePath + fileName);
}
public SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
my game class has this method
public FileIO getFileIO() {
return fileIO;
}
this is the way i load the file
Settings.load(game.getFileIO());
and finaly my save/load methods of the settings class
public static void load(FileIO files) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
files.readFile("mrnom.txt")));
soundEnabled = Boolean.parseBoolean(in.readLine());
for (int i = 0; i < 5; i++) {
highscores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
// :( It's ok we have defaults
} catch (NumberFormatException e) {
// :/ It's ok, defaults save our day
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile("mrnom.txt")));
out.write(Boolean.toString(soundEnabled));
for (int i = 0; i < 5; i++) {
out.write(Integer.toString(highscores[i]));
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
Here save is called
private void updateGameOver(List<TouchEvent> touchEvents) {
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
if(event.x >= 128 && event.x <= 192 &&
event.y >= 200 && event.y <= 264) {
if(Settings.soundEnabled)
Assets.click.play(1);
//debug begin
FileIO fileIO = game.getFileIO();
Settings.save(fileIO);
//debug end
game.setScreen(new MainMenuScreen(game));
return;
}
}
}
}
Your issue is in the save method when you write the strings to the out reference. You are not saving a value per line, but are later reading a value per line in your load method. With the current code you save the following in your mrnom.txt file: true10203040 instead of true\n10\n20\n30\n40.
To fix this, one way is to change:
out.write(Boolean.toString(soundEnabled));
to
out.write(Boolean.toString(soundEnabled) + "\n");
AND
out.write(Integer.toString(highscores[i]));
to
out.write(Integer.toString(highscores[i]) + "\n");
I have to retrieve offline messages from Google Talk for a particular client (friend/ XMPP Client) with whom I have had a conversationn with.
Additionally, I want to retrieve the chat history.
Right now, I am using a Hash Map to keep track of the conversation and have no means of having the offline messages.
I have made an XMPP connection to "talk.google.com". I am currently able to send messages to the client via my console. I have implemented the Message Listener Interface and hence can receive messages in my console itself.
I have another implementaion(made use of OfflineMessageManager) where I try to extract the offline messages headers as a start, unfortunately, it fails with Null Exception.
I have used smack-tcp version 4.0.3 and smackx 3.1.0.
Please find below what I have tried till now...
Working Implementation:
public class StartChatImpl implements startChat, MessageListener {
static XMPPConnection myXMPPConnection;
static ArrayList<String> myFriends = new ArrayList<String>();
ArrayList<Msg> messages;
HashMap<String,ArrayList> conversation = new HashMap<String, ArrayList>();
OfflineMessageManager offlineMessages;
#Override
public void engageChat(ChatRequest chatRequest) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
myXMPPConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
myXMPPConnection.connect();
System.out.println("Logging you in...");
myXMPPConnection.login(chatRequest.getUsername(),chatRequest.getPassword());
Presence pres = new Presence(Presence.Type.unavailable);
myXMPPConnection.sendPacket(pres);
offlineMessages = new OfflineMessageManager(myXMPPConnection);
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send (String message, String to) throws XMPPException
{
Chat chat = ChatManager.getInstanceFor(myXMPPConnection).createChat(to, this);
//System.out.println("********************************************");
//System.out.println("CHAT ID: "+ chat.getThreadID());
//System.out.println("Participant: "+chat.getParticipant());
//System.out.println("********************************************");
try {
chat.sendMessage(message);
String friendName = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName();
if(conversation.containsKey(friendName))
{
messages = conversation.get(friendName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
//messages.add("bot says: "+message);
}
else
{
messages = new ArrayList<Msg>();
//messages.add("Bot initiated the conversation on: "+new Date());
//messages.add("bot says: "+message);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
conversation.put(friendName,messages);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
System.out.println("You said "+"'"+message+"'"+" to "+myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName());
}
PacketListener myPacketListener = new PacketListener() {
#Override
public void processPacket(Packet p) {
if (p instanceof Message) {
Message msg = (Message) p;
}
}
};
public void displayMyFriends()
{
Roster roster = myXMPPConnection.getRoster();
Collection entries = roster.getEntries();
System.out.println("You currently have: "+entries.size()+" friends available to chat.");
int counter = 0;
Iterator i = entries.iterator();
while(i.hasNext())
{
RosterEntry r = (RosterEntry) i.next();
Presence.Type entryPresence;
entryPresence = roster.getPresence(r.getUser()).getType();
System.out.println((counter+1)+" . "+r.getName() +" is "+entryPresence);
//System.out.println("id:..."+r.getUser());
myFriends.add(r.getUser());
counter++;
}
}
public void disconnectMe()
{
try {
System.out.println("Disconnection in progress...");
myXMPPConnection.disconnect();
System.out.println("You have been successfully disconnected.");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void processMessage(Chat chat, Message message)
{
if((message.getType() == Message.Type.chat) && (message.getBody()!= null)) {
System.out.println(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody());
String myMsg = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody();
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
Msg actualMsg = new Msg(currentTimestamp,myMsg,"customer");
conversation.get(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName()).
add(actualMsg);
}
}
public void receiveMessage(){
myXMPPConnection.addPacketListener(myPacketListener, null);
}
public void retrieveUnservicedMessagesForSpecificPerson(String clientName)
{
ArrayList<Msg> myMessages = conversation.get(clientName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
System.out.println("Unserviced messages from: "+ clientName);
if(!myMessages.isEmpty())
{
int counter = myMessages.size()-1;
System.out.println("Size of array list: "+counter);
boolean found = false;
java.sql.Timestamp lastBotTimestamp = null;
while (counter != 0 && found == false){
if(myMessages.get(counter).getOwner()=="bot")
{
lastBotTimestamp = myMessages.get(counter).getTimestamp();
found = true;
}
else
{
counter = counter-1;
}
}
for(Msg msg:myMessages)
{
if(msg.getTimestamp().before(currentTimestamp) &&
msg.getTimestamp().after(lastBotTimestamp)){
System.out.println("---------------------------");
System.out.println("-"+msg.getActualMessage());
System.out.println("-"+msg.getTimestamp());
System.out.println("---------------------------");
}
}
}
}
public void returnConversation(String name) {
System.out.println("Name of participant entered: "+ name);
System.out.println("Conversation history is: ");
ArrayList<Msg> m = conversation.get(name);
for(Msg msg:m){
System.out.println(msg.getActualMessage());
System.out.println("on: "+msg.getTimestamp());
}
}
public void returnAllUnservicedMessagesHistory()
{
for(String name: conversation.keySet())
{
System.out.println("History of unserviced messages for: "+ name);
retrieveUnservicedMessagesForSpecificPerson(name);
}
}
public void getOfflineMessagesCount(){
try {
System.out.println("Number of offline messages: "+ offlineMessages.getMessageCount());
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
My Main Class Implementation:
public class MainGoogleChatApp {
public static void main(String[] args)
{
//Step 1: need to make a chat request with your username and password.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your username to start: ");
String myUsername = input.next();
System.out.println("Please enter your password to continue: ");
String myPassword = input.next();
ChatRequest myChatRequest = new ChatRequest();
myChatRequest.setUsername(myUsername);
myChatRequest.setPassword(myPassword);
//Step 2: Need to initiate a connection to talk.google.com
StartChatImpl convo = new StartChatImpl();
try {
convo.engageChat(myChatRequest);
} catch (XMPPException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String myMessage;
System.out.println("Friend list.");
convo.displayMyFriends();
convo.receiveMessage();
try {
while(true)
{
System.out.println("Input Which friend you want to chat with '0 to sign out' : ");
int num = input.nextInt() -1;
if (num == -1){
break;
}
String chatWith = StartChatImpl.myFriends.get(num);
System.out.print("Type your message: ");
myMessage=br.readLine();
try {
convo.send(myMessage,chatWith);
} catch (XMPPException e) {
e.printStackTrace();
}
convo.displayMyFriends();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Enter participant name to get specific chat...");
String yourName = null;
try {
yourName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName);
}
System.out.println("Enter another participant's name to get specific chat...");
String yourName1 = null;
try {
yourName1 = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName1!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName1);
}
System.out.println("Select a client name for whom you want to view unserviced messages: ");
String yourClientName = null;
try {
yourClientName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(yourClientName!=null){
System.out.println("...........................................");
convo.retrieveUnservicedMessagesForSpecificPerson(yourClientName);
}
System.out.println("...........................................");
convo.returnAllUnservicedMessagesHistory();
System.out.println("You have chosen to disconnect yourself from talk.google.com");
convo.disconnectMe();
System.exit(0);
}
}
Attempt to retrieve offline messages headers:
public class TestOfflineService {
XMPPConnection xmppConnection = null;
//OfflineMessageManager offlineMessageManager = null;
public void makeConnection()
{
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
xmppConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
xmppConnection.connect();
System.out.println("Logging you in...");
xmppConnection.login("*******.*#***.com", "*****");
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void makeMeUnavailable()
{
try {
xmppConnection.sendPacket(new Presence(Presence.Type.unavailable));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
public void getOfflineMessages()
{
OfflineMessageManager offlineMessageManager1 = new OfflineMessageManager(xmppConnection);
try {
Iterator<OfflineMessageHeader> headers = offlineMessageManager1.getHeaders();
if(headers.hasNext())
{
System.out.println("Messages found");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestOfflineService test = new TestOfflineService();
test.makeConnection();
test.makeMeUnavailable();
System.out.println("Enter messages");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting offline messages.....");
test.getOfflineMessages();
}
}
OfflineMessageManager tries to use XEP-0013 to retrieve offline messages. This XEP isn't implemented by GTalk. Also note that ever starting Hangouts means you'll never get offline messages anymore, as the Hangouts instance is never offline.
GTalk also does not have an XMPP API to retrieve chat history, like XEP-0136 or XEP-0313.
Now basically I have created three classes.
public void run() {
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
} catch (Exception e1) {
e1.printStackTrace();
}
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingMessages.addAll(list);
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
}
try {
Thread.sleep(3000);
System.out.println("new incoming message");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public List<KamMessage> 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<KamMessage> pojoCol = new ArrayList<KamMessage>();
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KamMessage 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 pojoCol;
}
The following are the classes:
1.Poller- does the Polling and Passes the new data from db to controller
2.Controller- this class has a thread Pool, which simultaneously calls the Poller and has the new data to be requested from processor
3.Processor- this class has to look for new data, process it and return it to controller.
So now my problem is how to implement the third phase...
Here is my controller class:
public class RunnableController {
/** Here This Queue initializes the DB and have the collection of incoming message
*
*/
private static Collection<KpiMessage> incomingQueue = new ArrayList<KpiMessage>();
private Connection dbConncetion;
public ExecutorService threadExecutor;
private void initializeDb()
{
//catching exception must be adapted - generic type Exception prohibited
DBhandler conn = new DBhandler();
try {
dbConncetion = conn.initializeDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initialiseThreads()
{
try {
threadExecutor = Executors.newFixedThreadPool(10);
PollingSynchronizer read = new PollingSynchronizer(incomingQueue, dbConncetion);
threadExecutor.submit(read);
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void shutDownThreads()
{
try {
threadExecutor.shutdown();
//DB handling should be moved to separate DB class
dbConncetion.close();
}catch (Exception e){
e.printStackTrace();
}
}
/** Here This Queue passes the messages and have the collection of outgoing message
*
*/
//private Collection<KpiMessage> outgingQueue = new ArrayList<KpiMessage>();
//have to implement something here for future
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
Thread.sleep(3000);
System.out.println("Polling");
}
}
I would recommend using a BlockingQueue for doing so, instead of a simple ArrayList. Just change the type of your incomingQueue variable. Then you can have another thread (or a thread pool) doing something like
//pseudocode
while (true) {
// it polls data from the incomingQueue that shares with the producers
KpiMessage message = this.incomingQueue.take()
//Then process the message and produces an output... you can put that output in a different queue as well for other part of the code to pick it up
}
A good example on BlockingQueues can be found here http://www.javamex.com/tutorials/blockingqueue_example.shtml