TechnoChris1
TechnoChris1

Reputation: 11

Migrating application made with Processing.org to Eclipse

I made a simple program in Processing, and it works great. Im now attempting to bring my beginner Java skills to Eclipse to make the same program over again. The program takes a Rs232 string that comes from the Com port and sends it over Xmpp.

The issue I'm having is that i cant call newChat.sendMessage(message) like i can in processing from any of the Classes/Tabs. Can someone clue me in to what i should look for to fix this issue. I'm guessing Extending, or implementing the Xmpp class is what i need to do. I love how simple processing handles it..

Any help will be greatly appreciated.

Fyi: the Smack library's are in the code folder for processing.

Main Application:

import processing.net.*;




void setup() {
  size(400, 200);
  noStroke();
  background(0);
  LoadSerialPort();
  OpenChatConnection();
  setupFilterThread ();
}

void draw() {
}



String timestampTime() {
  Calendar now = Calendar.getInstance();
  return String.format("%1$tH:%1$tM:%1$tS", now);
}


String timestampDate() {
  Calendar now = Calendar.getInstance();
  return String.format("%1$tm/%1$td/%1$tY", now);
}

Filter Class/Tab:

FilterThread thread1;

List FilteredArchAddressList = new ArrayList();
ArrayList CallList = new ArrayList();

void  setupFilterThread () {

  thread1 = new  FilterThread(100, "a");
  thread1.start();
}

void checkForNewCalls() {
  if (CallList.size() >=1) {
    println("New Call In List, Size: "+CallList.size());
    FilterComPortString((String) CallList.get(0));
    CallList.remove(0);
  }
}

void FilterComPortString(String s) {

    Message message = new Message("[email protected]", Message.Type.normal);
    //message.setTo("[email protected]");
    message.setSubject("MSG_TYPE_NORMAL");
    message.setBody(s);
    message.setProperty("systemID", "JS1");
    message.setProperty("serverTime", trim(timestampTime()));
    message.setProperty("serverDate", trim(timestampDate()));

    try {
      newChat.sendMessage(message);
    }
    catch (Exception e) {
      println(e);
    }
  }
}

class  FilterThread extends  Thread {

  boolean  running;           // Is the thread running?  Yes or no?
  int  wait;                  // How many milliseconds should we wait in between executions?
  String  id;                 // Thread name
  int  count;                 // counter

  // Constructor, create the thread
  // It is not running by default
  FilterThread (int  w, String  s) {
    wait = w;
    running = false ;
    id = s;
    count = 0;
  }

  int  getCount() {
    return  count;
  }

  // Overriding "start()"
  void  start () {
    // Set running equal to true
    running = true ;
    // Print messages
    println ("Starting thread (will execute every " + wait + " milliseconds.)"); 
    // Do whatever start does in Thread, don't forget this!
    super .start();
  }


  // We must implement run, this gets triggered by start()
  void  run () {
    while  (running) {
      checkForNewCalls();
      // Ok, let's wait for however long we should wait
      try {
        sleep((long )(wait));
      } 
      catch  (Exception e) {
      }
    }
    System.out.println (id + " thread is done!");  // The thread is done when we get to    the end of run()
  }


  // Our method that quits the thread
  void  quit() {
    System.out.println ("Quitting."); 
    running = false ;  // Setting running to false ends the loop in run()
    // IUn case the thread is waiting. . .
    interrupt();
  }
}

Rs232 Class/Tab:

import processing.serial.*;

Serial myPort; // Rs232, Serial Port
String inString;  // Input string from serial port: 
int lf = 10;      // ASCII linefeed 


String SelectedCom;

void LoadSerialPort() {


  println(Serial.list()); 
  println("________________________________________________________");

  try {
    myPort = new Serial(this, Serial.list()[0], 9600); 
    myPort.bufferUntil(lf);
    SelectedCom = Serial.list()[0];
    println("Connected to Serial Port:");
    println("________________________________________________________");
  } 
  catch (ArrayIndexOutOfBoundsException e) {
    String exception = e.toString();
    if (exception.contains("ArrayIndexOutOfBoundsException: 0")) {
      println("NO AVAILABLE COM PORT FOUND");
    } 
    else {
      println(e);
    }
  }
}

void serialEvent(Serial p) { 
  inString = p.readString();   
  CallList.add(new String(inString));
}

Xmpp Class/Tab:

String FromXmpp = "";
Chat newChat;
ChatManager chatmanager;


XMPPConnection connection;

public void OpenChatConnection() {

  // This is the connection to google talk. If you use jabber, put other stuff in here. 
  ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.103", 5222, "Jabber/XMPP");
  config.setSASLAuthenticationEnabled(false);

  configure(ProviderManager.getInstance());

  connection = new XMPPConnection(config);

  println("Connecting");
  try {
    //connection.DEBUG_ENABLED = true;
    connection.connect();
    println("Connected to: "+connection.getServiceName() );
  } 

  catch (XMPPException e1) {
    println("NOT Connected");
  }

  if (connection.isConnected()) {

    try {

      // This is the username and password of the chat client that is to run within Processing.  
      println("Connecting");
      connection.login("System1", "test"); 
      //connection.login("[email protected]", "yourpassword");
    } 
    catch (XMPPException e1) {
      // would probably be a good idea to put some user friendly action here.
      e1.printStackTrace();
    }  
    println("Logged in as: "+connection.getUser() );
  }
  chatmanager = connection.getChatManager();
  // Eventhandler, to catch incoming chat events
  newChat = chatmanager.createChat("[email protected]", new MessageListener() {   //[email protected]   //admin@x-dev
    public void processMessage(Chat chat, Message message) {
      // Here you do what you do with the message
      FromXmpp = message.getBody();
      // Process commands
      //println(FromXmpp);
    }
  }
  );


  Roster roster = connection.getRoster();
  Collection<RosterEntry> entries = roster.getEntries();
  for (RosterEntry entry : entries) {
    System.out.println(entry);
  }
}


public void configure(ProviderManager pm) {

  //  Private Data Storage
  pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());

  //  Time
  try {
    pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
  } 
  catch (ClassNotFoundException e) {
    println(("TestClient "+" Can't load class for org.jivesoftware.smackx.packet.Time"));
  }

  //  Roster Exchange
  pm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider());

  //  Message Events
  pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());

  //  Chat State
  pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider()); 
  pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());

  //  XHTML
  pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());

  //  Group Chat Invitations
  pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());

  //  Service Discovery # Items    
  pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());

  //  Service Discovery # Info
  pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

  //  Data Forms
  pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());

  //  MUC User
  pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());

  //  MUC Admin    
  pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());

  //  MUC Owner    
  pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());

  //  Delayed Delivery
  pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());

  //  Version
  try {
    pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
  } 
  catch (ClassNotFoundException e) {
    //  Not sure what's happening here.
  }

  //  VCard
  pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());

  //  Offline Message Requests
  pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());

  //  Offline Message Indicator
  pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());

  //  Last Activity
  pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());

  //  User Search
  pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());

  //  SharedGroupsInfo
  pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());

  //  JEP-33: Extended Stanza Addressing
  pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());

  //   FileTransfer
  pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());

  pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());

  //  Privacy
  pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
  pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
  pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
  pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
  pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
  pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
  pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
}

Upvotes: 0

Views: 830

Answers (2)

Pwdr
Pwdr

Reputation: 3781

Every class which uses the chat-functionality, needs to know the chat-object. You can put all your variables and functions which are not in a separate class in the main source-file.

When you declare a variable in Processing, it can be used from any tab, in java global variables do not exist. You can get a similar functionality like this: Create a new file GlobalVars.java with this content:

public class GlobalVars {
   public static Chat myChat;
}

Now everytime you want to access the Chat-functions, you have to write e.g. GlobalVars.myChat.sendMessage("Hi!");

Btw, You have to include the net.jar-file. On Mac this is located here: Processing.app/Contents/Resources/Java/modes/java/libraries/net/library/net.jar

Upvotes: 0

George Profenza
George Profenza

Reputation: 51867

If you know your way around eclipse, first you need to create a new Java project and add Processing's core.jar to the build path and start by creating a sublcass of PApplet. If not, there's a really easy to work with eclipse plugin called Proclipsing and video guide to get started with it.

proclipsing

Bringing your code from Processing to eclipse:

You need to understand that all the code you have in a Processing sketch (including tabs) gets merged into a single .java file and the sketch name is the class name. Any classes you define in tabs in the sketch become nested classes in a main single class. Easiest way to see this is to export an applet and have a look in the generated folder for the SketchName.java file. Remember, a tab is not a class (although it can contain one).

So you've got a few options. Here are two basic approaches:

  1. Create a new PApplet subclass and start pasting your whole code in it (including content of tabs). You will need to de explicit about accessors (e.g. public void setup() instead of just void setup()) and be careful with double/float values (e.g. if eclipse complains about 1.0, be explicit: 1.0f)

  2. The other option is to create multiple classes, as I imagine you intend to do if you're using eclipse. The catch is, in Processing, variables defined in tabs are actually 'global' variables. Your code would work the same way if you declare those in the main tab at the top. Also, using PApplet functions needs to be refactored. Some functions can be called using Java's classes (not PApplet's) to break the dependency: e.g. System.out.println() instead of println(), but of others you might want your classes to have access to a PApplet instance:

e.g.

public class  FilterThread extends  Thread {

  boolean  running;           // Is the thread running?  Yes or no?
  int  wait;                  // How many milliseconds should we wait in between executions?
  String  id;                 // Thread name
  int  count;                 // counter
  YourSketchClass parent;

  // Constructor, create the thread
  // It is not running by default
  FilterThread (int  w, String  s,YourSketchClass p) {
    wait = w;
    running = false ;
    id = s;
    count = 0;
    parent = p;
  }

  int  getCount() {
    return  count;
  }

  // Overriding "start()"
  public void  start () {
    // Set running equal to true
    running = true ;
    // Print messages
    System.out.println ("Starting thread (will execute every " + wait + " milliseconds.)"); 
    // Do whatever start does in Thread, don't forget this!
    super .start();
  }


  // We must implement run, this gets triggered by start()
  public void  run () {
    while  (running) {
      parent.checkForNewCalls();
      // Ok, let's wait for however long we should wait
      try {
        sleep((long )(wait));
      } 
      catch  (Exception e) {
      }
    }
    System.out.println (id + " thread is done!");  // The thread is done when we get to    the end of run()
  }


  // Our method that quits the thread
  void  quit() {
    System.out.println ("Quitting."); 
    running = false ;  // Setting running to false ends the loop in run()
    // IUn case the thread is waiting. . .
    interrupt();
  }
}

Upvotes: 1

Related Questions