How to retrieve Message and Task body - Exchange Web Services - Java - java

I am creating a message using JWebServices, but even though all other fields are retrieved successfully, body does not. message.getBody() returns null. Here are the two methods I call subsequently.
private void createMessage(Service service) throws ParseException {
try {
Message message = new Message();
message.setItemClass(ItemClass.MESSAGE);
message.setSubject("Test");
message.setBody(new Body("Body text"));
message.getToRecipients().add(new Mailbox("John#mydomain.com"));
message.getCcRecipients().add(new Mailbox("Mark#mydomain.com"));
ItemId itemId = service.createItem(message,StandardFolder.SENT_ITEMS);
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
private void listItemsInSent(Service service) throws ParseException {
try {
FindItemResponse response = service.findItem(StandardFolder.SENT_ITEMS);
Message m = null;
for (int i = 0; i < response.getItems().size(); i++) {
m = (Message)response.getItems().get(i);
System.out.println(m.getSubject());
System.out.println(m.getItemClass());
System.out.println(m.getLastModifiedTime());
System.out.println(m.getBody());
System.out.println(m.getBodyHtmlText());
System.out.println(m.getBodyPlainText());
System.out.println(m.getItemId());
System.out.println(m.toString());
System.out.println();
}
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}

Try to replace
m = (Message)response.getItems().get(i);
with
m = service.getMessage(response.getItems().get(i).getItemId());

Related

How to Get the java.util.function input parameters in exception block

How to Get the input arguments/parameters of java.util.function in exception block
In the below code, I want to get the input parameters that are supplied to the function. When processWithRetry(..) throws ApplicationException or any other exception and we do retry 10 attempts to do retry. When the retry fails for 10 times then we need to which Employee object has failed in Exception block
When i debug and check function parameter has mulipleArgyments args1, arg2, arg3, in runtime. One of the raguments points to Employee Object. How to get function arguments in below exception block.
When i say function.applyThen(..) method is there but no function.getParameters() or getArgs().. methods available.
catch (ApplicationException e) {
if (i == nRetries - 1) {
throw e;
}
} catch (Exception e) {
e.printStackTrace();
Long failed = 0L;
result = (T) failed;
}
Below is the complete code and flow.
Public class EmployeeProcessor {
public void processEmployee() {
BlockingQueue<Optional<Employee>> queue = new ArrayBlockingQueue<>(100000);
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new Thread(() -> {
try (for every DB connection from pool) {
while (true) {
Optional<Employee> take = queue.take();
if (!take.isPresent()) {
break;
} else {
Employee employee = take.get();
long count = processWithRetry(connectionObject, 10, dbSession -> {
// many statements here, but no try & catch block, but processing might throw ApplicationException
return 0L;
});
}
}
});
threads[i].start();
}
}
for (String filePath : fileList) {
processFileByFile(filePath, queue, connectionObject);
}
}
protected void processFileByFile(String filePath, BlockingQueue<Optional<Employee>> queue, DBconnectionObject)
throws IOException, InterruptedException {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
try {
String dataLine;
while ((dataLine = reader.readLine()) != null) {
if (dataLine != null && dataLine != "") {
List<String> eachLineList = Arrays.asList(eachLine.split(","));
queue.put(Optional.of(
new Employee(eachLineList.get(0), eachLineList.get(1), eachLineList.get(2))));
}
}
} finally {
reader.close();
}
}
class Employee {
String firstName;
String lastName;
String age;
public Employee(String firstName, String lastName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
#SuppressWarnings("unchecked")
<T> T processWithRetry(connectionObject connectionObject, int nRetries, Function<dbSession, T> function)
throws IllegalStateException, IllegalArgumentException, ApplicationException, UnsupportedOperationException {
if (nRetries < 1) {
throw new IllegalArgumentException("Wrong number of attempts: " + nRetries);
}
T result = null;
for (int i = 0; i < nRetries; i++) {
try {
result = function.apply(connectionObject);
break;
} catch (ApplicationException e) {
if (i == nRetries - 1) {
throw e;
}
} catch (Exception e) {
e.printStackTrace();
Long failed = 0L;
result = (T) failed;
}
}
return result;
}
}
Get one of the arguments what i see in inpsect during debug time. in the Below exception block.
catch (ApplicationException e) {
if (i == nRetries - 1) {
throw e;
}
} catch (Exception e) {
e.printStackTrace();
Long failed = 0L;
result = (T) failed;
}

Retrieve Offline Messages and Chat History From Google Talk in Java

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.

Invoking an instance method from a REST service method

I have a REST service accepting POST requests. Is there any way I can trigger a method inside my running swing GUI from that service? I want to make it possible to refresh the GUI table of posted data after every POST request is made. Is there any event handling mechanism for doing this?
REST service code:
#POST
#Consumes({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
#Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public Response createServiceRegistration(
#PathParam("serviceProviderId") final String serviceProviderId ,
final ServiceRegistration aServiceRegistration
) throws IOException, ServletException
{
try
{
ServiceRegistration newServiceRegistration = OrchestratorAdaptorManager.createServiceRegistration(httpServletRequest, aServiceRegistration, serviceProviderId);
httpServletResponse.setHeader("ETag", OrchestratorAdaptorManager.getETagFromServiceRegistration(newServiceRegistration));
/////////////////////////////////////////////////////
// Accessing and writing registration data to database
//
try
{
System.out.println("establishing database connection");
Registration registration = new Registration();
registration.createConnection();
registration.insertRegistration(aServiceRegistration.getService().toString(), aServiceRegistration.getTitle(), aServiceRegistration.getLabel());
registration.shutdown();
}
catch(Exception exc)
{
exc.printStackTrace();
throw new RuntimeException("Error inserting ServiceRegistration to the database", exc);
}
//
// Disconnected from the base
///////////////////////////////////////////////////
return Response.created(newServiceRegistration.getAbout()).entity(aServiceRegistration).build();
}
catch (Exception e)
{
e.printStackTrace();
throw new WebApplicationException(e);
}
//Trigger changes in GUI here :/
}
Class which I used to update the table every 10 seconds:
class CheckServices extends TimerTask
{
DefaultTableModel model;
protected CheckServices(DefaultTableModel model)
{
this.model = model;
}
#Override
public void run()
{
Registration reg = new Registration();
try
{
reg.createConnection();
ServiceRegistration[] sr = reg.selectRegistrations();
reg.shutdown();
System.out.println("Adding Registration Resources");
int rows = model.getRowCount();
for(int i = 0; i < rows; i++)
{
model.removeRow(0);
}
for(ServiceRegistration srItem : sr)
{
System.out.println("--> " + srItem.getTitle());
Object[] row = { false , srItem.getService().toString(), srItem.getTitle(), srItem.getLabel()};
model.addRow(row);
}
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Why does object inside a protected method has implementation?

Its the method invokeBackend(String request, HashMap context) .
Why does it have an object named java.security.PrivilegedAction createController = new java.security.PrivilegedAction()
and it has an implementation ? I see it has a run() method which means its a thread.
Does the run method returns "controller"? It returns "controller" to what?
What kind of an implementation is this? An object having implementation code?
3.Whats the primary use of implmentation of the method invokeBackend
Also the object
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction()
Thanks a lot!
protected static String invokeBackend(String request, HashMap context)
throws CommonModelException {
if (request.equals("")) {
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("request: \r\n" + request);
}
Properties clientAuthenticationEnv = CommonProperties
.getClientAuthenticationProperties();
if (wccClientId == null) {
wccClientId = clientAuthenticationEnv.getProperty(CLIENT_ID);
}
if (wccClientPassword == null) {
wccClientPassword = clientAuthenticationEnv
.getProperty(CLIENT_PASSWORD);
}
controllerHome = getControllerHome();
String response = null;
try {
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
if (isWASImpl) {
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
validateSecurityToken();
final DWLServiceController controller = (DWLServiceController) WSSubject
.doAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
validateSecurityToken();
response = (String) WSSubject.doAs(subject, processRequest);
} else {
// DWLServiceController controller = controllerHome.create();
// response = (String) controller.processRequest(context,
// request);
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
//reflection invoke to avoid compile dependency on weblogic library
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class securityClazz = cl.getClass().getClassLoader().loadClass("weblogic.security.Security");
Method runAs = securityClazz.getMethod("runAs", new Class[]{Subject.class, java.security.PrivilegedAction.class});
final DWLServiceController controller = (DWLServiceController) runAs.invoke(securityClazz, new Object[]{subject, createController});
//final DWLServiceController controller = (DWLServiceController) Security.runAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
response = (String)runAs.invoke(securityClazz, subject, processRequest);
//response = (String) Security.runAs(subject, processRequest);
}
} catch (Exception e) {
response = e.getLocalizedMessage();
// for non IBM WebSphere Server, we have one more chance to redo
// lookup for EJB server restart, clear the session first
controllerHome = getControllerHome();
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
try {
DWLServiceController controller = controllerHome.create();
response = (String) controller.processRequest(context, request);
} catch (DWLResponseException e1) {
response = e1.getLocalizedMessage();
} catch (RemoteException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e1);
throw new CommonModelException(e1);
} catch (CreateException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e1);
throw new CommonModelException(e1);
}
}
if (logger.isDebugEnabled()) {
logger.debug("response: \r\n" + response);
}
return response;
}
The declaration you're looking at is a local variable initialized to reference an instance of an anonymous inner class. The class implemented is PrivilegedAction. The syntax is used when you want to create a one-off implementation of an interface or class that you don't intend to use elsewhere, so there's no point in giving it a name. The code implements the run method from the interface and creates an object implementing that interface, that it assigns to the local variable.
The run method returns a controller object to whoever calls run on it. That isn't shown here, it's passed in as one of the arguments to the runAs method call on this line:
final DWLServiceController controller = (DWLServiceController) runAs.invoke(
securityClazz, new Object[]{subject, createController});
where the code used reflection to look up the runAs method on the class weblogic.security.Security.

How pass these new messages to another class

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

Categories