I’ve asked a similar question to this here: Best way to interact with EJBs in Java EE And the response was great, but I’m still not getting the results I’m looking for. The EJB is still not being called even though I added the @PostConstruct annotation and converted the main class to a managed bean so that I could use injection. I think I’m close but I’m still not grasping some fundamental concepts involved with Java EE and EJBs. I think I might have to use some kind of timer event to make this work.
Again, my problem is that I want this class to execute at least once while it’s running. It’s getting twitter feed results from the URL, parsing the content into an array and then adding the first value to the database. The database management is done through another EJB so I have to use some kind of injection to access this class. Originally I had created a main method to test the code but I was getting Null reference exceptions because I was trying to inject and call an EJB’s method from a regular java class.
Here is my new code with managed beans and PostConstruct annotation:
@ManagedBean
public class Driver {
@EJB RSSbean rssbean;
@PostConstruct
public void initURL() throws IOException, JSONException{
System.setProperty("http.proxyHost", "proxya..com");
System.setProperty("http.proxyPort", "8080");
/////////////auth code///////////////auth code/////////////////
String username = System.getProperty("proxy.authentication.username");
String password = System.getProperty("proxy.authentication.password");
if (username == null)
{
Authenticator.setDefault(new ProxyAuthenticator("s", "w"));
}
///////////////end auth code/////////////////////////////////end
URL twitterSource = new URL("http://search.twitter.com/search.json?q=news");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
JSONObject thisobject = new JSONObject(urlContents);
JSONArray names = thisobject.names();
JSONArray asArray = thisobject.toJSONArray(names);
JSONArray resultsArray = thisobject.getJSONArray("results");
JSONObject(urlContents.trim());
JSONObject jsonObject = resultsArray.getJSONObject(0);
String twitterText = jsonObject.getString("text");
System.out.println("Calling rssbean from Driver");
**rssbean.updateDatabase("twitterText");**
}}
The bottom line with the rssbean.updateDatabase is what needs to be executed for the updates to get persisted to the database.
You must add
@Statelessor@Stateful(Depending on your use/need) then remove the@ManagedBean. If you make it @Stateful be sure to implement Serializeable interface too.