package org.apache.interop.wcmgr;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JSplitPane;
import javax.swing.WindowConstants;
import javax.xml.namespace.QName;
import org.apache.interop.smgr.ConnectionListener;
import org.apache.interop.smgr.MessageListener;
import org.apache.interop.smgr.MessageWorker;
import org.apache.interop.smgr.NotificationListener;
import org.apache.interop.smgr.SubsciberInfoJPanel;
import org.apache.ws.addressing.EndpointReference;
import org.apache.ws.addressing.XmlBeansEndpointReference;
import org.apache.ws.addressing.v2004_08_10.AddressingConstants;
import org.apache.ws.muws.interop.client.FaultException;
import org.apache.ws.muws.interop.client.ResourceStub;
import org.apache.ws.muws.interop.client.ServiceStub;
import org.apache.ws.muws.interop.client.WcmMessage;
import org.apache.ws.util.XmlBeanUtils;
import org.apache.wsdm.interop.wcm.impl.WcImpl;
import org.apache.wsdm.interop.wcm.impl.WsImpl;
import org.apache.wsdm.interop.wcm.impl.ui.MessagesJPanel;
import org.apache.wsdm.interop.wcm.impl.ui.StatusJPanel;
import org.apache.wsdm.interop.wcm.impl.ui.jgraph.WsGraphCell;
import org.apache.wsdm.interop.wcm.model.IWc;
import org.apache.wsdm.interop.wcm.model.IWs;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
import org.oasisOpen.docs.wsdm.x2004.x12.muws.wsdmMuwsPart1.ComponentAddressType;
import org.oasisOpen.docs.wsdm.x2004.x12.muws.wsdmMuwsPart1.ComponentType;
import org.oasisOpen.docs.wsdm.x2004.x12.muws.wsdmMuwsPart1.impl.ManagementEventTypeImpl;
import org.oasisOpen.docs.wsdm.x2004.x12.muws.wsdmMuwsPart2.impl.RelationshipTypeImpl;
import org.oasisOpen.docs.wsn.x2004.x06.wsnWSBaseNotification12Draft01.NotificationMessageHolderType;
import org.oasisOpen.docs.wsn.x2004.x06.wsnWSBaseNotification12Draft01.NotifyDocument;
import org.oasisOpen.docs.wsrf.x2004.x06.wsrfWSResourceProperties12Draft01.ResourcePropertyValueChangeNotificationType;
import org.wsdmdemo.service.weatherStation.RecalibrateDocument;
import org.xmlsoap.schemas.soap.envelope.Body;
import org.xmlsoap.schemas.soap.envelope.EnvelopeDocument;
import org.xmlsoap.schemas.ws.x2004.x08.addressing.EndpointReferenceType;
import org.apache.interop.common.LocationJPanel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
/**
* This code was generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* *************************************
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED
* for this machine, so Jigloo or this code cannot be used legally
* for any corporate or commercial purpose.
* *************************************
*/
public class WcMgrApp extends javax.swing.JFrame implements ConnectionListener,MessageListener,CommandListener {
private LocationJPanel locationJPanel;
private MessagesJPanel messagesJPanel1;
private StatusJPanel statusJPanel;
private JSplitPane jSplitPane;
private MessageWorker m_messageWorker;
private NotificationListener m_listener;
private StringBuffer m_buffer=new StringBuffer();
private ResourceStub m_resource;
private static final QName RELATIONSHIP_QNAME=new QName("http://docs.oasis-open.org/wsdm/2004/12/muws/wsdm-muws-part2.xsd","Relationship");
private Vector model;
private String notificationListenerUrl="http://192.168.2.120:8001/bogas";
private static final int LISTENER_PORT = 8000;
private static final String WcConfigEprURL="";
private JButton jButton;
private JPanel jPanel1;
private String m_activeWeatherStation;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
WcMgrApp inst = new WcMgrApp();
inst.setVisible(true);
}
public WcMgrApp() {
super();
initGUI();
statusJPanel.setPopupListener(this);
locationJPanel.setConnectionListener(this);
// locationJPanel.setResourceUrl("http://12.35.246.160:8080/muse/services/WeatherStationDir");
// locationJPanel.setTopicNamespace("");
// locationJPanel.getTopicName("");
//locationJPanel.setNotificationLister("http://12.35.246.160:8001/bogas");
// locationJPanel.setNotificationLister("http://192.168.0.20:8001/bogas");
}
private void initGUI() {
try {
this.setSize(725, 605);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("WCMgr ");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.out.println("this.windowClosing, event=" + evt);
onDisconnect();
try {
locationJPanel.save();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
{
locationJPanel = new LocationJPanel();
this.getContentPane().add(locationJPanel, BorderLayout.NORTH);
}
{
jSplitPane = new JSplitPane();
this.getContentPane().add(jSplitPane, BorderLayout.CENTER);
jSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane.setDividerLocation(150);
{
statusJPanel = new StatusJPanel();
jSplitPane.add(statusJPanel, JSplitPane.TOP);
}
{
messagesJPanel1 = new MessagesJPanel();
jSplitPane.add(messagesJPanel1, JSplitPane.BOTTOM);
}
}
{
jPanel1 = new JPanel();
this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
{
jButton = new JButton();
jPanel1.add(jButton);
jButton.setText("Resolve Problem");
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out
.println("jButton.actionPerformed, event="
+ evt);
resolveWsProblem();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
protected void resolveWsProblem() {
Object[] allStations = statusJPanel.getRoots();
double lowestPrice=1000f;
WsImpl wsChoice=null;
System.out.println("Deciding How to resolve a WS problem");
for (int index = 0; index < allStations.length; index++) {
Object object = allStations[index];
if(object instanceof WsGraphCell){
WsGraphCell wsCell=(WsGraphCell)object;
String name=wsCell.toString();
WsImpl ws=(WsImpl)findInModel(name);
String status=ws.queryStatus();
String strPrice=ws.queryPrice();
float fprice=Float.parseFloat(strPrice);
String strEpr=ws.getEpr().toString();
System.out.println("Station:"+name+" status:"+status+" price:"+strPrice);
if(status.equals("Available")){
if(fprice<lowestPrice){
lowestPrice=fprice;
wsChoice=ws;
}
}
}
}
// Call WC and set it for the cheapest and the best
if(wsChoice!=null)
switchStations(wsChoice);
else
System.out.println("No CHoice found.");
}
private void switchStations(WsImpl ws){
System.out.println("I CHOOSE "+ws.getName());
try {
ws.makeActive(locationJPanel.getEpr("weather-client-config-epr.xml"));
} catch (XmlException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
statusJPanel.setCurrentWc(ws.getName());
}
/* (non-Javadoc)
* @see org.apache.interop.smgr.ConnectionListener#onConnect()
*/
public void onConnect() {
// Start TCP Listener and A worker that will deliver received notifications
m_messageWorker = new MessageWorker(this,m_buffer);
m_listener = new NotificationListener(LISTENER_PORT,60000,m_buffer);
try {
m_messageWorker.start();
m_listener.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Extact A model from the Wsdm Relationsship of
// The directory
try {
getModelFromRelationship();
// Request Inital Status of
updateOperationalStatus();
} catch (XmlException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FaultException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
*/
private void updateCurrentWsChoice() {
// TODO Auto-generated method stub
}
/**
*
*/
private void updateOperationalStatus() {
// TODO Auto-generated method stub
for (Iterator iter = model.iterator(); iter.hasNext();) {
IWs ws = (IWs) iter.next();
if(!(ws instanceof IWc)){
String status=ws.queryStatus();
Color color=colorFromStatus(status);
System.out.println(status);
statusJPanel.setColor(ws.getName(), color);
}
}
statusJPanel.invalidate();
statusJPanel.updateUI();
}
/**
* @param status
* @return
*/
private Color colorFromStatus(String status) {
if(status.equalsIgnoreCase("Available"))
return Color.GREEN;
if(status.equalsIgnoreCase("Unavailable"))
return Color.RED;
return Color.GRAY;
}
/**
* @throws FaultException
* @throws XmlException
* @throws IOException
*
*/
private void getModelFromRelationship() throws FaultException, XmlException, IOException {
// Query Relationships and build model
m_resource = new ResourceStub( locationJPanel.getEpr("weather-station-dir-epr.xml") );
m_resource.addObserver(messagesJPanel1);
XmlObject[] relationArry = m_resource.getResourceProperty(RELATIONSHIP_QNAME);
model = new Vector();
IWc wc=new WcImpl(0,"Wc",null);
model.add(wc);
RelationshipTypeImpl relationshipSample = (RelationshipTypeImpl) relationArry[0];
for (int i = 0; i < relationArry.length; i++) {
RelationshipTypeImpl relationship = (RelationshipTypeImpl) relationArry[i];
IWs ws1=new WsImpl(relationship,notificationListenerUrl,messagesJPanel1);
model.add(ws1);
}
// Capture the name of the defaultActive WS
for (Iterator siWter = model.iterator(); siWter.hasNext();) {
IWs element = (IWs) siWter.next();
if(!(element instanceof IWc)){
m_activeWeatherStation=element.getName();
break;
}
}
statusJPanel.setModel((IWs[]) model.toArray(new IWs[0]));
}
/* (non-Javadoc)
* @see org.apache.interop.smgr.ConnectionListener#onDisconnect()
*/
public void onDisconnect() {
m_messageWorker.stop();
m_listener.stop();
}
/* (non-Javadoc)
* @see org.apache.interop.smgr.MessageListener#onMessage(java.lang.String)
*/
public void onMessage(String messageText) {
// Create a new Message in the messages window
System.out.println("Message Starts.");
System.out.println(messageText);
messageText=hackAddNameSpace(messageText);
System.out.println("Message Ends.");
messagesJPanel1.setMessage(new WcmMessage(messageText, "","N"));
try {
NotificationMessageHolderType noteMess = getNotificationMessageHolder(messageText);
ManagementEventTypeImpl manEvt = parseManagementEvent(noteMess);
String optStatus = parseCurrentOperationalStatus(manEvt);
EndpointReferenceType epr = parseSourceEpr(noteMess) ;
//if(epr)
System.out.println(""+epr.getAddress()+" Reports "+optStatus);
updateStatusOfWs(epr,optStatus);
} catch (XmlException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param messageText
* @return
*/
private String hackAddNameSpace(String messageText) {
//xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
String find = "xmlns:wsa=\""+AddressingConstants.NSURI_ADDRESSING_SCHEMA+"\"";
String replace = "xmlns:wsa=\""+org.apache.ws.addressing.v2003_03.AddressingConstants.NSURI_ADDRESSING_SCHEMA+"\"";
String messageText1=messageText.replaceAll(find,replace);
return messageText1;
}
/**
* @param epr
* @param optStatus
*/
private void updateStatusOfWs(EndpointReferenceType epr, String optStatus) {
String epr1=epr.getAddress().getStringValue();
for (Iterator iter = model.iterator(); iter.hasNext();) {
WsImpl ws = (WsImpl) iter.next();
if(!(ws instanceof IWc)){
EndpointReference eprTest = ws.getEpr();
if(epr.getAddress().getStringValue().endsWith("anonymous")){
if(eprTest.getAddress().endsWith("WeatherStationSOAP")){
Color color=colorFromStatus(optStatus);
statusJPanel.setColor(ws.getName(),color);
}
}
else {
if(eprTest.getAddress().equals(epr.getAddress().getStringValue())){
Color color=colorFromStatus(optStatus);
statusJPanel.setColor(ws.getName(),color);
}
}
repairIfNeeded(ws.getName(),optStatus);
}
}
}
/**
* @param name
* @param optStatus
*/
private void repairIfNeeded(String name, String optStatus) {
// if(optStatus.equals("Available"))
// return; // Don't respond to avaiable notices
String activeWsName=getActiveWsName();
if(name.equals(activeWsName)){
System.out.println("Have decided to repair based on ACTIVE ws being "+activeWsName+" and event name being "+name +"being "+optStatus);
resolveWsProblem();
}
}
/**
*
* @return
*/
private String getActiveWsName() {
// TODO Auto-generated method stub
return m_activeWeatherStation;
}
private EndpointReference getEpr(String URL, String Rid) throws XmlException{
XmlBeansEndpointReference x=new XmlBeansEndpointReference(URL,AddressingConstants.NSURI_ADDRESSING_SCHEMA);
if(Rid!=null)
x.setReferenceProperties(new XmlObject[]{(XmlObject)XmlObject.Factory.parse("<svr:ResourceIdentifier xmlns:svr=\"http://wsdmdemo.org/service/weather-client-config\">"+Rid+"</svr:ResourceIdentifier>")});
return x;
}
/* (non-Javadoc)
* @see org.apache.interop.wcmgr.CommandListener#recalibrate(java.lang.String)
*/
public void recalibrate(String stationName) {
System.out.println("I will recalibrate "+stationName);
for (Iterator iter = model.iterator(); iter.hasNext();) {
WsImpl station = (WsImpl) iter.next();
if(station.getName().equals(stationName)){
//ServiceStub sstub;
ResourceStub sstub = new ResourceStub(station.getEpr());
sstub.addObserver(messagesJPanel1);
RecalibrateDocument recalibrateDocument = RecalibrateDocument.Factory.newInstance();
recalibrateDocument.addNewRecalibrate();
sstub.sendRequest(recalibrateDocument,
"http://recalibrate","M");
sstub.deleteObserver(messagesJPanel1);
}
}
}
/**
* Parses the ManagementEvent out of the SOAPEnvelope
*
* @param messageText
* @return ManagementEvent
* @throws XmlException
*/
private ManagementEventTypeImpl parseManagementEvent(NotificationMessageHolderType noteMess)
throws XmlException
{
XmlAnyTypeImpl mess = (XmlAnyTypeImpl) noteMess.getMessage();
ManagementEventTypeImpl manEvt =
(ManagementEventTypeImpl) XmlBeanUtils.getChildElements(mess)[0];
return manEvt;
}
/**
* @param messageText
* @return
* @throws XmlException
*/
private NotificationMessageHolderType getNotificationMessageHolder(String messageText) throws XmlException {
EnvelopeDocument ed = (EnvelopeDocument) XmlObject.Factory.parse(messageText);
org.xmlsoap.schemas.soap.envelope.Envelope env = ed.getEnvelope();
Body body = env.getBody();
XmlObject[] arryStuff = XmlBeanUtils.getChildElements(body);
NotifyDocument.Notify ele = (NotifyDocument.Notify) arryStuff[0];
NotificationMessageHolderType noteMess = ele.getNotificationMessageArray(0);
return noteMess;
}
/**
* Gets the current OperationalStatus from the ManagementEvent
*
* @param manEvt
* @return OperationalStatus (i.e. Available)
*/
private String parseCurrentOperationalStatus(ManagementEventTypeImpl manEvt)
{
XmlObject[] childElements = XmlBeanUtils.getChildElements(manEvt);
ResourcePropertyValueChangeNotificationType propChange = null;
for (int i = 0; i < childElements.length; i++) {
if(childElements[i] instanceof ResourcePropertyValueChangeNotificationType)
{
propChange =
(ResourcePropertyValueChangeNotificationType) childElements[i];
break;
}
}
if(propChange == null) return "Unavailable";
ResourcePropertyValueChangeNotificationType.NewValue newValue = propChange.getNewValue();
XmlObject operationalStatus =
XmlBeanUtils.getChildElements(newValue)[0];
XmlCursor xmlCursor = operationalStatus.newCursor();
return xmlCursor.getTextValue();
}
/**
* Parses the source (web service which threw event) epr from the ManagementEvent
*
* @param manEvt
* @return Source EPR
*/
private EndpointReferenceType parseSourceEpr(NotificationMessageHolderType noteMess)
{
return (EndpointReferenceType) new XmlBeansEndpointReference(noteMess.getProducerReference()).getXmlObject(AddressingConstants.NSURI_ADDRESSING_SCHEMA);
}
public IWs findInModel(String name){
for (Iterator iter = model.iterator(); iter.hasNext();) {
IWs ws = (IWs) iter.next();
if(name.equals(ws.getName())){
return ws;
}
}
return null;
}
}