Commit 86c27581 authored by claes's avatar claes

Event log implemented

parent c55dcbaf
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
/* This class is used as a ComponentListener for any Component for which
the Aspect Ratio is important and needs to be retained. The constructor
needs to know what Component it is applied to and the original size of it.
From the size the aspect ratio is calculated and every time the Container
is resized. The size is changed so that the aspect ratio matches the,
relatively, smaller one of the new width and height.
syntax : new AspectTarioListener(c)
or new AspectRatioListener(c,size)
where c is the component, and size is the original size of it. */
public class AspectRatioListener implements ComponentListener {
private double ratio;
private Dimension previous;
private Container victim;
public AspectRatioListener(Container c){
victim = c;
previous = (Dimension) c.getSize().clone();
ratio = 1.0*c.getSize().width/c.getSize().height;
}
public AspectRatioListener(Container c, Dimension size){
victim = c;
previous = (Dimension) size.clone();
ratio = 1.0*size.width/size.height;
}
public void componentResized(ComponentEvent e) {
int width = victim.getWidth();
int height = victim.getHeight();
// check if the height or width should be adjusted.
if (!(previous.equals(victim.getSize()))){
if ((width > previous.width) ||
(height > previous.height)){
if ((0.1*height/previous.height)>(0.1*width/previous.width))
width = (int) (ratio*height);
else
height = (int) (width/ratio);
}
else{
if ((0.1*width/previous.width)<(0.1*height/previous.height))
height = (int) (width/ratio);
else
width = (int) (ratio*height);
}
previous = new Dimension(width,height);
victim.setSize(width,height);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import jpwr.rt.Mh;
import jpwr.rt.MhrEvent;
/* This class is used to make sure an EventTableModel in a JaTable is presented
* in a graphically appealing manner. */
public class EventTableCellRender extends DefaultTableCellRenderer
{
Color ALarmColor = Color.red;
Color BLarmColor = Color.yellow;
Color CLarmColor = Color.blue;
Color DLarmColor = Color.cyan;
Color InfoColor = Color.green;
/**
* Gets the tableCellRendererComponent attribute of the
* EventTableCellRender object
*
*@param table Description of the Parameter
*@param value Description of the Parameter
*@param isSelected Description of the Parameter
*@param hasFocus Description of the Parameter
*@param row Description of the Parameter
*@param column Description of the Parameter
*@return The tableCellRendererComponent value
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
//I will assume that the number is stored as a string. if it is stored as an Integer, you can change this easily.
//if(column == 0)
//{
String number = (String)value;
//cast to a string
//int val = Integer.parseInt(number);//convert to an integer
MhrEvent ev = ((EventTableModel)table.getModel()).getRowObject(row);
this.setBackground(Color.white);
if(ev == null)
{
this.setText(" ");
return this;
}
boolean setColor = false;
if( ev.eventType == Mh.mh_eEvent_Alarm||ev.eventType == Mh.mh_eEvent_Info )
setColor = true;
//System.out.println("i eventTable.getTableCellRendererComponent(row " + row + "value" + number + ")");
if(number.compareTo("A") == 0)
{
if(setColor)
{
this.setBackground(ALarmColor);
}
this.setText("A");
}
else if(number.compareTo("B") == 0)
{
if(setColor)
{
this.setBackground(BLarmColor);
}
this.setText("B");
}
else if(number.compareTo("C") == 0)
{
if(setColor)
{
this.setBackground(CLarmColor);
}
this.setText("C");
}
else if(number.compareTo("D") == 0)
{
if(setColor)
{
this.setBackground(DLarmColor);
}
this.setText("D");
}
//annars mste det vara ett meddelande qqq??
else
{
if(setColor)
{
this.setBackground(InfoColor);
}
this.setText(" ");
}
//}
//else
// this.setBackground(Color.white);
return this;
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.Mh;
import jpwr.rt.MhData;
import jpwr.rt.MhrEvent;
/* The EventTableModel is an AbstractTableModel designed to keep the
*result from a search made with the AlertSearch engine. The result
*to present is contained in the MhData mhdata.*/
class EventTableModel extends AbstractTableModel
{
MhData mhData = new MhData(0,100);
String[][] columnNamesEventTable = {{"Prio","","Time","Description text","Event name"},{"P",
"Typ",
"Tid",
"Hndelsetext",
"Objekt"}};
int lang;
public final Object[] longValues = {"A", "Kvittens",
"10-12-31 12:12:12.98",
"QWERTYUIOPLK_JHGFDSAZXCVBNM__POIUYTRQWERTYUIOPL",
"QWERTYUIOPLK"};
/**
* Constructor for the EventTableModel object
*/
public EventTableModel() { lang=0; }
// constructor with language support
public EventTableModel(int l) { lang=l; }
/**
* Gets the columnCount attribute of the EventTableModel object
*
*@return The columnCount value
*/
public int getColumnCount()
{
return columnNamesEventTable[lang].length;
}
/**
* Gets the rowCount attribute of the EventTableModel object
*
*@return The rowCount value
*/
public int getRowCount()
{
return mhData.getNrOfEvents();//eventData.size();
}
/**
* Gets the columnName attribute of the EventTableModel object
*
*@param col Description of the Parameter
*@return The columnName value
*/
public String getColumnName(int col)
{
return (String)columnNamesEventTable[lang][col];
}
/**
* Gets the valueAt attribute of the EventTableModel object
*
*@param row Description of the Parameter
*@param col Description of the Parameter
*@return The valueAt value
*/
public Object getValueAt(int row, int col)
{
try
{
MhrEvent ev = mhData.getEvent(row);//(MhrEvent)eventData.get(row);
if(col == 0)
{
//System.out.println("col == 0 i eventTable.getValueAt()");
if(ev.eventPrio == Mh.mh_eEventPrio_A)
{
return "A";
}
if(ev.eventPrio == Mh.mh_eEventPrio_B)
{
return "B";
}
if(ev.eventPrio == Mh.mh_eEventPrio_C)
{
return "C";
}
if(ev.eventPrio == Mh.mh_eEventPrio_D)
{
return "D";
}
else
{
return "U";
}
}
if(col == 1)
{
String returnString = " ";
switch (ev.eventType)
{
case Mh.mh_eEvent_Alarm:
returnString = "Larm";
break;
case Mh.mh_eEvent_Ack:
returnString = "Kvittens";
break;
case Mh.mh_eEvent_Block:
returnString = "Block";
break;
case Mh.mh_eEvent_Cancel:
returnString = "Cancel";
break;
case Mh.mh_eEvent_CancelBlock:
returnString = "CancelBlock";
break;
case Mh.mh_eEvent_Missing:
returnString = "Missing";
break;
case Mh.mh_eEvent_Reblock:
returnString = "Reblock";
break;
case Mh.mh_eEvent_Return:
returnString = "Retur";
break;
case Mh.mh_eEvent_Unblock:
returnString = "Unblock";
break;
case Mh.mh_eEvent_Info:
returnString = "Info";
break;
case Mh.mh_eEvent_:
returnString = "?";
break;
default:
returnString = " ";
break;
}
return returnString;
}
if(col == 2)
{
return ev.eventTime;
}
if(col == 3)
{
return ev.eventText;
}
if(col == 4)
{
return ev.eventName;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
if(col == 1)
{
return new Boolean(false);
}
}
return "FEEELLLL";
}
/**
* Gets the columnClass attribute of the EventTableModel object
*
*@param c Description of the Parameter
*@return The columnClass value
*/
public Class getColumnClass(int c)
{
return longValues[c].getClass();
//return getValueAt(0, c).getClass();
}
/**
* Sets the valueAt attribute of the EventTableModel object
*
*@param value The new valueAt value
*@param row The new valueAt value
*@param col The new valueAt value
*/
public void setValueAt(Object value, int row, int col)
{
//alarmData[row][col] = value;
// fireTableCellUpdated(row, col);
}
/**
* Gets the rowObject attribute of the EventTableModel object
*
*@param row Description of the Parameter
*@return The rowObject value
*/
public MhrEvent getRowObject(int row)
{
try
{
return mhData.getEvent(row);//(MhrEvent)eventData.get(row);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("eventable.getRowObject " + e.toString());
}
return null;
}
/**
* Description of the Method
*/
public void rowInserted()
{
fireTableRowsInserted(0, 0);
}
/**
* Description of the Method
*
*@param row Description of the Parameter
*/
public void rowRemoved(int row)
{
fireTableRowsDeleted(row, row);
}
/**
* Description of the Method
*/
public void reloadTable()
{
fireTableStructureChanged();
}
/**
* Description of the Method
*/
public void updateTable()
{
fireTableDataChanged();
}
public void setMhData(MhData data)
{
mhData=data;
updateTable();
}
}
......@@ -16,7 +16,7 @@ public class GeComponent extends JComponent implements GeComponentIfc,
public JopEngine en;
public GeDyn dd = new GeDyn( this);
public int level;
Timer timer = new Timer(100, this);
public Timer timer = new Timer(100, this);
StringBuffer sb = new StringBuffer();
public JopSession session;
public GeComponent component = this;
......@@ -75,6 +75,8 @@ public class GeComponent extends JComponent implements GeComponentIfc,
if ( (dd.actionType & GeDyn.mActionType_Slider) != 0) {
this.addMouseMotionListener( new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if ( actionDisabled)
return;
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0 &&
en.gdh.isAuthorized( dd.access))
dd.action( GeDyn.eEvent_SliderMoved, e);
......@@ -110,6 +112,8 @@ public class GeComponent extends JComponent implements GeComponentIfc,
public void setLevelColorTone( int levelColorTone) { this.levelColorTone = levelColorTone;}
public void setLevelFillColor( int levelFillColor) { this.levelFillColor = levelFillColor;}
boolean actionDisabled = false;
public void setActionDisabled( boolean actionDisabled) { this.actionDisabled = actionDisabled;}
public String annot1 = new String();
public Font annot1Font = new Font("Helvetica", Font.BOLD, 14);
public void setAnnot1Font( Font font) { annot1Font = font;}
......
......@@ -24,4 +24,5 @@ public interface GeComponentIfc {
public int setPreviousPage();
public Object getDd();
public void repaintForeground();
public Object dynamicGetRoot();
}
......@@ -27,10 +27,16 @@ public class GeFrameThin extends GeComponent {
g.setTransform(save);
}
}
float original_width = 0;
float original_height = 0;
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
float width = getWidth();
float height = getHeight();
if ( original_width == 0)
original_width = width;
if ( original_height == 0)
original_height = height;
AffineTransform save = g.getTransform();
AffineTransform save_tmp;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
......@@ -42,6 +48,7 @@ public class GeFrameThin extends GeComponent {
shapes[3] = new Line2D.Float(width - 2F, height - 2F, width - 2F, 2F);
}
/*
if ( 45.0 <= rotate && rotate < 135.0) {
g.translate( width, 0.0);
g.rotate( Math.PI * rotate/180, 0.0, 0.0);
......@@ -59,6 +66,29 @@ public class GeFrameThin extends GeComponent {
g.transform( AffineTransform.getScaleInstance( height/width,
width/height));
}
*/
if ( 45.0 <= rotate && rotate < 135.0) {
g.translate( width, 0.0);
g.rotate( Math.PI * rotate/180, 0.0, 0.0);
g.transform( AffineTransform.getScaleInstance( height/original_width,
width/original_height));
}
else if ( 135.0 <= rotate && rotate < 225.0)
{
g.rotate( Math.PI * rotate/180, width/2, height/2);
g.transform( AffineTransform.getScaleInstance( width/original_width,
height/original_height));
}
else if ( 225.0 <= rotate && rotate < 315.0)
{
g.translate( -height, 0.0);
g.rotate( Math.PI * rotate/180, height, 0.0);
g.transform( AffineTransform.getScaleInstance( height/original_width,
width/original_height));
}
else
g.transform( AffineTransform.getScaleInstance( width/original_width,
height/original_height));
g.setStroke( new BasicStroke(1F));
g.setColor(GeColor.getColor(78, colorTone,
......
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class HistDateChooser extends JPanel implements ActionListener{
private Calendar date;
SpinnerDateModel yearModel;
private JComboBox month;
private JSpinner year, hour, minute, second;
private JPanel dayGrid = new JPanel();
private JPanel timeGrid = new JPanel();
private int selectedDay;
private int lang =0;
private String[][] months = {{"January", "February", "March", "April", "May", "June", "July"
,"August", "September", "October","November", "December"},
{"januari", "februari", "mars", "april", "maj", "juni", "juli"
,"augusti", "september", "oktober","november", "december"}};
private String[][] days = {{"Mon","Tue","Wed","Thu","Fri","Sat","Sun"},
{"Mn","Tis","Ons","Tor","Fre","Lr","Sn"}};
private String[][] time = {{"Hour","Minute","Second"},{"Timme","Minut","Sekund"}};
public HistDateChooser(){
date = Calendar.getInstance();
init();
}
public HistDateChooser(int l){
lang=l;
date = Calendar.getInstance();
init();
}
public HistDateChooser(Calendar Cal,int l){
lang=l;
date = (Calendar) Cal.clone();
init();
}
private void init(){
selectedDay=date.get(Calendar.DAY_OF_MONTH);
month = new JComboBox(months[lang]);
month.setSelectedIndex(date.get(Calendar.MONTH));
yearModel = new SpinnerDateModel();
yearModel.setValue(date.getTime());
yearModel.setCalendarField(Calendar.YEAR);
year = new JSpinner(yearModel);
year.setEditor(new JSpinner.DateEditor(year, "yyyy"));
this.setLayout(new BorderLayout());
this.add("North",year);
dayGrid.setLayout(new GridLayout(7,7));
month.addActionListener(this);
yearModel.addChangeListener( new YearChangeListener());
this.add("Center",dayGrid);
this.add("West",month);
hour=new JSpinner(new SpinnerNumberModel(date.get(Calendar.HOUR_OF_DAY),0,23,1));
minute=new JSpinner(new SpinnerNumberModel(date.get(Calendar.MINUTE),0,59,1));
second=new JSpinner(new SpinnerNumberModel(date.get(Calendar.SECOND),0,59,1));
setupTimeGrid();
this.add("South",timeGrid);
updateGrid();
}
public Calendar getDate(){
updateDate();
return date;
}
private void updateDate(){
date.setTime(yearModel.getDate());
date.set(Calendar.MONTH,month.getSelectedIndex());
date.set(Calendar.DAY_OF_MONTH,selectedDay);
date.set(Calendar.HOUR_OF_DAY,((Integer)hour.getValue()).intValue());
date.set(Calendar.MINUTE,((Integer)minute.getValue()).intValue());
date.set(Calendar.SECOND,((Integer)second.getValue()).intValue());
}
private void updateGrid(){
updateDate();
dayGrid.removeAll();
int i;
for (i=0;i<7;i++) dayGrid.add(new JLabel(days[lang][i],JLabel.CENTER));
Calendar temp =(Calendar) date.clone();
temp.set(Calendar.DAY_OF_MONTH,1);
int startDay = temp.get(Calendar.DAY_OF_WEEK)-Calendar.MONDAY;
if (startDay<0) startDay=6;
for (i=0;i<startDay;i++) dayGrid.add(new JLabel(""));
for (i=1;i<=date.getActualMaximum(Calendar.DAY_OF_MONTH);i++) {
JButton day = new JButton(String.valueOf(i));
day.addActionListener(this);
if (i==selectedDay)
day.setEnabled(false);
dayGrid.add(day);
}
for (i=startDay+date.getActualMaximum(Calendar.DAY_OF_MONTH)+1;i<42;i++) dayGrid.add(new Label(""));
repaint();
validate();
}
private void setupTimeGrid(){
timeGrid.setLayout(new GridLayout(3,3));
for (int i=0; i<3; i++){
timeGrid.add(new JLabel(""));
}
for (int i=0; i<3; i++){
timeGrid.add(new JLabel(time[lang][i],JLabel.CENTER));
}
timeGrid.add(hour);
timeGrid.add(minute);
timeGrid.add(second);
}
public void actionPerformed(ActionEvent e){
if (e.getSource().getClass() == (new JButton()).getClass()){
try{
JButton pressed = (JButton) e.getSource();
selectedDay = (new Integer(pressed.getText())).intValue();
}
catch (Exception ex) {
System.out.println("Error:" + ex);
}
}
updateGrid();
}
private class YearChangeListener implements ChangeListener{
public void stateChanged(ChangeEvent e){
updateGrid();
}
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import jpwr.rt.*;
import java.applet.Applet;
//XLS import netscape.javascript.*;
// Import of netscape.javascript.* from jaws.jar is needed !!!
/* HistSearch is a search engine for performing searches from the historic
*event list. It's mainly a GUI for getting input on the criteria on which
*the search should be based, launching the search and presenting the result.
*It uses a HistTable called result for presenting the search result.
*The HistQuery currentSearch is set to the criteria chosen via the GUI when
*the JButton btnSearch is pressed and currentSearch is then sent to a class
*in the HistTable result for evaluating the search and updating the table.
*The GUI is made to support English and Swedish by keeping arrays of all
*strings. The integer lang indicates which language to be used, (0=eng
*1=swe) and all texts on screen is updated at once by calling updateText().
*/
public class HistSearch extends JFrame implements ActionListener
{
public JopEngine engine;
public JopSession session;
public Object root;
;
/*integers for keeping track of the language setting and the number of
search results.*/
int lang=1;
int num=0;
JPanel contentPane;
// ****TOP****
//top contains the search interface
JPanel top = new JPanel();
//check contains the arrays of checkboxes
JPanel check = new JPanel();
// labels describing different objects in the search interface.
JLabel lblStart = new JLabel("", JLabel.LEFT);
JLabel lblStop = new JLabel("", JLabel.LEFT);
JLabel lblType = new JLabel("", JLabel.LEFT);
JLabel lblPriority = new JLabel("", JLabel.LEFT);
JLabel lblName = new JLabel("", JLabel.LEFT);
JLabel lblText = new JLabel("", JLabel.LEFT);
JLabel lblNum = new JLabel("",JLabel.LEFT);
String[] descStart = {"Start time:","Starttid:"};
String[] descStop = {"Stop time:","Stopptid:"};
String[] descType = {"Event type:","Hndelsetyp:"};
String[] descPriority = {"Priority:","Prioritet:"};
String[] descName = {"Event name:","Hndelsenamn:"};
String[] descText = {"Event text:","Hndelsetext:"};
String[] descStat = {"Statistics", "Statistik"};
// textfields for different parameters in the search interface
JTextField txStart,txStop,txName,txText;
// cbWhen is a combo box giving choices of search intervals
String[][] choice = {{"All alarms","This year","This month","This week","Today","Enter dates"},
{"Alla alarm","Detta r","Denna mnad","Den hr veckan","Idag","Egna datum"}};
JComboBox cbWhen ;
// type is an array of radiobuttons, one for each type of event
JCheckBox[] type = new JCheckBox[4];
String[][] nameType = {{"Active","Message","Return","Ack"},
{"Aktiv","Meddelande","Retur","Kvittens"}};
// priority is an array of checkboxes, one for each priority
JCheckBox[] priority = new JCheckBox[4];
String[] namePriority = {"A-Alarm","B-Alarm","C-Alarm","D-Alarm"};
// btnSearch is the search button
JButton btnSearch ;
String[] descSearch= {"Search","Sk"};
// two calendars for start and stop dates
Calendar calStop,calStart;
String defaultDate="YYYY-MM-DD HH:MM:SS";
String[] strNum={"Number of events: ","Antal hndelser: "};
String[] msgStart={"Enter start date and time","Ange startdatum och tid"};
String[] msgStop={"Enter stop date and time","Ange stoppdatum och tid"};
String[] errorDate={"Dates must be specified on the form YYYY-MM-DD HH:MM:SS \n"+
"e.g 1980-09-08 00:00:00", "Datum mste skrivas p formen YYYY-MM-DD HH:MM:SS \n"+
"t.ex 1980-09-08 00:00:00"};
/**** Menu + textstrings ****/
JMenu fileMenu, langMenu;
String[][] menuTitle = {{"File","Byt Sprk"},{"Arkiv","Change Language"}};
String[][] fileItems = {{"Copy result to excel","Quit"},{"Kopiera resultat till Excel","Avsluta"}};
String[][] langItems = {{"Svenska","English"},{"Svenska","English"}};
//****MIDDLE****
//middle contains the search condition and the search result.
JPanel middle = new JPanel();
//resultTable is the HistTable containing the search results.
HistTable result;
// result contains the table showing the search result.
//JTable result = new JTable(resultTable);
// lblCondition is the label showing the current search conditions.
JLabel lblCondition = new JLabel("",JLabel.LEFT);
// lblHead is the label showing the static text "Search condition"
JLabel lblHead = new JLabel("", JLabel.LEFT);
String[] descHead = {"<HTML><U>Search condition</U></HTML>",
"<HTML><U>Skvillkor</U></HTML>"};
HistQuery currentSearch;
public JButton btnStat;
class WindowExit extends WindowAdapter{
public void windowClosing(WindowEvent ev){
}
}
void HistSearch_WindowClosing(WindowEvent event) {
dispose();
}
//Default constructor
public HistSearch(){
engine = new JopEngine( 1000, (Object)this);
session = new JopSession( engine, (Object)this);
root = (Object) this;
setup();
}
public HistSearch( JopSession s)
{
session = s;
engine = session.getEngine();
root = session.getRoot();
setup();
}
public HistSearch(String q , JopSession s)
{
session = s;
engine = session.getEngine();
root = session.getRoot();
setup();
txName.setText("*" + q + "*");
doSearch();
}
private void setup(){
result =new HistTable(lang,session);
/* A mouse listener is added to the alarmTable from here because
the result of the double click affects components of the HistSearch.
To add the listener like this avoids compilation order problems.*/
result.alarmTable.addMouseListener(new MouseAdapter() {
/***** MOUSE LISTENER CODE START *****/
//Bring up a JopMethodsMenu
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=result.alarmTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) result.atModel.mhData.eventVec.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) result.alarmTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
int row=result.alarmTable.rowAtPoint(e.getPoint());
result.alarmTable.setRowSelectionInterval(row,row);
if ( e.isPopupTrigger()) {
MhrEvent event = (MhrEvent) result.atModel.mhData.eventVec.get(row);
String trace_object= event.eventName;
new JopMethodsMenu(session,
trace_object,
JopUtility.TRACE,(Component) result.alarmTable,
e.getX(), e.getY());
return;
}
}
//On double click copy name or text to corresponding textfields.
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
String tempStr="";
int row=result.alarmTable.rowAtPoint(e.getPoint());
if(result.alarmTable.columnAtPoint(e.getPoint())==3){
if (txText.getText().length() > 0)
tempStr=txText.getText() + ";";
tempStr=tempStr + "*" +
(String)result.alarmTable.getValueAt(row,3) + "*";
txText.setText(tempStr);
}
else{
if (txName.getText().length() > 0 )
tempStr=txName.getText() + ";";
tempStr=tempStr + "*" +
(String)result.alarmTable.getValueAt(row,4) + "*";
txName.setText(tempStr);
}
}
}
/**** MOUSE LISTENER CODE STOP ****/
});
addWindowListener(new WindowExit());
addComponentListener(new minSizeListener(this));
this.setTitle("Hist Search");
// setup the searchbutton
btnSearch= new JButton(descSearch[lang]);
btnSearch.addActionListener(this);
btnSearch.setActionCommand("search");
btnSearch.setMnemonic('s');
// setup the statisticsbutton
btnStat= new JButton(descStat[lang]);
btnStat.setMnemonic('t');
btnStat.setActionCommand("stat");
btnStat.addActionListener(this);
//setup tht combobox.
cbWhen=new JComboBox(choice[lang]);
cbWhen.addActionListener(this);
//setup the start and stop dates.
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.YEAR,1970);
// setup the array of checkboxes
checkSetup();
//make sure all buttons and labels have text.
menuSetup();
updateText();
place();
//set comboBox to "thisYear" by deafult. setSelectedItem calls
//the action listener, so the dates update.
cbWhen.setSelectedItem(cbWhen.getItemAt(1));
updateDate();
}
//Place all onscreen objects
private void place(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(new BorderLayout());
middleSetup();
topSetup();
contentPane.add("North",top);
contentPane.add("Center",middle);
contentPane.add("South",btnStat);
}
private void menuSetup(){
// set up the menu structure, with language choices.
this.setJMenuBar (new JMenuBar());
fileMenu=new JMenu(menuTitle[lang][0]);
fileMenu.setMnemonic(fileMenu.getText().charAt(0));
langMenu=new JMenu(menuTitle[lang][1]);
langMenu.setMnemonic(langMenu.getText().charAt(0));
for(int i=0; i< fileItems.length; i++){
JMenuItem item = new JMenuItem(fileItems[lang][i]);
item.addActionListener(this);
item.setMnemonic(item.getText().charAt(0));
fileMenu.add(item);
}
for(int i=0; i< langItems.length; i++){
JMenuItem item = new JMenuItem(langItems[lang][i]);
item.addActionListener(this);
item.setMnemonic(item.getText().charAt(0));
langMenu.add(item);
}
this.getJMenuBar().add(fileMenu);
this.getJMenuBar().add(langMenu);
}
private void middleSetup(){
//Setup the layout for the middle part of the screen.
middle.setLayout(new BorderLayout());
JPanel condition = new JPanel();
condition.setLayout(new BorderLayout());
condition.add("North",lblHead);
Dimension d = lblCondition.getSize();
d.height +=80;
lblCondition.setPreferredSize(d);
condition.add("Center", lblCondition);
middle.add("North",condition);
d = result.getSize();
result.setPreferredSize(d);
middle.add("Center", result);
}
private void topSetup(){
GridBagLayout topLayout = new GridBagLayout();
GridBagConstraints topC = new GridBagConstraints();
top.setLayout(topLayout);
// 1st row
topC.gridx=0;
topC.gridy=0;
topC.weightx=0;
topC.fill=GridBagConstraints.BOTH;
topC.anchor=GridBagConstraints.CENTER;
topC.insets= new Insets(2,2,5,5);
// Start time label
topLayout.setConstraints(lblStart, topC);
top.add(lblStart);
// Start time textfield
topC.gridx=1;
topC.weightx=1;
txStart = new JTextField (defaultDate);
txStart.setEditable(false);
txStart.setColumns(19);
topLayout.setConstraints(txStart, topC);
top.add(txStart);
//Stop time label
topC.gridx=2;
topC.weightx=0;
topLayout.setConstraints(lblStop, topC);
top.add(lblStop);
//Stop time textfield
topC.gridx=3;
topC.weightx=1;
topC.gridwidth=GridBagConstraints.RELATIVE;
txStop = new JTextField (defaultDate);
txStop.setEditable(false);
txStop.setColumns(19);
topLayout.setConstraints(txStop, topC);
top.add(txStop);
//Search interval combobox.
topC.gridx=4;
topC.gridwidth=GridBagConstraints.REMAINDER;
topLayout.setConstraints(cbWhen, topC);
top.add(cbWhen);
// 2nd & 3rd rows
// add the array of check boxes
topC.gridx=0;
topC.gridy=1;
topC.weightx=0;
topC.gridwidth=4;
topC.gridheight=2;
topLayout.setConstraints(check, topC);
top.add(check);
// 4th row
topC.gridx=0;
topC.gridy=3;
topC.gridwidth=1;
topC.gridheight=1;
// Event name time label
topLayout.setConstraints(lblName, topC);
top.add(lblName);
//Event name textfield
topC.gridx=1;
topC.gridwidth=GridBagConstraints.REMAINDER;
txName = new JTextField();
topLayout.setConstraints(txName, topC);
top.add(txName);
// 5th row
topC.gridx=0;
topC.gridy=4;
topC.gridwidth=1;
// Event name time label
topLayout.setConstraints(lblText, topC);
top.add(lblText);
//Event name textfield
topC.gridx=1;
topC.gridwidth=GridBagConstraints.REMAINDER;
txText = new JTextField();
topLayout.setConstraints(txText, topC);
top.add(txText);
// 6th row
topC.gridx=0;
topC.gridy=5;
topC.gridwidth=1;
// Number of events label
updateNum();
topLayout.setConstraints(lblNum, topC);
top.add(lblNum);
//The search button
topC.gridx=2;
topLayout.setConstraints(btnSearch, topC);
top.add(btnSearch);
}
private void checkSetup(){
// make the layout of the checkbox array a GridLayout. Add the event Type label.
check.setLayout(new GridLayout(2,5));
check.add(lblType);
//For loop adding the four type checkboxes with name tags
for (int i=0;i<4;i++){
type[i]=new JCheckBox(nameType[lang][i]);
check.add(type[i]);
}
// Add the Event priority label
check.add(lblPriority);
//For loop adding the four priority checkboxes with name tags.
for (int i=0;i<4;i++){
priority[i]=new JCheckBox(namePriority[i]);
check.add(priority[i]);
}
}
//Update the number of events label in the correct language.
private void updateNum(){
num=result.getNrOfResults();
lblNum.setText(strNum[lang]+num);
}
// All labels are updated in the current language (0 = English, 1 = Swedish)
private void updateText(){
// the combo box needs to be relableled according to language
// but not during initiation, hence the if statement...
if(txStart!=null){
cbWhen.removeAllItems();
for(int i=0;i<choice[lang].length;i++)
cbWhen.addItem(choice[lang][i]);
}
// the search button needs to be relabeled each time the language changes
btnSearch.setText(descSearch[lang]);
/*the checkboxes for type needs relabeling aswell. Not the priority checkboxes
since there's no difference in language...*/
for(int i=0; i<nameType[lang].length;i++){
type[i].setText(nameType[lang][i]);
}
// All labels are updated to show the right language.
lblStart.setText(descStart[lang]);
lblStop.setText(descStop[lang]);
lblType.setText(descType[lang]);
lblPriority.setText(descPriority[lang]);
lblName.setText(descName[lang]);
lblText.setText(descText[lang]);
lblHead.setText(descHead[lang]);
updateNum();
//Update the text in the menus. Easily done by remaking it...
menuSetup();
//update the result table headers
result.updateLang(lang);
//update the btnStat text.
btnStat.setText(descStat[lang]);
}
private void updateDate(){
txStart.setText(dateText(calStart));
txStop.setText(dateText(calStop));
}
// Update the text in the Start & Stop Textfields. Adjust x<10 to 0x
private String dateText(Calendar cal){
String text=""+cal.get(Calendar.YEAR)+"-";
if(cal.get(Calendar.MONTH)<9) text = text + "0";
text = text + (cal.get(Calendar.MONTH)+1)+"-";
if(cal.get(Calendar.DATE)<10) text = text + "0";
text = text +cal.get(Calendar.DATE)+" ";
if(cal.get(Calendar.HOUR_OF_DAY)<10) text = text +"0";
text = text+ cal.get(Calendar.HOUR_OF_DAY)+":";
if(cal.get(Calendar.MINUTE)<10) text = text +"0";
text = text +cal.get(Calendar.MINUTE)+":";
if(cal.get(Calendar.SECOND)<10) text = text + "0";
text = text + cal.get(Calendar.SECOND);
return text;
}
/* the action listener methods of this object. Checks on ComboBox, searchbutton
and menu options */
public void actionPerformed(ActionEvent e){
if (e.getSource()==cbWhen){
switch(cbWhen.getSelectedIndex()){
//all entries
case 0:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.YEAR,1970);
updateDate();
break;
//this year
case 1:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.MONTH,0);
calStart.set(Calendar.DATE,1);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//this month
case 2:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.DATE,1);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//this week
case 3:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
int diff = calStart.get(Calendar.DAY_OF_WEEK)-Calendar.MONDAY;
calStart.add(Calendar.DATE,-1*diff);
if (diff<0) calStart.add(Calendar.DATE,-7);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//today
case 4:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//enter dates
case 5:
//routine for Start time input dialog
HistDateChooser tempDate = new HistDateChooser(calStart,lang);
int buttonPressed = JOptionPane.showOptionDialog(this,tempDate,msgStart[lang],JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,null,null);
if (buttonPressed == JOptionPane.OK_OPTION){
calStart=tempDate.getDate();
//routine for Stop time input dialog
tempDate = new HistDateChooser(calStop,lang);
buttonPressed = JOptionPane.showOptionDialog(this,tempDate,msgStop[lang],JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,null,null);
if (buttonPressed == JOptionPane.OK_OPTION){
calStop=tempDate.getDate();
}
}
updateDate();
break;
default:
updateDate();
break;
}
}
// Handling of search button event.
if(e.getActionCommand()=="search"){
doSearch();
}
if (e.getActionCommand()=="stat"){
result.presentStat();
}
// the handling of menu events
if(e.getActionCommand()=="Copy result to excel"||e.getActionCommand()=="Kopiera resultat till Excel"){
// check if the root is an applet
try{
Applet source = (Applet) root;
/* //XLS Method for exporting an excel file from an applet
// Uses a javascript from the page that started the applet.
JSObject javaScript = JSObject.getWindow(source);
if (javaScript != null){
Object[] args = new Object[1];
args[0]=result.exportExcelFromApplet();
javaScript.call("appletHtml", args);
} */
}
catch(Exception ex){
//No applet, copy to system clipboard.
result.exportExcel();
}
}
if(e.getActionCommand()=="Quit"||e.getActionCommand()=="Avsluta"){
this.dispose();
}
if(e.getActionCommand()=="Svenska"){
lang=1;
updateText();
}
if(e.getActionCommand()=="English"){
lang=0;
updateText();
}
}
private void doSearch(){
lblCondition.setFont(new Font("SansSerif", Font.PLAIN, 14));
lblCondition.setForeground(new Color(0x000000));
lblCondition.setText(evalSearch(lang));
lblCondition.validate();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
result.performSearch(root,currentSearch);
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
updateNum();
}
// Returns a string showing all search criteria and sets the currentSearch
public String evalSearch(int lang){
//Useful words in english and swedish.
String[][] words ={{"All ", " Active", " Message", " Return", " Acknowlegement", " events"," with"," priority"," name"," text", " from "," to "," or"},
{"Alla", " Aktiv", " Meddelande", " Retur", " Kvittens", " hndelser"," med"," prioritet"," namn"," text", " fr.o.m. ", " t.o.m. ", " eller"}};
String eval="<html>" + words[lang][0];
String temp="";
boolean[] noCheck ={true,true};
boolean[] typeSelected = {false,false,false,false};
boolean[] prioSelected = {false,false,false,false};
for (int i=0;i<4;i++){
if (type[i].isSelected()){
typeSelected[i]=true;
if (noCheck[0]) noCheck[0]=false;
else eval=eval+words[lang][12];
eval=eval + "<b>" +words[lang][i+1] + "</b>";
}
if (priority[i].isSelected()){
prioSelected[i]=true;
if (noCheck[1]) noCheck[1]=false;
else temp=temp+words[lang][12];
int charA =(int)'A';
charA=charA+i;
temp=temp + " <b>" + (char) charA + "</b>";
}
}
eval= eval + words[lang][5] + " ";
if (temp.length()>0) {
eval=eval+ words[lang][6] + temp + words[lang][7] ;
}
eval=eval+"<br>"+words[lang][6]+words[lang][8]+" <b>"+txName.getText() +"</b><br>";
eval=eval+words[lang][6]+words[lang][9]+" <b>"+txText.getText() +"</b><br>";
eval=eval + words[lang][10] + "<b>"+ dateText(calStart)+ "</b>" + words[lang][11] + "<b>" + dateText(calStop)+"</b> </html>";
String nameFormatted= txName.getText().replace('"','*');
String textFormatted= txText.getText().replace('"','*');
//Setup the current search for transfer to server
currentSearch=new HistQuery(dateText(calStart), dateText(calStop),typeSelected,prioSelected,nameFormatted,textFormatted);
return eval;
}
public class minSizeListener implements ComponentListener {
static final int MIN_WIDTH=600;
static final int MIN_HEIGHT=480;
private HistSearch as;
public minSizeListener(HistSearch a){
as=a;
}
public void componentResized(ComponentEvent e) {
int width = as.getWidth();
int height = as.getHeight();
boolean resize=false;
//we check if either the width
//or the height are below minimum
if (width < MIN_WIDTH) {
width = MIN_WIDTH;
resize=true;
}
if (height < MIN_HEIGHT) {
height = MIN_HEIGHT;
resize=true;
}
if (resize)
as.setSize(width, height);
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
//Testprogram
public static void main(String args[]){
HistSearch ASWindow = new HistSearch();
ASWindow.pack();
ASWindow.show();
}
}
package jpwr.jop;
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.Vector;
import jpwr.rt.*;
/* The HistSender initiates a socket to the server and can then perform a
*SearchRequest given a HistQuery using an ObjectInput- and an
*ObjectOutputStream.*/
public class HistSender {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
Object root;
final static int PORT = 4447;
public HistSender(Object r){
root=r;
setup();
}
// initiate the socket to the server
private void setup(){
try {
URL url;
String urlString = "192.168.60.16";
try {
url = ((JApplet)root).getCodeBase();
if(url != null)
urlString = url.getHost();
}
catch(Exception e)
{
System.out.println("Program not run from applet..."+e);
}
socket = new Socket(urlString, PORT);
}
catch(UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
//System.exit(1);
}
catch(IOException e) {
JOptionPane.showMessageDialog(null,"Couldn't get contact with the server (HistServer). \n Kunde inte ansluta till servern(HistServer).","I/O Error",JOptionPane.ERROR_MESSAGE);
}
}
public MhData SearchRequest(HistQuery search){
// Open output and input streams.
try
{
out = new ObjectOutputStream( socket.getOutputStream() );
out.flush();
//varfr???
in = new ObjectInputStream( socket.getInputStream() );
}
catch(Exception e)
{
System.out.println("IOException vid skapande av strmmar mot server");
//errh.error("DataStream failed");
return new MhData(100,100);
}
//Send search request
try
{
out.writeObject(search);
out.flush();
}
catch(Exception e)
{
System.out.println("Search send Exception");
}
// Start receiving data
MhData answer = new MhData(0,0);
try
{
MhrEvent[] result = (MhrEvent[])in.readObject();
int i = 0;
while(i < result.length)
{
answer.addMessToVectorInSortedOrder(answer.eventVec, result[i++]);
}
}
catch(Exception e) {
System.out.println("#"+e.toString());
}
//Close input and output streams
try
{
in.close();
out.close();
}
catch(Exception e)
{
System.out.println("Error while closing streams: " + e);
}
return answer;
}
}
package jpwr.jop;
import java.util.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.*;
/*The HistStatModel1 class is used to derive how many times an Alarm has been
set off during the interval of the search provided in a MhData.*/
public class HistStatModel1 extends AbstractTableModel{
// The List storing the resulting statistics.
public List result;
private String[][] freqNames={{"Object", "Nr. of alarms" },{"Objekt","Antal larm"}};
int lang;
public HistStatModel1(MhData m, int l ){
lang=l;
clearData();
setData(m);
sortData();
}
public void clearData(){
result = new ArrayList();
}
public void setData(MhData m){
/* The MhData is Stepped through. If an Alarm is found which eventName
is not yet present in the result List, a copy of the Alarm's
MhrEvent is added to the result List. If an alarm is found that is
present in the result List the nr of times the alarm has been found
is increased by one. The nr of times is stored in the int
eventFlags of each MhrEvent in the result List*/
for(int i=0; i<m.eventVec.size();i++){
boolean found=false;
for (int j = 0; j<result.size();j++){
if (((MhrEvent) m.eventVec.get(i)).eventName.equals(((MhrEvent)(result.get(j))).eventName)){
if(((MhrEvent) m.eventVec.get(i)).eventType == Mh.mh_eEvent_Alarm){
((MhrEvent)(result.get(j))).eventFlags++;
found=true;
}
}
if (found) break;
}
if (! found){
if(((MhrEvent) m.eventVec.get(i)).eventType == Mh.mh_eEvent_Alarm){
result.add(((MhrEvent)(m.eventVec.get(i))).getCopy());
((MhrEvent)result.get(result.size()-1)).eventFlags=1;
}
}
}
}
public Object getValueAt(int r,int c){
if (c==0) return ((MhrEvent)result.get(r)).eventName;
else return new Integer(((MhrEvent)result.get(r)).eventFlags);
}
public int getRowCount(){
return result.size();
}
public int getColumnCount(){
return freqNames.length;
}
public String getColumnName(int i){
return freqNames[lang][i];
}
public void sortData(){
//sortData sorts the result List. Largest number of times found first.
Collections.sort(result, new Comparator(){
public int compare(Object o1, Object o2){
if (((MhrEvent)o1).eventFlags < ((MhrEvent)o2).eventFlags)
return 1;
else if (((MhrEvent)o1).eventFlags > ((MhrEvent)o2).eventFlags)
return -1;
else return 0;
}
});
}
}
package jpwr.jop;
import java.util.*;
import java.util.regex.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.*;
/* HistStatModel2 is an AbstractTableModel that derives information on the
duration of alarms (Active to Return) supplied in a MhData. Proper methods
for displaying the results as a table ar included aswell... */
public class HistStatModel2 extends AbstractTableModel{
// The List holding the statistics
List result;
private String[][] names={{"Object", "Duration time" },{"Objekt", "Varaktighet"}};
int lang;
//Constructor
public HistStatModel2(MhData m, int l ){
lang=l;
clearData();
setData(m);
sortData();
}
public void clearData(){
result = new ArrayList();
}
public void setData(MhData m){
/* All elements in the MhData eventVec are stepped through, looking for
Alarms. When one is found the rest are looked through, looking for a
matching Return (the Return's target.birthTime = the Alarm's
birthTime). If a matching Return is found the a copy of the alarm's
MhrEvent is stored in the result List with the int eventFlags used
as a storage for the duration time.*/
for(int i=m.eventVec.size()-1; i>0;i--){
boolean found=false;
int timeDiff=0;
if (((MhrEvent)m.eventVec.get(i)).eventType==Mh.mh_eEvent_Alarm){
for(int j=i-1; j>=0;j--){
if (((MhrEvent) m.eventVec.get(j)).targetId.birthTime.equals(((MhrEvent) m.eventVec.get(i)).eventId.birthTime))
if (((MhrEvent)m.eventVec.get(j)).eventType==Mh.mh_eEvent_Return){
found=true;
// The duration is calculated in seconds. The
//duration is limited to at most two months.
Pattern p = Pattern.compile("[\\s-:.]");
String[] stop=p.split(((MhrEvent) m.eventVec.get(j)).eventTime);
int month = new Integer(stop[1]).intValue();
int day = new Integer(stop[2]).intValue();
int hour = new Integer(stop[3]).intValue();
int minute = new Integer(stop[4]).intValue();
int second = new Integer(stop[5]).intValue();
int millis = new Integer(stop[6]).intValue();
String[] start=p.split(((MhrEvent) m.eventVec.get(i)).eventTime);
month -= new Integer(start[1]).intValue();
if (month > 0){
month = new Integer(stop[1].charAt(2)).intValue();
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day+=31;
break;
case 4:
case 6:
case 9:
case 11:
day+=30;
break;
case 2:
day+=28;
default:
break;
}
}
day = day - new Integer(start[2]).intValue();
hour = hour- new Integer(start[3]).intValue();
minute -= new Integer(start[4]).intValue();
second = second - new Integer(start[5]).intValue();
millis -= new Integer(start[6]).intValue();
timeDiff= second + 60*minute + 3600*hour +
3600*24*day;
}
if (found) break;
}
}
if (found){
result.add(((MhrEvent)m.eventVec.get(i)).getCopy());
((MhrEvent)result.get(result.size()-1)).eventFlags=timeDiff;
}
}
}
public Object getValueAt(int r,int c){
if (c==0) return ((MhrEvent)result.get(r)).eventName;
else {
int temp = ((MhrEvent)result.get(r)).eventFlags;
//Format a String showing the duration in days, hours, minutes
// and seconds.
String retString= "" + (temp/(3600*24)) + "D ";
temp = temp%(3600*24);
retString= retString + (temp/(3600)) + "H ";
temp = temp%(3600);
retString= retString + (temp/(60)) + "M ";
temp = temp%(60);
retString= retString + (temp) + "S " ;
return retString;
}
}
public int getRowCount(){
return result.size();
}
public int getColumnCount(){
return names.length;
}
public String getColumnName(int i){
return names[lang][i];
}
//sortData sorts the result List based on duration (the value of
//eventFlags).Longest duration on top.)
public void sortData(){
Collections.sort(result, new Comparator(){
public int compare(Object o1, Object o2){
if (((MhrEvent)o1).eventFlags < ((MhrEvent)o2).eventFlags) return 1;
else if (((MhrEvent)o1).eventFlags > ((MhrEvent)o2).eventFlags) return -1;
else return 0;
}
});
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
import jpwr.rt.*;
/* The HistStatistics class is a JPanel containing two JTables showing
statistics derived from the MhData supplied in the constructor. The tables
get their contents from a HistStatModel1 and an HistStatModel2. The tables support
the use of JopMethodsMenu.*/
public class HistStatistics extends JPanel{
// The session is needed for the use of JopMethodsMenu
private JopSession session;
private JTable fTable, eTable;
private HistStatModel1 fModel;
private HistStatModel2 eModel;
JScrollPane fScroll, eScroll;
int lang;
String[][] names = {{"Most frequent alarms","Longest duration"},{"Mest frekventa alarm","Lngst varaktighet"}};
public HistStatistics(MhData m, int l, JopSession s){
//Setup and layout. (The only method of this class..)
session = s;
lang=l;
this.setLayout(new GridLayout(2,1));
JPanel upper = new JPanel();
upper.setLayout(new BorderLayout());
fModel=new HistStatModel1(m,lang);
fTable = new JTable(fModel);
fScroll= new JScrollPane(fTable );
fTable.getColumnModel().getColumn(0).setPreferredWidth(420);
fTable.getColumnModel().getColumn(1).setPreferredWidth(70);
//Mouse listener for fTable JopMethodMenu support.
fTable.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=fTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) fModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) fTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=fTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) fModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) fTable,
e.getX(), e.getY());
return;
}
}
public void mouseClicked(MouseEvent e) {
}
});
upper.add(fScroll,BorderLayout.CENTER);
upper.add(new JLabel(names[lang][0]), BorderLayout.NORTH);
upper.add(new JLabel("\n\n") , BorderLayout.SOUTH);
JPanel lower = new JPanel();
lower.setLayout(new BorderLayout());
eModel=new HistStatModel2(m,lang);
eTable = new JTable(eModel);
eScroll= new JScrollPane(eTable );
eTable.getColumnModel().getColumn(0).setPreferredWidth(420);
eTable.getColumnModel().getColumn(1).setPreferredWidth(70);
//Mouse listener for eTable JopMethodMenu support.
eTable.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=eTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) eModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) eTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=eTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) eModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) eTable,
e.getX(), e.getY());
return;
}
}
public void mouseClicked(MouseEvent e) {
}
});
lower.add(eScroll,BorderLayout.CENTER);
lower.add(new JLabel(names[lang][1]), BorderLayout.NORTH);
this.setPreferredSize(new Dimension(600, 500));
this.add(upper);
this.add(lower);
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.io.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import jpwr.rt.*;
/* HistTable is an extended JScrollPane containing the
* a JTable alarmTable. The HistTable also contains methods for exporting
* the alarmTable to an excel file, and for performing a search in the historic
* event list using a HistSender */
public class HistTable extends JScrollPane{
JopSession session;
boolean DEBUG=false;
public EventTableModel atModel;
public JTable alarmTable;
String[][] columnNamesEventTable = {{"P","Type","Time","Description text","Event name"},{"P",
"Typ",
"Tid",
"Hndelsetext",
"Objekt"}};
String[][] excelMess=
{
{"Copy to Excel","Your search result has been put on the Clipboard.\nOpen a new document in Excel and choose \"Paste\" from the Edit menu\nto create a Worksheet with your search result."},
{"Kopiera till Excel","Ditt skresultat har nu lagrats i Urklipp.\nppna ett nytt dokument i Excel och vlj \"Klistra in\" i Redigeramenyn\nfr att skapa ett Excelark med ditt skresultat."}
};
int lang=0;
// Language sensitive constructor
public HistTable(int l, JopSession s){
session = s;
lang=l;
setup();
}
//Layout the HistTable. Add a mouse Listener to the JTable alarmTable
//and set it up to support JopMethodsMenu.
private void setup(){
atModel = new EventTableModel(lang);
alarmTable = new JTable(atModel);
alarmTable.setCellEditor(null);
this.initColumnSizes(alarmTable, atModel);
alarmTable.getTableHeader().setReorderingAllowed(false);
alarmTable.getColumn((Object)columnNamesEventTable[lang][0]).setCellRenderer(new EventTableCellRender());
this.setViewportView(alarmTable);
this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.getViewport().setBackground(Color.white);
((EventTableModel)alarmTable.getModel()).updateTable();
}
//Update the table headers to the correct language.
public void updateLang(int l){
lang=l;
for (int i=0; i<alarmTable.getColumnCount();i++)
alarmTable.getColumnModel().getColumn(i).setHeaderValue(columnNamesEventTable[lang][i]);
alarmTable.getTableHeader().resizeAndRepaint();
}
/*Get a pointer to the local Clipboard, format a string with all cell
elements with \t between columns and \n between rows and put it on
the clipboard. Display a message telling how to paste the string to
excel*/
public void exportExcel(){
StringBuffer copybuffer = new StringBuffer("");
for(int i=0;i<alarmTable.getRowCount();i++){
for (int j=0; j<alarmTable.getColumnCount();j++){
copybuffer.append((String) alarmTable.getValueAt(i,j));
copybuffer.append("\t");
}
copybuffer.append("\n");
}
Clipboard cb= Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection output = new StringSelection(copybuffer.toString());
cb.setContents(output, output);
JOptionPane.showMessageDialog(this.getParent(),excelMess[lang][1],excelMess[lang][0],JOptionPane.INFORMATION_MESSAGE);
}
//XLS
//Creates a String for sending to a javascript which can save to a file.
public String exportExcelFromApplet(){
String copyString = "";
for(int i=0;i<alarmTable.getRowCount();i++){
for (int j=0; j<alarmTable.getColumnCount();j++){
copyString = copyString +(String) alarmTable.getValueAt(i,j);
copyString = copyString+"\t";
}
copyString = copyString + "\n" ;
}
return copyString;
}
//Set column sizes to fit the table contents...
private void initColumnSizes(JTable table, AbstractTableModel model)
{
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues;
longValues = ((EventTableModel)(model)).longValues;
for(int i = 0; i < longValues.length; i++)
{
column = table.getColumnModel().getColumn(i);
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if(DEBUG)
{
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
}
//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
if(i == 0)
{
column.setMaxWidth(Math.max(headerWidth, cellWidth));
column.setResizable(false);
}
}
}
public void presentStat(){
// Derive interesting statistics from the current searchresult and
//display it in a JFrame...
HistStatistics statistics = new HistStatistics(atModel.mhData,lang,session);
JFrame frame = new JFrame();
JPanel panel = (JPanel)frame.getContentPane();
panel.setLayout(new FlowLayout());
panel.add(statistics);
frame.pack();
frame.show();
}
public int getNrOfResults(){
return alarmTable.getRowCount();
}
// Make a search in the Historical Event list based on the HistQuery search
public void performSearch(Object root, HistQuery search){
HistSender sender = new HistSender(root);
atModel.setMhData(sender.SearchRequest(search));
}
}
......@@ -79,6 +79,15 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
popup.add( item = new JMenuItem( "Circuit Diagram"));
item.addActionListener( this);
}
if ( classGraphFilter()) {
popup.add( item = new JMenuItem( "ClassGraph"));
item.addActionListener( this);
}
if (openSearchFilter()){
popup.add(item= new JMenuItem( "Hist Search"));
item.addActionListener( this);
}
popup.addPopupMenuListener( this);
popup.show( invoker, x, y);
session.getEngine().add(this);
......@@ -114,6 +123,12 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
else if ( event.getActionCommand().equals("Circuit Diagram")) {
circuitDiagram();
}
else if ( event.getActionCommand().equals("ClassGraph")) {
classGraph();
}
else if ( event.getActionCommand().equals("Hist Search")) {
openSearch();
}
}
//
......@@ -317,6 +332,54 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
session.executeCommand( cmd);
}
public boolean classGraphFilter() {
if ( classid == Pwrs.cClass_Node)
return true;
CdhrObjid coid = gdh.classIdToObjid( classid);
if ( coid.evenSts()) return false;
CdhrString sret = gdh.objidToName( coid.objid, Cdh.mName_object);
if ( sret.evenSts()) return false;
String name;
if ( coid.objid.vid < Cdh.cUserClassVolMin) {
// Class is a base class, java classname starts with JopC_
if ( coid.objid.vid == 1)
name = "jpwr.jopc.Jopc" + sret.str.substring(1,2).toUpperCase() +
sret.str.substring(2).toLowerCase();
else
name = "jpwr.jopc.Jopc" + sret.str.substring(0,1).toUpperCase() +
sret.str.substring(1).toLowerCase();
}
else
// Java name equals class name
name = sret.str.substring(0,1).toUpperCase() + sret.str.substring(1).toLowerCase();
try {
Class clazz = Class.forName( name);
}
catch ( Exception e) {
return false;
}
return true;
}
public void classGraph() {
String cmd = "open graph /class /instance=" + object;
System.out.println( "classGraph: " + cmd);
session.executeCommand( cmd);
}
public boolean openSearchFilter(){
// XXX If needed, this is the place to filter what
// objects are searchable.
return true;
}
public void openSearch(){
session.openSearch(object);
}
public boolean isVisible() {
return popup.isVisible();
}
......
......@@ -96,6 +96,10 @@ public class JopSession {
public boolean isOpWindowApplet() {
return ((JopSessionIfc) sessionRep).isOpWindowApplet();
}
public void openSearch(String object ){
((JopSessionIfc) sessionRep).openSearch(object);
}
}
......@@ -106,3 +110,4 @@ public class JopSession {
......@@ -21,4 +21,5 @@ public interface JopSessionIfc {
public boolean isApplet();
public boolean isApplication();
public boolean isOpWindowApplet();
public void openSearch(String object);
}
......@@ -114,6 +114,19 @@ public class JopSessionRep implements JopSessionIfc {
CdhrString sret = engine.gdh.objidToName( coid.objid, Cdh.mName_object);
if ( sret.evenSts()) return;
System.out.println( "open frame: vid " + coid.objid.vid);
if ( coid.objid.vid < Cdh.cUserClassVolMin) {
// Class is a base class, java classname starts with JopC_
if ( coid.objid.vid == 1)
name = "jpwr.jopc.Jopc" + sret.str.substring(1,2).toUpperCase() +
sret.str.substring(2).toLowerCase();
else
name = "jpwr.jopc.Jopc" + sret.str.substring(0,1).toUpperCase() +
sret.str.substring(1).toLowerCase();
}
else
// Java name equals class name
name = sret.str.substring(0,1).toUpperCase() + sret.str.substring(1).toLowerCase();
}
}
......@@ -207,6 +220,12 @@ public class JopSessionRep implements JopSessionIfc {
public boolean isOpWindowApplet() {
return ( root instanceof JopOpWindowApplet);
}
public void openSearch(String object){
HistSearch HSWindow = new HistSearch(object,session );
HSWindow.pack();
HSWindow.show();
}
}
......
package jpwr.jop;
import java.awt.*;
/* The Proportion class is used when using the RatioLayout layoutmanager. It
makes sure that the object associated with it keeps its proportions
when the frame is resized. */
public class Proportion {
//The ratios in x,y position and width, height
public double rx,ry,rw,rh;
public Dimension previous;
public boolean firstDraw =true;
// constructor. area= the size and place of an object. framesize
//is the size of the frame in which it is placed.
public Proportion(Rectangle area, Dimension framesize){
rx= (double) (1.0*area.x/framesize.width);
ry= (double) (1.0*area.y/framesize.height);
rw= (double) (1.0*area.width/framesize.width);
rh= (double) (1.0*area.height/framesize.height);
previous= new Dimension(1,1);
}
// For debuging purposes...
public String toString(){
return ""+rx+" "+ry+" "+rw+" "+rh+" "+previous+" "+firstDraw;
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import jpwr.jop.*;
import java.beans.Beans;
/** RatioLayout.java -- Layout manager for Java containers
*
* This layout manager allows you to specify ratios of x,y,width,height
* using a Proportion object.
*
* For example,
*
* setLayout(new RatioLayout());
* add( myObject, new Proportion(myObject.getBounds(), this.getSize()));
*
* @author Mats Trovik inspired by RatioLayout.java by Terence Parr
*
*/
public class RatioLayout implements LayoutManager2 {
// track the ratios for each object of form "xratio,yratio;wratio,hratio"
Vector ratios = new Vector(1);
// track the components also so we can remove associated modifier
// if necessary.
Vector components = new Vector(1);
public void addLayoutComponent(String r, Component comp) {
}
// The used method for adding components.
public void addLayoutComponent(Component comp, Object o){
Proportion r = (Proportion) o;
ratios.addElement(r);
components.addElement(comp);
}
//Maximum layout size depends on the target (as opposed to the normal case)
public Dimension maximumLayoutSize(Container target){
return target.getSize();
}
public float getLayoutAlignmentX(Container target){
//The layout is left aligned
return (float) 0.0;
}
public float getLayoutAlignmentY(Container target){
//the layout is top aligned
return (float) 0.0;
}
//Reset the Layout
public void invalidateLayout(Container target){
Vector ratios = new Vector(1);
Vector components = new Vector(1);
}
// Remove component from Layout
public void removeLayoutComponent(Component comp) {
int i = components.indexOf(comp);
if ( i!=-1 ) {
ratios.removeElementAt(i);
components.removeElementAt(i);
}
}
public Dimension preferredLayoutSize(Container target) {
return target.getSize();
}
public Dimension minimumLayoutSize(Container target) {
return target.getSize();
}
public void layoutContainer(Container target) {
Insets insets = target.getInsets();
int ncomponents = target.getComponentCount();
Dimension d = target.getSize();
//make sure to not draw over the insets.(Java standard)
d.width -= insets.left+insets.right;
d.height -= insets.top+insets.bottom;
//Layout each component
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = target.getComponent(i);
Proportion compProp=(Proportion)ratios.elementAt(i);
//Set the width and height according to the ratio specified when
//the component was added.
int w = (int)(d.width*compProp.rw);
int h = (int)(d.height*compProp.rh);
// set x & y to the ratio specified when the component was added.
//These values will be changed if the comonent is a slider or
//a moving GeComponent.
int x = (int) (d.width*compProp.rx);
int y = (int) (d.height*compProp.ry);
if(comp instanceof GeComponent){
GeComponent tempComp= (GeComponent) comp;
//If the component is of type mDynType_Move...
if((tempComp.dd.dynType & GeDyn.mDynType_Move) != 0){
if (compProp.firstDraw){
// ... and it's drawn for the first time, store the
//parent's dimension in Proportion.previous,
compProp.firstDraw=false;
compProp.previous.setSize(d.width,d.height);
}
else{
/*... and it's drawn for at least the 2nd time, the
*place where to draw it is caculated from the ratio
*between the the current dimensions of the parent and
*the previous dimensions (before resize)
*of the parent multiplied with the position of the
*object. Care is taken to only adjust the position in
*the direction(s) specified by the GeDynMove.moveX(Y)Attribute.
*The current dimensions of the parent are stored
*in Proportion.previous.*/
for(int j=0;j<tempComp.dd.elements.length;j++)
{
if(tempComp.dd.elements[j] instanceof GeDynMove){
Rectangle compLoc = comp.getBounds();
if ((! ((GeDynMove)tempComp.dd.elements[j]).moveXAttribute.equals(""))){
double rx = (1.0*d.width /compProp.previous.width );
x = (int) (compLoc.x*rx);
}
if ((! ((GeDynMove)tempComp.dd.elements[j]).moveYAttribute.equals(""))){
double ry = (1.0*d.height/compProp.previous.height);
y = (int) (compLoc.y*ry);
}
}
compProp.previous.setSize(d.width,d.height);
}
}
}
//If the component is a slider...
else if((tempComp.dd.actionType & GeDyn.mActionType_Slider) != 0){
if (compProp.firstDraw){
// ... and it's drawn for the first time, store the
//parent's dimension in Proportion.previous,
compProp.firstDraw=false;
compProp.previous.setSize(d.width,d.height);
}
else{
/*... and it's drawn for at least the 2nd time,
*the direction of the slider is checked.
*The ratio between the target width or height
*(after resize) and the previous width or
*height is used to calculate the position
*fitting the new size. The current dimensions
*of the parent are stored in Proportion.previous.*/
for(int j=0;j<tempComp.dd.elements.length;j++)
{
if(tempComp.dd.elements[j] instanceof GeDynSlider){
Rectangle compLoc = comp.getBounds();
if (
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_LEFT
||
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_RIGHT){
double rx = (1.0*d.width /compProp.previous.width );
x = (int) (compLoc.x*rx);
}
else if (
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_UP
||
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_DOWN){
double ry = (1.0*d.height/compProp.previous.height);
y = (int) (compLoc.y*ry);
}
}
}
compProp.previous.setSize(d.width,d.height);
}
}
}
//Place the component.
comp.setBounds(x+insets.left,y+insets.top,w,h);
//Resize the font of JTextFields.
if (comp instanceof JTextField){
comp.setFont(comp.getFont().deriveFont((float)(1.0*h*9/10)));
}
}
}
public String toString() {
return getClass().getName();
}
}
......@@ -24,6 +24,8 @@ import jpwr.rt.*;
public class XttTree extends JPanel
{
boolean findFieldEnable = false;
/*Mats frndringar ny boolean fr enterComm tillagd (enterFieldEnable)*/
boolean enterFieldEnable = false;
JPanel userPanel = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JPanel messagePanel = new JPanel();
......@@ -33,6 +35,7 @@ public class XttTree extends JPanel
JTextField userValue = new JTextField(25);
/** Description of the Field */
JLabel userValueLabel = new JLabel("Value input: ");
JLabel userCommandLabel = new JLabel("Command:");
JLabel labelMessage = new JLabel("Navigator ver 1.0");
Dimension size;
/** Description of the Field */
......@@ -56,7 +59,8 @@ public class XttTree extends JPanel
private DefaultTreeModel treeModel;
private URL url;
final JPopupMenu popup = new JPopupMenu();
//Mats frndringar: popup borttagen
//final JPopupMenu popup = new JPopupMenu();
InputMap inputMap = new InputMap();
ActionMap actionMap = new ActionMap();
......@@ -124,6 +128,11 @@ public class XttTree extends JPanel
String find_EN = "find...";
String find_SW = "sk...";
String find;
//Mats frndringar: strngar fr enterComm
String enterComm_EN = "enter command";
String enterComm_SW = "kommandorad";
String enterComm;
static final int SWEDISH = 0;
static final int ENGLISH = 1;
......@@ -172,6 +181,7 @@ public class XttTree extends JPanel
openPlc = openPlc_SW;
showCross = showCross_SW;
find = find_SW;
enterComm=enterComm_SW;
break;
case ENGLISH :
......@@ -185,6 +195,7 @@ public class XttTree extends JPanel
openPlc = openPlc_EN;
showCross = showCross_EN;
find = find_EN;
enterComm=enterComm_EN;
break;
}
//get all icons that is to be used in the tree
......@@ -291,19 +302,34 @@ public class XttTree extends JPanel
{
public void actionPerformed(ActionEvent evt)
{
if(!findFieldEnable)
/*Mats frndringar: Omstrukturering av ifsatser + en tillagd ifsats
fr enterFieldEnable*/
if(enterFieldEnable)
{
Logg.logg("XttTree: innan changeValue(" + userValue.getText() + ");", 6);
changeValue(userValue.getText());
Logg.logg("XttTree: innan enterCommand:(" + userValue.getText() + ");", 6);
enterComm(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userCommandLabel);
enterFieldEnable=false;
}
else
else if(findFieldEnable)
{
Logg.logg("XttTree: innan find(" + userValue.getText() + ");", 6);
find(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userValueLabel);
findFieldEnable=false;
}
tree.setRequestFocusEnabled(true);
else
{
Logg.logg("XttTree: innan changeValue(" + userValue.getText() + ");", 6);
changeValue(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userValueLabel);
}
tree.setRequestFocusEnabled(true);
messagePanel.add(labelMessage, BorderLayout.CENTER);
messagePanel.doLayout();
repaint();
......@@ -974,6 +1000,17 @@ public class XttTree extends JPanel
}
};
//Mats frndringar: Ny AbstractAction fr enterComm
AbstractAction COMM = new AbstractAction("COMM")
{
public void actionPerformed(ActionEvent evt)
{
enterComm();
}
};
/**
* Creates menuitem and keyboardbinding for a "method"
*
......@@ -985,7 +1022,9 @@ public class XttTree extends JPanel
*@param keyStroke A string representing the key-combination that is to be associated with the method
*@return Void
*/
public void newMethod(String name, Action action, String actionName, boolean toPopup, int toMenu, String keyStroke)
// Mats frndringar: booelan toPopup borttagen.
public void newMethod(String name, Action action, String actionName, /*boolean toPopup,*/ int toMenu, String keyStroke)
{
if(action != null)
{
......@@ -995,10 +1034,12 @@ public class XttTree extends JPanel
{
inputMap.put(KeyStroke.getKeyStroke(keyStroke), actionName);
}
/*
if(toPopup)
{
popup.add(menuItem(name, action, null));
}
*/
if(toMenu >= 0)
{
menubar.getMenu(toMenu).add(menuItem(name, action, keyStroke));
......@@ -1023,19 +1064,20 @@ public class XttTree extends JPanel
this.getRootPane().setJMenuBar(menubar);
//Mats frndringar: boolean toPopup borttagen ny metod fr enterComm
// Create some keystrokes and bind them to an action
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", true, 0, "ctrl A");
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", false, -1, "shift RIGHT");
this.newMethod("COLLAPSENODE", COLLAPSENODE, "COLLAPSENODE", false, -1, "LEFT");
this.newMethod(openPlc, OPENPLC, "OPENPLC", true, 0, "ctrl L");
this.newMethod(showCross, SHOWCROSS, "SHOWCROSS", true, 0, "ctrl R");
this.newMethod(changeValue, CHANGEVALUE, "CHANGEVALUE", true, 0, "ctrl Q");
this.newMethod(debug, DEBUG, "DEBUG", true, 0, "ctrl RIGHT");
this.newMethod(find, FIND, "FIND", false, 0, "ctrl F");
this.newMethod(swedish, LAN_SW, "LAN_SW", false, 1, null);
this.newMethod(english, LAN_EN, "LAN_EN", false, 1, null);
this.newMethod("INCLOG", INCLOG, "INCLOG", false, -1, "ctrl O");
this.newMethod("DECLOG", DECLOG, "DECLOG", false, -1, "ctrl P");
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO",/* true,*/ 0, "ctrl A"); this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", /*false,*/ -1, "shift RIGHT");
this.newMethod("COLLAPSENODE", COLLAPSENODE, "COLLAPSENODE",/* false,*/ -1, "LEFT");
this.newMethod(openPlc, OPENPLC, "OPENPLC", /*true,*/ 0, "ctrl L");
this.newMethod(showCross, SHOWCROSS, "SHOWCROSS", /*true,*/ 0, "ctrl R");
this.newMethod(changeValue, CHANGEVALUE, "CHANGEVALUE", /*true,*/ 0, "ctrl Q");
this.newMethod(debug, DEBUG, "DEBUG", /*true,*/ 0, "ctrl RIGHT");
this.newMethod(find, FIND, "FIND",/* false,*/ 0, "ctrl F");
this.newMethod(swedish, LAN_SW, "LAN_SW",/* false,*/ 1, null);
this.newMethod(english, LAN_EN, "LAN_EN", /*false,*/ 1, null);
this.newMethod("INCLOG", INCLOG, "INCLOG", /*false,*/ -1, "ctrl O");
this.newMethod("DECLOG", DECLOG, "DECLOG", /*false,*/ -1, "ctrl P");
this.newMethod(enterComm, COMM,"COMM",0,"ctrl C");
inputMap.setParent(this.tree.getInputMap(JComponent.WHEN_FOCUSED));
this.tree.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
......@@ -1076,7 +1118,31 @@ public class XttTree extends JPanel
if(e.isPopupTrigger())
{
System.out.println("mouse pressed isPopUpTrigger");
popup.show((Component)e.getSource(), e.getX(), e.getY());
//Mats frndringar: popup borttagen, JopMethodsMenu tillagd.
TreePath tp = tree.getSelectionPath();
if(tp == null) return;
DefaultMutableTreeNode tn = (DefaultMutableTreeNode)(tp.getLastPathComponent());
if(tn == null) return;
try
{
TreeObj obj = (TreeObj)tn.getUserObject();
String name = obj.fullName;
if(name == null)
{
return;
}
new JopMethodsMenu( session,
name,
JopUtility.TRACE,(Component) tree,
e.getX(), e.getY());
}
catch(Exception ex)
{
Logg.logg("Error in showCross() " + ex.toString(),0);
}
Logg.loggToApplet("");
//popup.show((Component)e.getSource(), e.getX(), e.getY());
}
}
}
......@@ -1090,7 +1156,31 @@ public class XttTree extends JPanel
if(e.isPopupTrigger())
{
System.out.println("isPopUpTrigger");
popup.show((Component)e.getSource(), e.getX(), e.getY());
//Mats frndringar: popup borttagen, JopMethodsMenu tillagd.
TreePath tp = tree.getSelectionPath();
if(tp == null) return;
DefaultMutableTreeNode tn = (DefaultMutableTreeNode)(tp.getLastPathComponent());
if(tn == null) return;
try
{
TreeObj obj = (TreeObj)tn.getUserObject();
String name = obj.fullName;
if(name == null)
{
return;
}
new JopMethodsMenu( session,
name,
JopUtility.TRACE,(Component) tree,
e.getX(), e.getY());
}
catch(Exception ex)
{
Logg.logg("Error in showCross() " + ex.toString(),0);
}
Logg.loggToApplet("");
// popup.show((Component)e.getSource(), e.getX(), e.getY());
}
}
});
......@@ -1258,6 +1348,7 @@ public class XttTree extends JPanel
this.openPlc = openPlc_SW;
this.find = find_SW;
this.showCross = showCross_SW;
this.enterComm = enterComm_SW;
this.currentLanguage = SWEDISH;
this.updateMenuLabels();
}
......@@ -1273,6 +1364,7 @@ public class XttTree extends JPanel
this.openPlc = openPlc_EN;
this.find = find_EN;
this.showCross = showCross_EN;
this.enterComm = enterComm_EN;
this.currentLanguage = ENGLISH;
this.updateMenuLabels();
}
......@@ -1290,16 +1382,18 @@ public class XttTree extends JPanel
menuFunctions.getItem(3).setText(changeValue);
menuFunctions.getItem(4).setText(debug);
menuFunctions.getItem(5).setText(find);
menuFunctions.getItem(6).setText(enterComm);
menuLan.setText(language);
menuLan.getItem(0).setText(swedish);
menuLan.getItem(1).setText(english);
MenuElement[] menuElements = popup.getSubElements();
//Mats frndringar: Uppdatering av popup borttagen
/*MenuElement[] menuElements = popup.getSubElements();
((JMenuItem)(menuElements[0])).setText(openObject);
((JMenuItem)(menuElements[1])).setText(openPlc);
((JMenuItem)(menuElements[2])).setText(showCross);
((JMenuItem)(menuElements[3])).setText(changeValue);
((JMenuItem)(menuElements[4])).setText(debug);
((JMenuItem)(menuElements[4])).setText(debug);*/
}
......@@ -1312,7 +1406,11 @@ public class XttTree extends JPanel
Logg.logg("JopXttApplet: changeValue()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
this.messagePanel.remove(labelMessage);
if (enterFieldEnable){
enterFieldEnable = false;
this.messagePanel.remove(userCommandLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userValueLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
......@@ -1332,7 +1430,12 @@ public class XttTree extends JPanel
Logg.logg("JopXttApplet: find()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
this.messagePanel.remove(labelMessage);
//Mats frndringar: Hantering av om enterFieldEnable =true
if (enterFieldEnable){
enterFieldEnable = false;
this.messagePanel.remove(userCommandLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userValueLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
......@@ -1341,7 +1444,30 @@ public class XttTree extends JPanel
this.userValue.requestFocus();
this.findFieldEnable = true;
}
//Mats frndringar: Ny metod enterComm fr att hantera manuellt inskrivna kommandon.
public void enterComm()
{
Logg.loggToApplet(" ");
Logg.logg("JopXttApplet: enterComm()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
if (userValueLabel.isVisible()){
findFieldEnable = false;
this.messagePanel.remove(userValueLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userCommandLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
messagePanel.repaint();
this.userValue.requestFocus();
this.enterFieldEnable = true;
}
//Mats frndringar: ny metod som exekverar kommandot com.
public void enterComm(String com){
session.executeCommand(com);
}
/**
......
/**
* Title: Hist.java Description: Klass som fungerar som en port mot
* Historiska Händelselistan Copyright: <p>
*
* Company SSAB<p>
*
*
*
*@author JN
*@version 1.0
*/
package jpwr.rt;
/**
* Description of the Class
*
*@author Jonas Nylund
*@created July 5, 2004
*/
public class Hist
{
static
{
System.loadLibrary("jpwr_rt_gdh");
initHistIDs();
}
/**
*@author claes
*@created November 26, 2002
*@ingroup MSGH_DS
*@brief Defines a bit pattern.
*@param mh_mEventFlags_Return Setting this flag enables a return
* message associated with this message to be shown in the event list.
*@param mh_mEventFlags_Ack Setting this flag enables an
* acknowledgement message associated with this message to be shown in
* the event list.
*@param mh_mEventFlags_Bell
*@param mh_mEventFlags_Force
*@param mh_mEventFlags_InfoWindow
*@param mh_mEventFlags_Returned
*@param mh_mEventFlags_NoObject
*/
public static final int mh_mEventFlags_Return = 0x01;
public static final int mh_mEventFlags_Ack = 0x02;
public static final int mh_mEventFlags_Bell = 0x04;
public static final int mh_mEventFlags_Force = 0x08;
public static final int mh_mEventFlags_InfoWindow = 0x10;
public static final int mh_mEventFlags_Returned = 0x20;
public static final int mh_mEventFlags_NoObject = 0x40;
public static final int mh_mEventStatus_NotRet = (1 << 0);
public static final int mh_mEventStatus_NotAck = (1 << 1);
public static final int mh_mEventStatus_Block = (1 << 2);
/**
* @ingroup MSGH_DS
* @brief Event prio
*
* This enumeration defines the priority of the event.
* This affects how the message handler treats the generated message.
* For A and B priorities the alarm window displays number of alarms,
* number of unacknowledged alarms, identities of the alarms, and associated
* message texts. For C and D priorities, only number of alarms and number of
* unacknowledged alarms are shown.
* @param mh_eEventPrio_A Priority A, the highest priority.
* Alarm messages of this priority are shown in the upper part of the alarm window.
* @param mh_eEventPrio_B Priority B.
* These messages are shown in the lower part of the alarm window.
* @param mh_eEventPrio_C Priority C.
* @param mh_eEventPrio_D Priority D. This is the lowest priority.
*/
public static final int mh_eEventPrio__ = 0;
public static final int mh_eEventPrio_A = 67;
public static final int mh_eEventPrio_B = 66;
public static final int mh_eEventPrio_C = 65;
public static final int mh_eEventPrio_D = 64;
public static final int mh_eEventPrio_ = 63;
public static final int mh_eEvent__ = 0;
public static final int mh_eEvent_Ack = 1;
public static final int mh_eEvent_Block = 2;
public static final int mh_eEvent_Cancel = 3;
public static final int mh_eEvent_CancelBlock = 4;
public static final int mh_eEvent_Missing = 5;
public static final int mh_eEvent_Reblock = 6;
public static final int mh_eEvent_Return = 7;
public static final int mh_eEvent_Unblock = 8;
public static final int mh_eEvent_Info = 32;
public static final int mh_eEvent_Alarm = 64;
public static final int mh_eEvent_ = 65;
public static final int EventType_ClearAlarmList = 66;
private static boolean initDone = false;
/**
* Constructor for the Hist object
*
*@param root Description of the Parameter
*/
public Hist()
{
if(!initDone)
{
initDone = true;
}
}
private native static void initHistIDs();
/**
* Description of the Method
*
*@param query The query to the HistDB
*@return Vector A Vector containing matching events
*/
public native static MhrEvent[] getHistList(String startTime,
String stopTime,
boolean typeAlarm,
boolean typeInfo,
boolean typeReturn,
boolean typeAck,
boolean prioA,
boolean prioB,
boolean prioC,
boolean prioD,
String name,
String text);
}
package jpwr.rt;
import java.io.Serializable;
/*The HistQuery class represents the search criteria needed to perform a Search
*in the eventlist. It is used as the argument for performing SearchRequest from
*a SearchSender */
public class HistQuery implements Serializable{
public String startTime;
public String stopTime;
public boolean[] type;
public boolean[] priority;
public String name;
public String text;
public HistQuery(String start, String stop, boolean[] ty, boolean[] p, String n,String tx)
{
this.startTime=start;
this.stopTime=stop;
this.type=ty;
this.priority=p;
this.name=n;
this.text=tx;
}
}
package jpwr.rt;
import java.net.*;
import java.io.*;
import java.util.*;
//for test
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.*;
//end for test
/**
* Description of the Class
*
*@author claes, Jonas
*@created November 25, 2002
*@version 0.1 beta: Frsta testversionen
*/
public class HistServer
{
public final static int HISTPORT = 4447;
public final static int __IO_EXCEPTION = 2000;
static boolean ignoreHandler = false;
static boolean log = false;
static boolean logStatistics = false;
static boolean test = false;
boolean keepRunning = true;
/**
* The main program for the HistServer class
*
*@param args The command line arguments
*/
public static void main(String[] args)
{
for(int i = 0; i < args.length; i++)
{
if(args[i].equals("-i"))
{
ignoreHandler = true;
}
else if(args[i].equals("-l"))
{
log = true;
}
else if(args[i].equals("-s"))
{
logStatistics = true;
}
else if(args[i].equals("-t"))
{
test = true;
}
}
if(log)
{
System.out.println("HistServer starting");
}
Hist hist = new Hist();
HistServer hs = new HistServer();
hs.run(hist);
System.out.println("HistServer exiting");
System.exit(0);
}
public void run(Hist hist)
{
boolean keepRunning = true;
ServerSocket serverSocket = null;
if(test)
{
boolean[] type = new boolean[4];
type[0] = type[1] = type[2] = type[3] = false;
type[0] = true;
boolean[] prio = new boolean[4];
prio[0] = prio[1] = prio[2] = prio[3] = false;
HistQuery query = new HistQuery("2003-11-05 09:26:49", "2004-11-05 09:26:49", type, prio, "*", "*");
MhrEvent[] ev = hist.getHistList(query.startTime,
query.stopTime,
query.type[0],
query.type[1],
query.type[2],
query.type[3],
query.priority[0],
query.priority[1],
query.priority[2],
query.priority[3],
query.name,
query.text);
int i = 0;
System.out.println("No events: "+ ev.length);
while(i < ev.length)
{
System.out.println(ev[i].toString());
i++;
}
return;
}
try
{
serverSocket = new ServerSocket(HISTPORT);
serverSocket.setSoTimeout(1000);
}
catch(IOException e)
{
System.out.println("IOException in openServerSocket");
//errh.fatal("Could not listen on port " + HISTPORT);
System.exit(1);
}
// gdh = new Gdh((Object)null);
// errh = new Errh("MhServer", Errh.eAnix_webmonmh);
// errh.setStatus( Errh.PWR__SRVSTARTUP);
if(log)
{
System.out.println("JHist: Before waiting for client");
}
// mh = new Mh((Object)null, maxAlarms, maxEvents);
// errh.setStatus( Errh.PWR__SRUN);
// Qcom qcom = new Qcom();
// QcomrCreateQ qque = qcom.createIniEventQ("MhServer");
// if(qque.evenSts())
// {
// System.out.println("MH:Error during qreateque");
// errh.fatal("MH:Error during qcom.createIniEventQ");
// return;
// }
// QcomrGetIniEvent qrGetIniEv;
while(keepRunning)
{
Socket cliSocket = null;
try
{
if(log)
{
//System.out.println(" Wait for accept ");
}
cliSocket = serverSocket.accept();
}
catch(InterruptedIOException e)
{
continue;
/*
qrGetIniEv = qcom.getIniEvent(qque.qix, qque.nid, 0);
if(qrGetIniEv.timeout)
{
//do nothing
continue;
}
else if(qrGetIniEv.terminate)
{
//Time to die
System.out.println("MhServer received killmess from QCom");
return;
}
else
{
//All other messages is qurrently ignored
//But perhaps we should reinitialize when we get
//swapdone
continue;
}
*/
}
catch(IOException e)
{
//errh.error("Accept failed.");
this.keepRunning = false;
continue;
}
if(log)
{
System.out.println("New client for HistServer");
}
new HistThread(hist, cliSocket);
}
}
private class HistThread extends Thread
{
Hist hist;
Socket socket;
public HistThread(Hist hist, Socket socket)
{
this.hist = hist;
this.socket = socket;
start();
}
public void run()
{
this.handleClient(this.socket);
}
public void handleClient(Socket socket)
{
ObjectInputStream in = null;
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
//wait for the question
HistQuery query = (HistQuery)in.readObject();
if(log)
{
System.out.println("Recieved a query");
System.out.println("query: Prio(ABCD): " + query.priority[0] + query.priority[1] + query.priority[2] + query.priority[3]);
System.out.println(" type(Akt Mess Ret Kvitt): " + query.type[0] + query.type[1] + query.type[2] + query.type[3]);
System.out.println(" startTime: " + query.startTime);
System.out.println(" stopTime: " + query.stopTime);
System.out.println(" name: " + query.name);
System.out.println(" text: " + query.text);
}
//send the answer
out.writeObject(hist.getHistList(query.startTime,
query.stopTime,
query.type[0],
query.type[1],
query.type[2],
query.type[3],
query.priority[0],
query.priority[1],
query.priority[2],
query.priority[3],
query.name,
query.text));
}
catch(IOException e)
{
System.out.println("Exception in hist.handleQuery:" + e.toString());
//errh.error("hist.handleCLient: DataStream failed");
}
catch(Exception e)
{
System.out.println("Exception in hist.handleQuery:" + e.toString());
//errh.error("hist.handleCLient: Exception");
}
finally
{
//System.out.println("finally");
try
{
out.close();
}
catch(Exception e)
{
}
try
{
in.close();
}
catch(Exception e)
{
System.out.println("Closing client socket");
}
try
{
socket.close();
}
catch(Exception e)
{
}
}//finally
}//handleClient
}//HistThread
}//HistServer
......@@ -62,6 +62,10 @@ public class MhrEvent implements Serializable
eventType,
object);
}
public String toString()
{
return new String(eventTime + eventText + eventName + eventFlags + eventPrio + eventType);
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
/* This class is used as a ComponentListener for any Component for which
the Aspect Ratio is important and needs to be retained. The constructor
needs to know what Component it is applied to and the original size of it.
From the size the aspect ratio is calculated and every time the Container
is resized. The size is changed so that the aspect ratio matches the,
relatively, smaller one of the new width and height.
syntax : new AspectTarioListener(c)
or new AspectRatioListener(c,size)
where c is the component, and size is the original size of it. */
public class AspectRatioListener implements ComponentListener {
private double ratio;
private Dimension previous;
private Container victim;
public AspectRatioListener(Container c){
victim = c;
previous = (Dimension) c.getSize().clone();
ratio = 1.0*c.getSize().width/c.getSize().height;
}
public AspectRatioListener(Container c, Dimension size){
victim = c;
previous = (Dimension) size.clone();
ratio = 1.0*size.width/size.height;
}
public void componentResized(ComponentEvent e) {
int width = victim.getWidth();
int height = victim.getHeight();
// check if the height or width should be adjusted.
if (!(previous.equals(victim.getSize()))){
if ((width > previous.width) ||
(height > previous.height)){
if ((0.1*height/previous.height)>(0.1*width/previous.width))
width = (int) (ratio*height);
else
height = (int) (width/ratio);
}
else{
if ((0.1*width/previous.width)<(0.1*height/previous.height))
height = (int) (width/ratio);
else
width = (int) (ratio*height);
}
previous = new Dimension(width,height);
victim.setSize(width,height);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import jpwr.rt.Mh;
import jpwr.rt.MhrEvent;
/* This class is used to make sure an EventTableModel in a JaTable is presented
* in a graphically appealing manner. */
public class EventTableCellRender extends DefaultTableCellRenderer
{
Color ALarmColor = Color.red;
Color BLarmColor = Color.yellow;
Color CLarmColor = Color.blue;
Color DLarmColor = Color.cyan;
Color InfoColor = Color.green;
/**
* Gets the tableCellRendererComponent attribute of the
* EventTableCellRender object
*
*@param table Description of the Parameter
*@param value Description of the Parameter
*@param isSelected Description of the Parameter
*@param hasFocus Description of the Parameter
*@param row Description of the Parameter
*@param column Description of the Parameter
*@return The tableCellRendererComponent value
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
//I will assume that the number is stored as a string. if it is stored as an Integer, you can change this easily.
//if(column == 0)
//{
String number = (String)value;
//cast to a string
//int val = Integer.parseInt(number);//convert to an integer
MhrEvent ev = ((EventTableModel)table.getModel()).getRowObject(row);
this.setBackground(Color.white);
if(ev == null)
{
this.setText(" ");
return this;
}
boolean setColor = false;
if( ev.eventType == Mh.mh_eEvent_Alarm||ev.eventType == Mh.mh_eEvent_Info )
setColor = true;
//System.out.println("i eventTable.getTableCellRendererComponent(row " + row + "value" + number + ")");
if(number.compareTo("A") == 0)
{
if(setColor)
{
this.setBackground(ALarmColor);
}
this.setText("A");
}
else if(number.compareTo("B") == 0)
{
if(setColor)
{
this.setBackground(BLarmColor);
}
this.setText("B");
}
else if(number.compareTo("C") == 0)
{
if(setColor)
{
this.setBackground(CLarmColor);
}
this.setText("C");
}
else if(number.compareTo("D") == 0)
{
if(setColor)
{
this.setBackground(DLarmColor);
}
this.setText("D");
}
//annars mste det vara ett meddelande qqq??
else
{
if(setColor)
{
this.setBackground(InfoColor);
}
this.setText(" ");
}
//}
//else
// this.setBackground(Color.white);
return this;
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.Mh;
import jpwr.rt.MhData;
import jpwr.rt.MhrEvent;
/* The EventTableModel is an AbstractTableModel designed to keep the
*result from a search made with the AlertSearch engine. The result
*to present is contained in the MhData mhdata.*/
class EventTableModel extends AbstractTableModel
{
MhData mhData = new MhData(0,100);
String[][] columnNamesEventTable = {{"Prio","","Time","Description text","Event name"},{"P",
"Typ",
"Tid",
"Hndelsetext",
"Objekt"}};
int lang;
public final Object[] longValues = {"A", "Kvittens",
"10-12-31 12:12:12.98",
"QWERTYUIOPLK_JHGFDSAZXCVBNM__POIUYTRQWERTYUIOPL",
"QWERTYUIOPLK"};
/**
* Constructor for the EventTableModel object
*/
public EventTableModel() { lang=0; }
// constructor with language support
public EventTableModel(int l) { lang=l; }
/**
* Gets the columnCount attribute of the EventTableModel object
*
*@return The columnCount value
*/
public int getColumnCount()
{
return columnNamesEventTable[lang].length;
}
/**
* Gets the rowCount attribute of the EventTableModel object
*
*@return The rowCount value
*/
public int getRowCount()
{
return mhData.getNrOfEvents();//eventData.size();
}
/**
* Gets the columnName attribute of the EventTableModel object
*
*@param col Description of the Parameter
*@return The columnName value
*/
public String getColumnName(int col)
{
return (String)columnNamesEventTable[lang][col];
}
/**
* Gets the valueAt attribute of the EventTableModel object
*
*@param row Description of the Parameter
*@param col Description of the Parameter
*@return The valueAt value
*/
public Object getValueAt(int row, int col)
{
try
{
MhrEvent ev = mhData.getEvent(row);//(MhrEvent)eventData.get(row);
if(col == 0)
{
//System.out.println("col == 0 i eventTable.getValueAt()");
if(ev.eventPrio == Mh.mh_eEventPrio_A)
{
return "A";
}
if(ev.eventPrio == Mh.mh_eEventPrio_B)
{
return "B";
}
if(ev.eventPrio == Mh.mh_eEventPrio_C)
{
return "C";
}
if(ev.eventPrio == Mh.mh_eEventPrio_D)
{
return "D";
}
else
{
return "U";
}
}
if(col == 1)
{
String returnString = " ";
switch (ev.eventType)
{
case Mh.mh_eEvent_Alarm:
returnString = "Larm";
break;
case Mh.mh_eEvent_Ack:
returnString = "Kvittens";
break;
case Mh.mh_eEvent_Block:
returnString = "Block";
break;
case Mh.mh_eEvent_Cancel:
returnString = "Cancel";
break;
case Mh.mh_eEvent_CancelBlock:
returnString = "CancelBlock";
break;
case Mh.mh_eEvent_Missing:
returnString = "Missing";
break;
case Mh.mh_eEvent_Reblock:
returnString = "Reblock";
break;
case Mh.mh_eEvent_Return:
returnString = "Retur";
break;
case Mh.mh_eEvent_Unblock:
returnString = "Unblock";
break;
case Mh.mh_eEvent_Info:
returnString = "Info";
break;
case Mh.mh_eEvent_:
returnString = "?";
break;
default:
returnString = " ";
break;
}
return returnString;
}
if(col == 2)
{
return ev.eventTime;
}
if(col == 3)
{
return ev.eventText;
}
if(col == 4)
{
return ev.eventName;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
if(col == 1)
{
return new Boolean(false);
}
}
return "FEEELLLL";
}
/**
* Gets the columnClass attribute of the EventTableModel object
*
*@param c Description of the Parameter
*@return The columnClass value
*/
public Class getColumnClass(int c)
{
return longValues[c].getClass();
//return getValueAt(0, c).getClass();
}
/**
* Sets the valueAt attribute of the EventTableModel object
*
*@param value The new valueAt value
*@param row The new valueAt value
*@param col The new valueAt value
*/
public void setValueAt(Object value, int row, int col)
{
//alarmData[row][col] = value;
// fireTableCellUpdated(row, col);
}
/**
* Gets the rowObject attribute of the EventTableModel object
*
*@param row Description of the Parameter
*@return The rowObject value
*/
public MhrEvent getRowObject(int row)
{
try
{
return mhData.getEvent(row);//(MhrEvent)eventData.get(row);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("eventable.getRowObject " + e.toString());
}
return null;
}
/**
* Description of the Method
*/
public void rowInserted()
{
fireTableRowsInserted(0, 0);
}
/**
* Description of the Method
*
*@param row Description of the Parameter
*/
public void rowRemoved(int row)
{
fireTableRowsDeleted(row, row);
}
/**
* Description of the Method
*/
public void reloadTable()
{
fireTableStructureChanged();
}
/**
* Description of the Method
*/
public void updateTable()
{
fireTableDataChanged();
}
public void setMhData(MhData data)
{
mhData=data;
updateTable();
}
}
......@@ -16,7 +16,7 @@ public class GeComponent extends JComponent implements GeComponentIfc,
public JopEngine en;
public GeDyn dd = new GeDyn( this);
public int level;
Timer timer = new Timer(100, this);
public Timer timer = new Timer(100, this);
StringBuffer sb = new StringBuffer();
public JopSession session;
public GeComponent component = this;
......@@ -75,6 +75,8 @@ public class GeComponent extends JComponent implements GeComponentIfc,
if ( (dd.actionType & GeDyn.mActionType_Slider) != 0) {
this.addMouseMotionListener( new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if ( actionDisabled)
return;
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0 &&
en.gdh.isAuthorized( dd.access))
dd.action( GeDyn.eEvent_SliderMoved, e);
......@@ -110,6 +112,8 @@ public class GeComponent extends JComponent implements GeComponentIfc,
public void setLevelColorTone( int levelColorTone) { this.levelColorTone = levelColorTone;}
public void setLevelFillColor( int levelFillColor) { this.levelFillColor = levelFillColor;}
boolean actionDisabled = false;
public void setActionDisabled( boolean actionDisabled) { this.actionDisabled = actionDisabled;}
public String annot1 = new String();
public Font annot1Font = new Font("Helvetica", Font.BOLD, 14);
public void setAnnot1Font( Font font) { annot1Font = font;}
......
......@@ -24,4 +24,5 @@ public interface GeComponentIfc {
public int setPreviousPage();
public Object getDd();
public void repaintForeground();
public Object dynamicGetRoot();
}
......@@ -27,10 +27,16 @@ public class GeFrameThin extends GeComponent {
g.setTransform(save);
}
}
float original_width = 0;
float original_height = 0;
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
float width = getWidth();
float height = getHeight();
if ( original_width == 0)
original_width = width;
if ( original_height == 0)
original_height = height;
AffineTransform save = g.getTransform();
AffineTransform save_tmp;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
......@@ -42,6 +48,7 @@ public class GeFrameThin extends GeComponent {
shapes[3] = new Line2D.Float(width - 2F, height - 2F, width - 2F, 2F);
}
/*
if ( 45.0 <= rotate && rotate < 135.0) {
g.translate( width, 0.0);
g.rotate( Math.PI * rotate/180, 0.0, 0.0);
......@@ -59,6 +66,29 @@ public class GeFrameThin extends GeComponent {
g.transform( AffineTransform.getScaleInstance( height/width,
width/height));
}
*/
if ( 45.0 <= rotate && rotate < 135.0) {
g.translate( width, 0.0);
g.rotate( Math.PI * rotate/180, 0.0, 0.0);
g.transform( AffineTransform.getScaleInstance( height/original_width,
width/original_height));
}
else if ( 135.0 <= rotate && rotate < 225.0)
{
g.rotate( Math.PI * rotate/180, width/2, height/2);
g.transform( AffineTransform.getScaleInstance( width/original_width,
height/original_height));
}
else if ( 225.0 <= rotate && rotate < 315.0)
{
g.translate( -height, 0.0);
g.rotate( Math.PI * rotate/180, height, 0.0);
g.transform( AffineTransform.getScaleInstance( height/original_width,
width/original_height));
}
else
g.transform( AffineTransform.getScaleInstance( width/original_width,
height/original_height));
g.setStroke( new BasicStroke(1F));
g.setColor(GeColor.getColor(78, colorTone,
......
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class HistDateChooser extends JPanel implements ActionListener{
private Calendar date;
SpinnerDateModel yearModel;
private JComboBox month;
private JSpinner year, hour, minute, second;
private JPanel dayGrid = new JPanel();
private JPanel timeGrid = new JPanel();
private int selectedDay;
private int lang =0;
private String[][] months = {{"January", "February", "March", "April", "May", "June", "July"
,"August", "September", "October","November", "December"},
{"januari", "februari", "mars", "april", "maj", "juni", "juli"
,"augusti", "september", "oktober","november", "december"}};
private String[][] days = {{"Mon","Tue","Wed","Thu","Fri","Sat","Sun"},
{"Mn","Tis","Ons","Tor","Fre","Lr","Sn"}};
private String[][] time = {{"Hour","Minute","Second"},{"Timme","Minut","Sekund"}};
public HistDateChooser(){
date = Calendar.getInstance();
init();
}
public HistDateChooser(int l){
lang=l;
date = Calendar.getInstance();
init();
}
public HistDateChooser(Calendar Cal,int l){
lang=l;
date = (Calendar) Cal.clone();
init();
}
private void init(){
selectedDay=date.get(Calendar.DAY_OF_MONTH);
month = new JComboBox(months[lang]);
month.setSelectedIndex(date.get(Calendar.MONTH));
yearModel = new SpinnerDateModel();
yearModel.setValue(date.getTime());
yearModel.setCalendarField(Calendar.YEAR);
year = new JSpinner(yearModel);
year.setEditor(new JSpinner.DateEditor(year, "yyyy"));
this.setLayout(new BorderLayout());
this.add("North",year);
dayGrid.setLayout(new GridLayout(7,7));
month.addActionListener(this);
yearModel.addChangeListener( new YearChangeListener());
this.add("Center",dayGrid);
this.add("West",month);
hour=new JSpinner(new SpinnerNumberModel(date.get(Calendar.HOUR_OF_DAY),0,23,1));
minute=new JSpinner(new SpinnerNumberModel(date.get(Calendar.MINUTE),0,59,1));
second=new JSpinner(new SpinnerNumberModel(date.get(Calendar.SECOND),0,59,1));
setupTimeGrid();
this.add("South",timeGrid);
updateGrid();
}
public Calendar getDate(){
updateDate();
return date;
}
private void updateDate(){
date.setTime(yearModel.getDate());
date.set(Calendar.MONTH,month.getSelectedIndex());
date.set(Calendar.DAY_OF_MONTH,selectedDay);
date.set(Calendar.HOUR_OF_DAY,((Integer)hour.getValue()).intValue());
date.set(Calendar.MINUTE,((Integer)minute.getValue()).intValue());
date.set(Calendar.SECOND,((Integer)second.getValue()).intValue());
}
private void updateGrid(){
updateDate();
dayGrid.removeAll();
int i;
for (i=0;i<7;i++) dayGrid.add(new JLabel(days[lang][i],JLabel.CENTER));
Calendar temp =(Calendar) date.clone();
temp.set(Calendar.DAY_OF_MONTH,1);
int startDay = temp.get(Calendar.DAY_OF_WEEK)-Calendar.MONDAY;
if (startDay<0) startDay=6;
for (i=0;i<startDay;i++) dayGrid.add(new JLabel(""));
for (i=1;i<=date.getActualMaximum(Calendar.DAY_OF_MONTH);i++) {
JButton day = new JButton(String.valueOf(i));
day.addActionListener(this);
if (i==selectedDay)
day.setEnabled(false);
dayGrid.add(day);
}
for (i=startDay+date.getActualMaximum(Calendar.DAY_OF_MONTH)+1;i<42;i++) dayGrid.add(new Label(""));
repaint();
validate();
}
private void setupTimeGrid(){
timeGrid.setLayout(new GridLayout(3,3));
for (int i=0; i<3; i++){
timeGrid.add(new JLabel(""));
}
for (int i=0; i<3; i++){
timeGrid.add(new JLabel(time[lang][i],JLabel.CENTER));
}
timeGrid.add(hour);
timeGrid.add(minute);
timeGrid.add(second);
}
public void actionPerformed(ActionEvent e){
if (e.getSource().getClass() == (new JButton()).getClass()){
try{
JButton pressed = (JButton) e.getSource();
selectedDay = (new Integer(pressed.getText())).intValue();
}
catch (Exception ex) {
System.out.println("Error:" + ex);
}
}
updateGrid();
}
private class YearChangeListener implements ChangeListener{
public void stateChanged(ChangeEvent e){
updateGrid();
}
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import jpwr.rt.*;
import java.applet.Applet;
//XLS import netscape.javascript.*;
// Import of netscape.javascript.* from jaws.jar is needed !!!
/* HistSearch is a search engine for performing searches from the historic
*event list. It's mainly a GUI for getting input on the criteria on which
*the search should be based, launching the search and presenting the result.
*It uses a HistTable called result for presenting the search result.
*The HistQuery currentSearch is set to the criteria chosen via the GUI when
*the JButton btnSearch is pressed and currentSearch is then sent to a class
*in the HistTable result for evaluating the search and updating the table.
*The GUI is made to support English and Swedish by keeping arrays of all
*strings. The integer lang indicates which language to be used, (0=eng
*1=swe) and all texts on screen is updated at once by calling updateText().
*/
public class HistSearch extends JFrame implements ActionListener
{
public JopEngine engine;
public JopSession session;
public Object root;
;
/*integers for keeping track of the language setting and the number of
search results.*/
int lang=1;
int num=0;
JPanel contentPane;
// ****TOP****
//top contains the search interface
JPanel top = new JPanel();
//check contains the arrays of checkboxes
JPanel check = new JPanel();
// labels describing different objects in the search interface.
JLabel lblStart = new JLabel("", JLabel.LEFT);
JLabel lblStop = new JLabel("", JLabel.LEFT);
JLabel lblType = new JLabel("", JLabel.LEFT);
JLabel lblPriority = new JLabel("", JLabel.LEFT);
JLabel lblName = new JLabel("", JLabel.LEFT);
JLabel lblText = new JLabel("", JLabel.LEFT);
JLabel lblNum = new JLabel("",JLabel.LEFT);
String[] descStart = {"Start time:","Starttid:"};
String[] descStop = {"Stop time:","Stopptid:"};
String[] descType = {"Event type:","Hndelsetyp:"};
String[] descPriority = {"Priority:","Prioritet:"};
String[] descName = {"Event name:","Hndelsenamn:"};
String[] descText = {"Event text:","Hndelsetext:"};
String[] descStat = {"Statistics", "Statistik"};
// textfields for different parameters in the search interface
JTextField txStart,txStop,txName,txText;
// cbWhen is a combo box giving choices of search intervals
String[][] choice = {{"All alarms","This year","This month","This week","Today","Enter dates"},
{"Alla alarm","Detta r","Denna mnad","Den hr veckan","Idag","Egna datum"}};
JComboBox cbWhen ;
// type is an array of radiobuttons, one for each type of event
JCheckBox[] type = new JCheckBox[4];
String[][] nameType = {{"Active","Message","Return","Ack"},
{"Aktiv","Meddelande","Retur","Kvittens"}};
// priority is an array of checkboxes, one for each priority
JCheckBox[] priority = new JCheckBox[4];
String[] namePriority = {"A-Alarm","B-Alarm","C-Alarm","D-Alarm"};
// btnSearch is the search button
JButton btnSearch ;
String[] descSearch= {"Search","Sk"};
// two calendars for start and stop dates
Calendar calStop,calStart;
String defaultDate="YYYY-MM-DD HH:MM:SS";
String[] strNum={"Number of events: ","Antal hndelser: "};
String[] msgStart={"Enter start date and time","Ange startdatum och tid"};
String[] msgStop={"Enter stop date and time","Ange stoppdatum och tid"};
String[] errorDate={"Dates must be specified on the form YYYY-MM-DD HH:MM:SS \n"+
"e.g 1980-09-08 00:00:00", "Datum mste skrivas p formen YYYY-MM-DD HH:MM:SS \n"+
"t.ex 1980-09-08 00:00:00"};
/**** Menu + textstrings ****/
JMenu fileMenu, langMenu;
String[][] menuTitle = {{"File","Byt Sprk"},{"Arkiv","Change Language"}};
String[][] fileItems = {{"Copy result to excel","Quit"},{"Kopiera resultat till Excel","Avsluta"}};
String[][] langItems = {{"Svenska","English"},{"Svenska","English"}};
//****MIDDLE****
//middle contains the search condition and the search result.
JPanel middle = new JPanel();
//resultTable is the HistTable containing the search results.
HistTable result;
// result contains the table showing the search result.
//JTable result = new JTable(resultTable);
// lblCondition is the label showing the current search conditions.
JLabel lblCondition = new JLabel("",JLabel.LEFT);
// lblHead is the label showing the static text "Search condition"
JLabel lblHead = new JLabel("", JLabel.LEFT);
String[] descHead = {"<HTML><U>Search condition</U></HTML>",
"<HTML><U>Skvillkor</U></HTML>"};
HistQuery currentSearch;
public JButton btnStat;
class WindowExit extends WindowAdapter{
public void windowClosing(WindowEvent ev){
}
}
void HistSearch_WindowClosing(WindowEvent event) {
dispose();
}
//Default constructor
public HistSearch(){
engine = new JopEngine( 1000, (Object)this);
session = new JopSession( engine, (Object)this);
root = (Object) this;
setup();
}
public HistSearch( JopSession s)
{
session = s;
engine = session.getEngine();
root = session.getRoot();
setup();
}
public HistSearch(String q , JopSession s)
{
session = s;
engine = session.getEngine();
root = session.getRoot();
setup();
txName.setText("*" + q + "*");
doSearch();
}
private void setup(){
result =new HistTable(lang,session);
/* A mouse listener is added to the alarmTable from here because
the result of the double click affects components of the HistSearch.
To add the listener like this avoids compilation order problems.*/
result.alarmTable.addMouseListener(new MouseAdapter() {
/***** MOUSE LISTENER CODE START *****/
//Bring up a JopMethodsMenu
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=result.alarmTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) result.atModel.mhData.eventVec.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) result.alarmTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
int row=result.alarmTable.rowAtPoint(e.getPoint());
result.alarmTable.setRowSelectionInterval(row,row);
if ( e.isPopupTrigger()) {
MhrEvent event = (MhrEvent) result.atModel.mhData.eventVec.get(row);
String trace_object= event.eventName;
new JopMethodsMenu(session,
trace_object,
JopUtility.TRACE,(Component) result.alarmTable,
e.getX(), e.getY());
return;
}
}
//On double click copy name or text to corresponding textfields.
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
String tempStr="";
int row=result.alarmTable.rowAtPoint(e.getPoint());
if(result.alarmTable.columnAtPoint(e.getPoint())==3){
if (txText.getText().length() > 0)
tempStr=txText.getText() + ";";
tempStr=tempStr + "*" +
(String)result.alarmTable.getValueAt(row,3) + "*";
txText.setText(tempStr);
}
else{
if (txName.getText().length() > 0 )
tempStr=txName.getText() + ";";
tempStr=tempStr + "*" +
(String)result.alarmTable.getValueAt(row,4) + "*";
txName.setText(tempStr);
}
}
}
/**** MOUSE LISTENER CODE STOP ****/
});
addWindowListener(new WindowExit());
addComponentListener(new minSizeListener(this));
this.setTitle("Hist Search");
// setup the searchbutton
btnSearch= new JButton(descSearch[lang]);
btnSearch.addActionListener(this);
btnSearch.setActionCommand("search");
btnSearch.setMnemonic('s');
// setup the statisticsbutton
btnStat= new JButton(descStat[lang]);
btnStat.setMnemonic('t');
btnStat.setActionCommand("stat");
btnStat.addActionListener(this);
//setup tht combobox.
cbWhen=new JComboBox(choice[lang]);
cbWhen.addActionListener(this);
//setup the start and stop dates.
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.YEAR,1970);
// setup the array of checkboxes
checkSetup();
//make sure all buttons and labels have text.
menuSetup();
updateText();
place();
//set comboBox to "thisYear" by deafult. setSelectedItem calls
//the action listener, so the dates update.
cbWhen.setSelectedItem(cbWhen.getItemAt(1));
updateDate();
}
//Place all onscreen objects
private void place(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(new BorderLayout());
middleSetup();
topSetup();
contentPane.add("North",top);
contentPane.add("Center",middle);
contentPane.add("South",btnStat);
}
private void menuSetup(){
// set up the menu structure, with language choices.
this.setJMenuBar (new JMenuBar());
fileMenu=new JMenu(menuTitle[lang][0]);
fileMenu.setMnemonic(fileMenu.getText().charAt(0));
langMenu=new JMenu(menuTitle[lang][1]);
langMenu.setMnemonic(langMenu.getText().charAt(0));
for(int i=0; i< fileItems.length; i++){
JMenuItem item = new JMenuItem(fileItems[lang][i]);
item.addActionListener(this);
item.setMnemonic(item.getText().charAt(0));
fileMenu.add(item);
}
for(int i=0; i< langItems.length; i++){
JMenuItem item = new JMenuItem(langItems[lang][i]);
item.addActionListener(this);
item.setMnemonic(item.getText().charAt(0));
langMenu.add(item);
}
this.getJMenuBar().add(fileMenu);
this.getJMenuBar().add(langMenu);
}
private void middleSetup(){
//Setup the layout for the middle part of the screen.
middle.setLayout(new BorderLayout());
JPanel condition = new JPanel();
condition.setLayout(new BorderLayout());
condition.add("North",lblHead);
Dimension d = lblCondition.getSize();
d.height +=80;
lblCondition.setPreferredSize(d);
condition.add("Center", lblCondition);
middle.add("North",condition);
d = result.getSize();
result.setPreferredSize(d);
middle.add("Center", result);
}
private void topSetup(){
GridBagLayout topLayout = new GridBagLayout();
GridBagConstraints topC = new GridBagConstraints();
top.setLayout(topLayout);
// 1st row
topC.gridx=0;
topC.gridy=0;
topC.weightx=0;
topC.fill=GridBagConstraints.BOTH;
topC.anchor=GridBagConstraints.CENTER;
topC.insets= new Insets(2,2,5,5);
// Start time label
topLayout.setConstraints(lblStart, topC);
top.add(lblStart);
// Start time textfield
topC.gridx=1;
topC.weightx=1;
txStart = new JTextField (defaultDate);
txStart.setEditable(false);
txStart.setColumns(19);
topLayout.setConstraints(txStart, topC);
top.add(txStart);
//Stop time label
topC.gridx=2;
topC.weightx=0;
topLayout.setConstraints(lblStop, topC);
top.add(lblStop);
//Stop time textfield
topC.gridx=3;
topC.weightx=1;
topC.gridwidth=GridBagConstraints.RELATIVE;
txStop = new JTextField (defaultDate);
txStop.setEditable(false);
txStop.setColumns(19);
topLayout.setConstraints(txStop, topC);
top.add(txStop);
//Search interval combobox.
topC.gridx=4;
topC.gridwidth=GridBagConstraints.REMAINDER;
topLayout.setConstraints(cbWhen, topC);
top.add(cbWhen);
// 2nd & 3rd rows
// add the array of check boxes
topC.gridx=0;
topC.gridy=1;
topC.weightx=0;
topC.gridwidth=4;
topC.gridheight=2;
topLayout.setConstraints(check, topC);
top.add(check);
// 4th row
topC.gridx=0;
topC.gridy=3;
topC.gridwidth=1;
topC.gridheight=1;
// Event name time label
topLayout.setConstraints(lblName, topC);
top.add(lblName);
//Event name textfield
topC.gridx=1;
topC.gridwidth=GridBagConstraints.REMAINDER;
txName = new JTextField();
topLayout.setConstraints(txName, topC);
top.add(txName);
// 5th row
topC.gridx=0;
topC.gridy=4;
topC.gridwidth=1;
// Event name time label
topLayout.setConstraints(lblText, topC);
top.add(lblText);
//Event name textfield
topC.gridx=1;
topC.gridwidth=GridBagConstraints.REMAINDER;
txText = new JTextField();
topLayout.setConstraints(txText, topC);
top.add(txText);
// 6th row
topC.gridx=0;
topC.gridy=5;
topC.gridwidth=1;
// Number of events label
updateNum();
topLayout.setConstraints(lblNum, topC);
top.add(lblNum);
//The search button
topC.gridx=2;
topLayout.setConstraints(btnSearch, topC);
top.add(btnSearch);
}
private void checkSetup(){
// make the layout of the checkbox array a GridLayout. Add the event Type label.
check.setLayout(new GridLayout(2,5));
check.add(lblType);
//For loop adding the four type checkboxes with name tags
for (int i=0;i<4;i++){
type[i]=new JCheckBox(nameType[lang][i]);
check.add(type[i]);
}
// Add the Event priority label
check.add(lblPriority);
//For loop adding the four priority checkboxes with name tags.
for (int i=0;i<4;i++){
priority[i]=new JCheckBox(namePriority[i]);
check.add(priority[i]);
}
}
//Update the number of events label in the correct language.
private void updateNum(){
num=result.getNrOfResults();
lblNum.setText(strNum[lang]+num);
}
// All labels are updated in the current language (0 = English, 1 = Swedish)
private void updateText(){
// the combo box needs to be relableled according to language
// but not during initiation, hence the if statement...
if(txStart!=null){
cbWhen.removeAllItems();
for(int i=0;i<choice[lang].length;i++)
cbWhen.addItem(choice[lang][i]);
}
// the search button needs to be relabeled each time the language changes
btnSearch.setText(descSearch[lang]);
/*the checkboxes for type needs relabeling aswell. Not the priority checkboxes
since there's no difference in language...*/
for(int i=0; i<nameType[lang].length;i++){
type[i].setText(nameType[lang][i]);
}
// All labels are updated to show the right language.
lblStart.setText(descStart[lang]);
lblStop.setText(descStop[lang]);
lblType.setText(descType[lang]);
lblPriority.setText(descPriority[lang]);
lblName.setText(descName[lang]);
lblText.setText(descText[lang]);
lblHead.setText(descHead[lang]);
updateNum();
//Update the text in the menus. Easily done by remaking it...
menuSetup();
//update the result table headers
result.updateLang(lang);
//update the btnStat text.
btnStat.setText(descStat[lang]);
}
private void updateDate(){
txStart.setText(dateText(calStart));
txStop.setText(dateText(calStop));
}
// Update the text in the Start & Stop Textfields. Adjust x<10 to 0x
private String dateText(Calendar cal){
String text=""+cal.get(Calendar.YEAR)+"-";
if(cal.get(Calendar.MONTH)<9) text = text + "0";
text = text + (cal.get(Calendar.MONTH)+1)+"-";
if(cal.get(Calendar.DATE)<10) text = text + "0";
text = text +cal.get(Calendar.DATE)+" ";
if(cal.get(Calendar.HOUR_OF_DAY)<10) text = text +"0";
text = text+ cal.get(Calendar.HOUR_OF_DAY)+":";
if(cal.get(Calendar.MINUTE)<10) text = text +"0";
text = text +cal.get(Calendar.MINUTE)+":";
if(cal.get(Calendar.SECOND)<10) text = text + "0";
text = text + cal.get(Calendar.SECOND);
return text;
}
/* the action listener methods of this object. Checks on ComboBox, searchbutton
and menu options */
public void actionPerformed(ActionEvent e){
if (e.getSource()==cbWhen){
switch(cbWhen.getSelectedIndex()){
//all entries
case 0:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.YEAR,1970);
updateDate();
break;
//this year
case 1:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.MONTH,0);
calStart.set(Calendar.DATE,1);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//this month
case 2:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.DATE,1);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//this week
case 3:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
int diff = calStart.get(Calendar.DAY_OF_WEEK)-Calendar.MONDAY;
calStart.add(Calendar.DATE,-1*diff);
if (diff<0) calStart.add(Calendar.DATE,-7);
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//today
case 4:
calStop = Calendar.getInstance();
calStart = Calendar.getInstance();
calStart.set(Calendar.HOUR_OF_DAY,0);
calStart.set(Calendar.MINUTE,0);
calStart.set(Calendar.SECOND,0);
updateDate();
break;
//enter dates
case 5:
//routine for Start time input dialog
HistDateChooser tempDate = new HistDateChooser(calStart,lang);
int buttonPressed = JOptionPane.showOptionDialog(this,tempDate,msgStart[lang],JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,null,null);
if (buttonPressed == JOptionPane.OK_OPTION){
calStart=tempDate.getDate();
//routine for Stop time input dialog
tempDate = new HistDateChooser(calStop,lang);
buttonPressed = JOptionPane.showOptionDialog(this,tempDate,msgStop[lang],JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,null,null);
if (buttonPressed == JOptionPane.OK_OPTION){
calStop=tempDate.getDate();
}
}
updateDate();
break;
default:
updateDate();
break;
}
}
// Handling of search button event.
if(e.getActionCommand()=="search"){
doSearch();
}
if (e.getActionCommand()=="stat"){
result.presentStat();
}
// the handling of menu events
if(e.getActionCommand()=="Copy result to excel"||e.getActionCommand()=="Kopiera resultat till Excel"){
// check if the root is an applet
try{
Applet source = (Applet) root;
/* //XLS Method for exporting an excel file from an applet
// Uses a javascript from the page that started the applet.
JSObject javaScript = JSObject.getWindow(source);
if (javaScript != null){
Object[] args = new Object[1];
args[0]=result.exportExcelFromApplet();
javaScript.call("appletHtml", args);
} */
}
catch(Exception ex){
//No applet, copy to system clipboard.
result.exportExcel();
}
}
if(e.getActionCommand()=="Quit"||e.getActionCommand()=="Avsluta"){
this.dispose();
}
if(e.getActionCommand()=="Svenska"){
lang=1;
updateText();
}
if(e.getActionCommand()=="English"){
lang=0;
updateText();
}
}
private void doSearch(){
lblCondition.setFont(new Font("SansSerif", Font.PLAIN, 14));
lblCondition.setForeground(new Color(0x000000));
lblCondition.setText(evalSearch(lang));
lblCondition.validate();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
result.performSearch(root,currentSearch);
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
updateNum();
}
// Returns a string showing all search criteria and sets the currentSearch
public String evalSearch(int lang){
//Useful words in english and swedish.
String[][] words ={{"All ", " Active", " Message", " Return", " Acknowlegement", " events"," with"," priority"," name"," text", " from "," to "," or"},
{"Alla", " Aktiv", " Meddelande", " Retur", " Kvittens", " hndelser"," med"," prioritet"," namn"," text", " fr.o.m. ", " t.o.m. ", " eller"}};
String eval="<html>" + words[lang][0];
String temp="";
boolean[] noCheck ={true,true};
boolean[] typeSelected = {false,false,false,false};
boolean[] prioSelected = {false,false,false,false};
for (int i=0;i<4;i++){
if (type[i].isSelected()){
typeSelected[i]=true;
if (noCheck[0]) noCheck[0]=false;
else eval=eval+words[lang][12];
eval=eval + "<b>" +words[lang][i+1] + "</b>";
}
if (priority[i].isSelected()){
prioSelected[i]=true;
if (noCheck[1]) noCheck[1]=false;
else temp=temp+words[lang][12];
int charA =(int)'A';
charA=charA+i;
temp=temp + " <b>" + (char) charA + "</b>";
}
}
eval= eval + words[lang][5] + " ";
if (temp.length()>0) {
eval=eval+ words[lang][6] + temp + words[lang][7] ;
}
eval=eval+"<br>"+words[lang][6]+words[lang][8]+" <b>"+txName.getText() +"</b><br>";
eval=eval+words[lang][6]+words[lang][9]+" <b>"+txText.getText() +"</b><br>";
eval=eval + words[lang][10] + "<b>"+ dateText(calStart)+ "</b>" + words[lang][11] + "<b>" + dateText(calStop)+"</b> </html>";
String nameFormatted= txName.getText().replace('"','*');
String textFormatted= txText.getText().replace('"','*');
//Setup the current search for transfer to server
currentSearch=new HistQuery(dateText(calStart), dateText(calStop),typeSelected,prioSelected,nameFormatted,textFormatted);
return eval;
}
public class minSizeListener implements ComponentListener {
static final int MIN_WIDTH=600;
static final int MIN_HEIGHT=480;
private HistSearch as;
public minSizeListener(HistSearch a){
as=a;
}
public void componentResized(ComponentEvent e) {
int width = as.getWidth();
int height = as.getHeight();
boolean resize=false;
//we check if either the width
//or the height are below minimum
if (width < MIN_WIDTH) {
width = MIN_WIDTH;
resize=true;
}
if (height < MIN_HEIGHT) {
height = MIN_HEIGHT;
resize=true;
}
if (resize)
as.setSize(width, height);
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
//Testprogram
public static void main(String args[]){
HistSearch ASWindow = new HistSearch();
ASWindow.pack();
ASWindow.show();
}
}
package jpwr.jop;
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.Vector;
import jpwr.rt.*;
/* The HistSender initiates a socket to the server and can then perform a
*SearchRequest given a HistQuery using an ObjectInput- and an
*ObjectOutputStream.*/
public class HistSender {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
Object root;
final static int PORT = 4447;
public HistSender(Object r){
root=r;
setup();
}
// initiate the socket to the server
private void setup(){
try {
URL url;
String urlString = "192.168.60.16";
try {
url = ((JApplet)root).getCodeBase();
if(url != null)
urlString = url.getHost();
}
catch(Exception e)
{
System.out.println("Program not run from applet..."+e);
}
socket = new Socket(urlString, PORT);
}
catch(UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
//System.exit(1);
}
catch(IOException e) {
JOptionPane.showMessageDialog(null,"Couldn't get contact with the server (HistServer). \n Kunde inte ansluta till servern(HistServer).","I/O Error",JOptionPane.ERROR_MESSAGE);
}
}
public MhData SearchRequest(HistQuery search){
// Open output and input streams.
try
{
out = new ObjectOutputStream( socket.getOutputStream() );
out.flush();
//varfr???
in = new ObjectInputStream( socket.getInputStream() );
}
catch(Exception e)
{
System.out.println("IOException vid skapande av strmmar mot server");
//errh.error("DataStream failed");
return new MhData(100,100);
}
//Send search request
try
{
out.writeObject(search);
out.flush();
}
catch(Exception e)
{
System.out.println("Search send Exception");
}
// Start receiving data
MhData answer = new MhData(0,0);
try
{
MhrEvent[] result = (MhrEvent[])in.readObject();
int i = 0;
while(i < result.length)
{
answer.addMessToVectorInSortedOrder(answer.eventVec, result[i++]);
}
}
catch(Exception e) {
System.out.println("#"+e.toString());
}
//Close input and output streams
try
{
in.close();
out.close();
}
catch(Exception e)
{
System.out.println("Error while closing streams: " + e);
}
return answer;
}
}
package jpwr.jop;
import java.util.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.*;
/*The HistStatModel1 class is used to derive how many times an Alarm has been
set off during the interval of the search provided in a MhData.*/
public class HistStatModel1 extends AbstractTableModel{
// The List storing the resulting statistics.
public List result;
private String[][] freqNames={{"Object", "Nr. of alarms" },{"Objekt","Antal larm"}};
int lang;
public HistStatModel1(MhData m, int l ){
lang=l;
clearData();
setData(m);
sortData();
}
public void clearData(){
result = new ArrayList();
}
public void setData(MhData m){
/* The MhData is Stepped through. If an Alarm is found which eventName
is not yet present in the result List, a copy of the Alarm's
MhrEvent is added to the result List. If an alarm is found that is
present in the result List the nr of times the alarm has been found
is increased by one. The nr of times is stored in the int
eventFlags of each MhrEvent in the result List*/
for(int i=0; i<m.eventVec.size();i++){
boolean found=false;
for (int j = 0; j<result.size();j++){
if (((MhrEvent) m.eventVec.get(i)).eventName.equals(((MhrEvent)(result.get(j))).eventName)){
if(((MhrEvent) m.eventVec.get(i)).eventType == Mh.mh_eEvent_Alarm){
((MhrEvent)(result.get(j))).eventFlags++;
found=true;
}
}
if (found) break;
}
if (! found){
if(((MhrEvent) m.eventVec.get(i)).eventType == Mh.mh_eEvent_Alarm){
result.add(((MhrEvent)(m.eventVec.get(i))).getCopy());
((MhrEvent)result.get(result.size()-1)).eventFlags=1;
}
}
}
}
public Object getValueAt(int r,int c){
if (c==0) return ((MhrEvent)result.get(r)).eventName;
else return new Integer(((MhrEvent)result.get(r)).eventFlags);
}
public int getRowCount(){
return result.size();
}
public int getColumnCount(){
return freqNames.length;
}
public String getColumnName(int i){
return freqNames[lang][i];
}
public void sortData(){
//sortData sorts the result List. Largest number of times found first.
Collections.sort(result, new Comparator(){
public int compare(Object o1, Object o2){
if (((MhrEvent)o1).eventFlags < ((MhrEvent)o2).eventFlags)
return 1;
else if (((MhrEvent)o1).eventFlags > ((MhrEvent)o2).eventFlags)
return -1;
else return 0;
}
});
}
}
package jpwr.jop;
import java.util.*;
import java.util.regex.*;
import javax.swing.table.AbstractTableModel;
import jpwr.rt.*;
/* HistStatModel2 is an AbstractTableModel that derives information on the
duration of alarms (Active to Return) supplied in a MhData. Proper methods
for displaying the results as a table ar included aswell... */
public class HistStatModel2 extends AbstractTableModel{
// The List holding the statistics
List result;
private String[][] names={{"Object", "Duration time" },{"Objekt", "Varaktighet"}};
int lang;
//Constructor
public HistStatModel2(MhData m, int l ){
lang=l;
clearData();
setData(m);
sortData();
}
public void clearData(){
result = new ArrayList();
}
public void setData(MhData m){
/* All elements in the MhData eventVec are stepped through, looking for
Alarms. When one is found the rest are looked through, looking for a
matching Return (the Return's target.birthTime = the Alarm's
birthTime). If a matching Return is found the a copy of the alarm's
MhrEvent is stored in the result List with the int eventFlags used
as a storage for the duration time.*/
for(int i=m.eventVec.size()-1; i>0;i--){
boolean found=false;
int timeDiff=0;
if (((MhrEvent)m.eventVec.get(i)).eventType==Mh.mh_eEvent_Alarm){
for(int j=i-1; j>=0;j--){
if (((MhrEvent) m.eventVec.get(j)).targetId.birthTime.equals(((MhrEvent) m.eventVec.get(i)).eventId.birthTime))
if (((MhrEvent)m.eventVec.get(j)).eventType==Mh.mh_eEvent_Return){
found=true;
// The duration is calculated in seconds. The
//duration is limited to at most two months.
Pattern p = Pattern.compile("[\\s-:.]");
String[] stop=p.split(((MhrEvent) m.eventVec.get(j)).eventTime);
int month = new Integer(stop[1]).intValue();
int day = new Integer(stop[2]).intValue();
int hour = new Integer(stop[3]).intValue();
int minute = new Integer(stop[4]).intValue();
int second = new Integer(stop[5]).intValue();
int millis = new Integer(stop[6]).intValue();
String[] start=p.split(((MhrEvent) m.eventVec.get(i)).eventTime);
month -= new Integer(start[1]).intValue();
if (month > 0){
month = new Integer(stop[1].charAt(2)).intValue();
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day+=31;
break;
case 4:
case 6:
case 9:
case 11:
day+=30;
break;
case 2:
day+=28;
default:
break;
}
}
day = day - new Integer(start[2]).intValue();
hour = hour- new Integer(start[3]).intValue();
minute -= new Integer(start[4]).intValue();
second = second - new Integer(start[5]).intValue();
millis -= new Integer(start[6]).intValue();
timeDiff= second + 60*minute + 3600*hour +
3600*24*day;
}
if (found) break;
}
}
if (found){
result.add(((MhrEvent)m.eventVec.get(i)).getCopy());
((MhrEvent)result.get(result.size()-1)).eventFlags=timeDiff;
}
}
}
public Object getValueAt(int r,int c){
if (c==0) return ((MhrEvent)result.get(r)).eventName;
else {
int temp = ((MhrEvent)result.get(r)).eventFlags;
//Format a String showing the duration in days, hours, minutes
// and seconds.
String retString= "" + (temp/(3600*24)) + "D ";
temp = temp%(3600*24);
retString= retString + (temp/(3600)) + "H ";
temp = temp%(3600);
retString= retString + (temp/(60)) + "M ";
temp = temp%(60);
retString= retString + (temp) + "S " ;
return retString;
}
}
public int getRowCount(){
return result.size();
}
public int getColumnCount(){
return names.length;
}
public String getColumnName(int i){
return names[lang][i];
}
//sortData sorts the result List based on duration (the value of
//eventFlags).Longest duration on top.)
public void sortData(){
Collections.sort(result, new Comparator(){
public int compare(Object o1, Object o2){
if (((MhrEvent)o1).eventFlags < ((MhrEvent)o2).eventFlags) return 1;
else if (((MhrEvent)o1).eventFlags > ((MhrEvent)o2).eventFlags) return -1;
else return 0;
}
});
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
import jpwr.rt.*;
/* The HistStatistics class is a JPanel containing two JTables showing
statistics derived from the MhData supplied in the constructor. The tables
get their contents from a HistStatModel1 and an HistStatModel2. The tables support
the use of JopMethodsMenu.*/
public class HistStatistics extends JPanel{
// The session is needed for the use of JopMethodsMenu
private JopSession session;
private JTable fTable, eTable;
private HistStatModel1 fModel;
private HistStatModel2 eModel;
JScrollPane fScroll, eScroll;
int lang;
String[][] names = {{"Most frequent alarms","Longest duration"},{"Mest frekventa alarm","Lngst varaktighet"}};
public HistStatistics(MhData m, int l, JopSession s){
//Setup and layout. (The only method of this class..)
session = s;
lang=l;
this.setLayout(new GridLayout(2,1));
JPanel upper = new JPanel();
upper.setLayout(new BorderLayout());
fModel=new HistStatModel1(m,lang);
fTable = new JTable(fModel);
fScroll= new JScrollPane(fTable );
fTable.getColumnModel().getColumn(0).setPreferredWidth(420);
fTable.getColumnModel().getColumn(1).setPreferredWidth(70);
//Mouse listener for fTable JopMethodMenu support.
fTable.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=fTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) fModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) fTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=fTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) fModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) fTable,
e.getX(), e.getY());
return;
}
}
public void mouseClicked(MouseEvent e) {
}
});
upper.add(fScroll,BorderLayout.CENTER);
upper.add(new JLabel(names[lang][0]), BorderLayout.NORTH);
upper.add(new JLabel("\n\n") , BorderLayout.SOUTH);
JPanel lower = new JPanel();
lower.setLayout(new BorderLayout());
eModel=new HistStatModel2(m,lang);
eTable = new JTable(eModel);
eScroll= new JScrollPane(eTable );
eTable.getColumnModel().getColumn(0).setPreferredWidth(420);
eTable.getColumnModel().getColumn(1).setPreferredWidth(70);
//Mouse listener for eTable JopMethodMenu support.
eTable.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=eTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) eModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) eTable,
e.getX(), e.getY());
return;
}
}
public void mousePressed(MouseEvent e) {
if ( e.isPopupTrigger()) {
int row=eTable.rowAtPoint(e.getPoint());
MhrEvent event = (MhrEvent) eModel.result.get(row);
String trace_object= event.eventName;
new JopMethodsMenu( session,
trace_object,
JopUtility.TRACE,(Component) eTable,
e.getX(), e.getY());
return;
}
}
public void mouseClicked(MouseEvent e) {
}
});
lower.add(eScroll,BorderLayout.CENTER);
lower.add(new JLabel(names[lang][1]), BorderLayout.NORTH);
this.setPreferredSize(new Dimension(600, 500));
this.add(upper);
this.add(lower);
}
}
package jpwr.jop;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.io.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import jpwr.rt.*;
/* HistTable is an extended JScrollPane containing the
* a JTable alarmTable. The HistTable also contains methods for exporting
* the alarmTable to an excel file, and for performing a search in the historic
* event list using a HistSender */
public class HistTable extends JScrollPane{
JopSession session;
boolean DEBUG=false;
public EventTableModel atModel;
public JTable alarmTable;
String[][] columnNamesEventTable = {{"P","Type","Time","Description text","Event name"},{"P",
"Typ",
"Tid",
"Hndelsetext",
"Objekt"}};
String[][] excelMess=
{
{"Copy to Excel","Your search result has been put on the Clipboard.\nOpen a new document in Excel and choose \"Paste\" from the Edit menu\nto create a Worksheet with your search result."},
{"Kopiera till Excel","Ditt skresultat har nu lagrats i Urklipp.\nppna ett nytt dokument i Excel och vlj \"Klistra in\" i Redigeramenyn\nfr att skapa ett Excelark med ditt skresultat."}
};
int lang=0;
// Language sensitive constructor
public HistTable(int l, JopSession s){
session = s;
lang=l;
setup();
}
//Layout the HistTable. Add a mouse Listener to the JTable alarmTable
//and set it up to support JopMethodsMenu.
private void setup(){
atModel = new EventTableModel(lang);
alarmTable = new JTable(atModel);
alarmTable.setCellEditor(null);
this.initColumnSizes(alarmTable, atModel);
alarmTable.getTableHeader().setReorderingAllowed(false);
alarmTable.getColumn((Object)columnNamesEventTable[lang][0]).setCellRenderer(new EventTableCellRender());
this.setViewportView(alarmTable);
this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.getViewport().setBackground(Color.white);
((EventTableModel)alarmTable.getModel()).updateTable();
}
//Update the table headers to the correct language.
public void updateLang(int l){
lang=l;
for (int i=0; i<alarmTable.getColumnCount();i++)
alarmTable.getColumnModel().getColumn(i).setHeaderValue(columnNamesEventTable[lang][i]);
alarmTable.getTableHeader().resizeAndRepaint();
}
/*Get a pointer to the local Clipboard, format a string with all cell
elements with \t between columns and \n between rows and put it on
the clipboard. Display a message telling how to paste the string to
excel*/
public void exportExcel(){
StringBuffer copybuffer = new StringBuffer("");
for(int i=0;i<alarmTable.getRowCount();i++){
for (int j=0; j<alarmTable.getColumnCount();j++){
copybuffer.append((String) alarmTable.getValueAt(i,j));
copybuffer.append("\t");
}
copybuffer.append("\n");
}
Clipboard cb= Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection output = new StringSelection(copybuffer.toString());
cb.setContents(output, output);
JOptionPane.showMessageDialog(this.getParent(),excelMess[lang][1],excelMess[lang][0],JOptionPane.INFORMATION_MESSAGE);
}
//XLS
//Creates a String for sending to a javascript which can save to a file.
public String exportExcelFromApplet(){
String copyString = "";
for(int i=0;i<alarmTable.getRowCount();i++){
for (int j=0; j<alarmTable.getColumnCount();j++){
copyString = copyString +(String) alarmTable.getValueAt(i,j);
copyString = copyString+"\t";
}
copyString = copyString + "\n" ;
}
return copyString;
}
//Set column sizes to fit the table contents...
private void initColumnSizes(JTable table, AbstractTableModel model)
{
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues;
longValues = ((EventTableModel)(model)).longValues;
for(int i = 0; i < longValues.length; i++)
{
column = table.getColumnModel().getColumn(i);
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if(DEBUG)
{
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
}
//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
if(i == 0)
{
column.setMaxWidth(Math.max(headerWidth, cellWidth));
column.setResizable(false);
}
}
}
public void presentStat(){
// Derive interesting statistics from the current searchresult and
//display it in a JFrame...
HistStatistics statistics = new HistStatistics(atModel.mhData,lang,session);
JFrame frame = new JFrame();
JPanel panel = (JPanel)frame.getContentPane();
panel.setLayout(new FlowLayout());
panel.add(statistics);
frame.pack();
frame.show();
}
public int getNrOfResults(){
return alarmTable.getRowCount();
}
// Make a search in the Historical Event list based on the HistQuery search
public void performSearch(Object root, HistQuery search){
HistSender sender = new HistSender(root);
atModel.setMhData(sender.SearchRequest(search));
}
}
......@@ -79,6 +79,15 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
popup.add( item = new JMenuItem( "Circuit Diagram"));
item.addActionListener( this);
}
if ( classGraphFilter()) {
popup.add( item = new JMenuItem( "ClassGraph"));
item.addActionListener( this);
}
if (openSearchFilter()){
popup.add(item= new JMenuItem( "Hist Search"));
item.addActionListener( this);
}
popup.addPopupMenuListener( this);
popup.show( invoker, x, y);
session.getEngine().add(this);
......@@ -114,6 +123,12 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
else if ( event.getActionCommand().equals("Circuit Diagram")) {
circuitDiagram();
}
else if ( event.getActionCommand().equals("ClassGraph")) {
classGraph();
}
else if ( event.getActionCommand().equals("Hist Search")) {
openSearch();
}
}
//
......@@ -317,6 +332,54 @@ public class JopMethodsMenu implements ActionListener, PopupMenuListener,
session.executeCommand( cmd);
}
public boolean classGraphFilter() {
if ( classid == Pwrs.cClass_Node)
return true;
CdhrObjid coid = gdh.classIdToObjid( classid);
if ( coid.evenSts()) return false;
CdhrString sret = gdh.objidToName( coid.objid, Cdh.mName_object);
if ( sret.evenSts()) return false;
String name;
if ( coid.objid.vid < Cdh.cUserClassVolMin) {
// Class is a base class, java classname starts with JopC_
if ( coid.objid.vid == 1)
name = "jpwr.jopc.Jopc" + sret.str.substring(1,2).toUpperCase() +
sret.str.substring(2).toLowerCase();
else
name = "jpwr.jopc.Jopc" + sret.str.substring(0,1).toUpperCase() +
sret.str.substring(1).toLowerCase();
}
else
// Java name equals class name
name = sret.str.substring(0,1).toUpperCase() + sret.str.substring(1).toLowerCase();
try {
Class clazz = Class.forName( name);
}
catch ( Exception e) {
return false;
}
return true;
}
public void classGraph() {
String cmd = "open graph /class /instance=" + object;
System.out.println( "classGraph: " + cmd);
session.executeCommand( cmd);
}
public boolean openSearchFilter(){
// XXX If needed, this is the place to filter what
// objects are searchable.
return true;
}
public void openSearch(){
session.openSearch(object);
}
public boolean isVisible() {
return popup.isVisible();
}
......
......@@ -96,6 +96,10 @@ public class JopSession {
public boolean isOpWindowApplet() {
return ((JopSessionIfc) sessionRep).isOpWindowApplet();
}
public void openSearch(String object ){
((JopSessionIfc) sessionRep).openSearch(object);
}
}
......@@ -106,3 +110,4 @@ public class JopSession {
......@@ -21,4 +21,5 @@ public interface JopSessionIfc {
public boolean isApplet();
public boolean isApplication();
public boolean isOpWindowApplet();
public void openSearch(String object);
}
......@@ -114,6 +114,19 @@ public class JopSessionRep implements JopSessionIfc {
CdhrString sret = engine.gdh.objidToName( coid.objid, Cdh.mName_object);
if ( sret.evenSts()) return;
System.out.println( "open frame: vid " + coid.objid.vid);
if ( coid.objid.vid < Cdh.cUserClassVolMin) {
// Class is a base class, java classname starts with JopC_
if ( coid.objid.vid == 1)
name = "jpwr.jopc.Jopc" + sret.str.substring(1,2).toUpperCase() +
sret.str.substring(2).toLowerCase();
else
name = "jpwr.jopc.Jopc" + sret.str.substring(0,1).toUpperCase() +
sret.str.substring(1).toLowerCase();
}
else
// Java name equals class name
name = sret.str.substring(0,1).toUpperCase() + sret.str.substring(1).toLowerCase();
}
}
......@@ -207,6 +220,12 @@ public class JopSessionRep implements JopSessionIfc {
public boolean isOpWindowApplet() {
return ( root instanceof JopOpWindowApplet);
}
public void openSearch(String object){
HistSearch HSWindow = new HistSearch(object,session );
HSWindow.pack();
HSWindow.show();
}
}
......
package jpwr.jop;
import java.awt.*;
/* The Proportion class is used when using the RatioLayout layoutmanager. It
makes sure that the object associated with it keeps its proportions
when the frame is resized. */
public class Proportion {
//The ratios in x,y position and width, height
public double rx,ry,rw,rh;
public Dimension previous;
public boolean firstDraw =true;
// constructor. area= the size and place of an object. framesize
//is the size of the frame in which it is placed.
public Proportion(Rectangle area, Dimension framesize){
rx= (double) (1.0*area.x/framesize.width);
ry= (double) (1.0*area.y/framesize.height);
rw= (double) (1.0*area.width/framesize.width);
rh= (double) (1.0*area.height/framesize.height);
previous= new Dimension(1,1);
}
// For debuging purposes...
public String toString(){
return ""+rx+" "+ry+" "+rw+" "+rh+" "+previous+" "+firstDraw;
}
}
package jpwr.jop;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import jpwr.jop.*;
import java.beans.Beans;
/** RatioLayout.java -- Layout manager for Java containers
*
* This layout manager allows you to specify ratios of x,y,width,height
* using a Proportion object.
*
* For example,
*
* setLayout(new RatioLayout());
* add( myObject, new Proportion(myObject.getBounds(), this.getSize()));
*
* @author Mats Trovik inspired by RatioLayout.java by Terence Parr
*
*/
public class RatioLayout implements LayoutManager2 {
// track the ratios for each object of form "xratio,yratio;wratio,hratio"
Vector ratios = new Vector(1);
// track the components also so we can remove associated modifier
// if necessary.
Vector components = new Vector(1);
public void addLayoutComponent(String r, Component comp) {
}
// The used method for adding components.
public void addLayoutComponent(Component comp, Object o){
Proportion r = (Proportion) o;
ratios.addElement(r);
components.addElement(comp);
}
//Maximum layout size depends on the target (as opposed to the normal case)
public Dimension maximumLayoutSize(Container target){
return target.getSize();
}
public float getLayoutAlignmentX(Container target){
//The layout is left aligned
return (float) 0.0;
}
public float getLayoutAlignmentY(Container target){
//the layout is top aligned
return (float) 0.0;
}
//Reset the Layout
public void invalidateLayout(Container target){
Vector ratios = new Vector(1);
Vector components = new Vector(1);
}
// Remove component from Layout
public void removeLayoutComponent(Component comp) {
int i = components.indexOf(comp);
if ( i!=-1 ) {
ratios.removeElementAt(i);
components.removeElementAt(i);
}
}
public Dimension preferredLayoutSize(Container target) {
return target.getSize();
}
public Dimension minimumLayoutSize(Container target) {
return target.getSize();
}
public void layoutContainer(Container target) {
Insets insets = target.getInsets();
int ncomponents = target.getComponentCount();
Dimension d = target.getSize();
//make sure to not draw over the insets.(Java standard)
d.width -= insets.left+insets.right;
d.height -= insets.top+insets.bottom;
//Layout each component
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = target.getComponent(i);
Proportion compProp=(Proportion)ratios.elementAt(i);
//Set the width and height according to the ratio specified when
//the component was added.
int w = (int)(d.width*compProp.rw);
int h = (int)(d.height*compProp.rh);
// set x & y to the ratio specified when the component was added.
//These values will be changed if the comonent is a slider or
//a moving GeComponent.
int x = (int) (d.width*compProp.rx);
int y = (int) (d.height*compProp.ry);
if(comp instanceof GeComponent){
GeComponent tempComp= (GeComponent) comp;
//If the component is of type mDynType_Move...
if((tempComp.dd.dynType & GeDyn.mDynType_Move) != 0){
if (compProp.firstDraw){
// ... and it's drawn for the first time, store the
//parent's dimension in Proportion.previous,
compProp.firstDraw=false;
compProp.previous.setSize(d.width,d.height);
}
else{
/*... and it's drawn for at least the 2nd time, the
*place where to draw it is caculated from the ratio
*between the the current dimensions of the parent and
*the previous dimensions (before resize)
*of the parent multiplied with the position of the
*object. Care is taken to only adjust the position in
*the direction(s) specified by the GeDynMove.moveX(Y)Attribute.
*The current dimensions of the parent are stored
*in Proportion.previous.*/
for(int j=0;j<tempComp.dd.elements.length;j++)
{
if(tempComp.dd.elements[j] instanceof GeDynMove){
Rectangle compLoc = comp.getBounds();
if ((! ((GeDynMove)tempComp.dd.elements[j]).moveXAttribute.equals(""))){
double rx = (1.0*d.width /compProp.previous.width );
x = (int) (compLoc.x*rx);
}
if ((! ((GeDynMove)tempComp.dd.elements[j]).moveYAttribute.equals(""))){
double ry = (1.0*d.height/compProp.previous.height);
y = (int) (compLoc.y*ry);
}
}
compProp.previous.setSize(d.width,d.height);
}
}
}
//If the component is a slider...
else if((tempComp.dd.actionType & GeDyn.mActionType_Slider) != 0){
if (compProp.firstDraw){
// ... and it's drawn for the first time, store the
//parent's dimension in Proportion.previous,
compProp.firstDraw=false;
compProp.previous.setSize(d.width,d.height);
}
else{
/*... and it's drawn for at least the 2nd time,
*the direction of the slider is checked.
*The ratio between the target width or height
*(after resize) and the previous width or
*height is used to calculate the position
*fitting the new size. The current dimensions
*of the parent are stored in Proportion.previous.*/
for(int j=0;j<tempComp.dd.elements.length;j++)
{
if(tempComp.dd.elements[j] instanceof GeDynSlider){
Rectangle compLoc = comp.getBounds();
if (
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_LEFT
||
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_RIGHT){
double rx = (1.0*d.width /compProp.previous.width );
x = (int) (compLoc.x*rx);
}
else if (
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_UP
||
((GeDynSlider)tempComp.dd.elements[j]).direction == Ge.DIRECTION_DOWN){
double ry = (1.0*d.height/compProp.previous.height);
y = (int) (compLoc.y*ry);
}
}
}
compProp.previous.setSize(d.width,d.height);
}
}
}
//Place the component.
comp.setBounds(x+insets.left,y+insets.top,w,h);
//Resize the font of JTextFields.
if (comp instanceof JTextField){
comp.setFont(comp.getFont().deriveFont((float)(1.0*h*9/10)));
}
}
}
public String toString() {
return getClass().getName();
}
}
......@@ -24,6 +24,8 @@ import jpwr.rt.*;
public class XttTree extends JPanel
{
boolean findFieldEnable = false;
/*Mats frndringar ny boolean fr enterComm tillagd (enterFieldEnable)*/
boolean enterFieldEnable = false;
JPanel userPanel = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JPanel messagePanel = new JPanel();
......@@ -33,6 +35,7 @@ public class XttTree extends JPanel
JTextField userValue = new JTextField(25);
/** Description of the Field */
JLabel userValueLabel = new JLabel("Value input: ");
JLabel userCommandLabel = new JLabel("Command:");
JLabel labelMessage = new JLabel("Navigator ver 1.0");
Dimension size;
/** Description of the Field */
......@@ -56,7 +59,8 @@ public class XttTree extends JPanel
private DefaultTreeModel treeModel;
private URL url;
final JPopupMenu popup = new JPopupMenu();
//Mats frndringar: popup borttagen
//final JPopupMenu popup = new JPopupMenu();
InputMap inputMap = new InputMap();
ActionMap actionMap = new ActionMap();
......@@ -124,6 +128,11 @@ public class XttTree extends JPanel
String find_EN = "find...";
String find_SW = "sk...";
String find;
//Mats frndringar: strngar fr enterComm
String enterComm_EN = "enter command";
String enterComm_SW = "kommandorad";
String enterComm;
static final int SWEDISH = 0;
static final int ENGLISH = 1;
......@@ -172,6 +181,7 @@ public class XttTree extends JPanel
openPlc = openPlc_SW;
showCross = showCross_SW;
find = find_SW;
enterComm=enterComm_SW;
break;
case ENGLISH :
......@@ -185,6 +195,7 @@ public class XttTree extends JPanel
openPlc = openPlc_EN;
showCross = showCross_EN;
find = find_EN;
enterComm=enterComm_EN;
break;
}
//get all icons that is to be used in the tree
......@@ -291,19 +302,34 @@ public class XttTree extends JPanel
{
public void actionPerformed(ActionEvent evt)
{
if(!findFieldEnable)
/*Mats frndringar: Omstrukturering av ifsatser + en tillagd ifsats
fr enterFieldEnable*/
if(enterFieldEnable)
{
Logg.logg("XttTree: innan changeValue(" + userValue.getText() + ");", 6);
changeValue(userValue.getText());
Logg.logg("XttTree: innan enterCommand:(" + userValue.getText() + ");", 6);
enterComm(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userCommandLabel);
enterFieldEnable=false;
}
else
else if(findFieldEnable)
{
Logg.logg("XttTree: innan find(" + userValue.getText() + ");", 6);
find(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userValueLabel);
findFieldEnable=false;
}
tree.setRequestFocusEnabled(true);
else
{
Logg.logg("XttTree: innan changeValue(" + userValue.getText() + ");", 6);
changeValue(userValue.getText());
messagePanel.remove(userValue);
messagePanel.remove(userValueLabel);
}
tree.setRequestFocusEnabled(true);
messagePanel.add(labelMessage, BorderLayout.CENTER);
messagePanel.doLayout();
repaint();
......@@ -974,6 +1000,17 @@ public class XttTree extends JPanel
}
};
//Mats frndringar: Ny AbstractAction fr enterComm
AbstractAction COMM = new AbstractAction("COMM")
{
public void actionPerformed(ActionEvent evt)
{
enterComm();
}
};
/**
* Creates menuitem and keyboardbinding for a "method"
*
......@@ -985,7 +1022,9 @@ public class XttTree extends JPanel
*@param keyStroke A string representing the key-combination that is to be associated with the method
*@return Void
*/
public void newMethod(String name, Action action, String actionName, boolean toPopup, int toMenu, String keyStroke)
// Mats frndringar: booelan toPopup borttagen.
public void newMethod(String name, Action action, String actionName, /*boolean toPopup,*/ int toMenu, String keyStroke)
{
if(action != null)
{
......@@ -995,10 +1034,12 @@ public class XttTree extends JPanel
{
inputMap.put(KeyStroke.getKeyStroke(keyStroke), actionName);
}
/*
if(toPopup)
{
popup.add(menuItem(name, action, null));
}
*/
if(toMenu >= 0)
{
menubar.getMenu(toMenu).add(menuItem(name, action, keyStroke));
......@@ -1023,19 +1064,20 @@ public class XttTree extends JPanel
this.getRootPane().setJMenuBar(menubar);
//Mats frndringar: boolean toPopup borttagen ny metod fr enterComm
// Create some keystrokes and bind them to an action
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", true, 0, "ctrl A");
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", false, -1, "shift RIGHT");
this.newMethod("COLLAPSENODE", COLLAPSENODE, "COLLAPSENODE", false, -1, "LEFT");
this.newMethod(openPlc, OPENPLC, "OPENPLC", true, 0, "ctrl L");
this.newMethod(showCross, SHOWCROSS, "SHOWCROSS", true, 0, "ctrl R");
this.newMethod(changeValue, CHANGEVALUE, "CHANGEVALUE", true, 0, "ctrl Q");
this.newMethod(debug, DEBUG, "DEBUG", true, 0, "ctrl RIGHT");
this.newMethod(find, FIND, "FIND", false, 0, "ctrl F");
this.newMethod(swedish, LAN_SW, "LAN_SW", false, 1, null);
this.newMethod(english, LAN_EN, "LAN_EN", false, 1, null);
this.newMethod("INCLOG", INCLOG, "INCLOG", false, -1, "ctrl O");
this.newMethod("DECLOG", DECLOG, "DECLOG", false, -1, "ctrl P");
this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO",/* true,*/ 0, "ctrl A"); this.newMethod(openObject, ADDOBJECTINFO, "ADDOBJECTINFO", /*false,*/ -1, "shift RIGHT");
this.newMethod("COLLAPSENODE", COLLAPSENODE, "COLLAPSENODE",/* false,*/ -1, "LEFT");
this.newMethod(openPlc, OPENPLC, "OPENPLC", /*true,*/ 0, "ctrl L");
this.newMethod(showCross, SHOWCROSS, "SHOWCROSS", /*true,*/ 0, "ctrl R");
this.newMethod(changeValue, CHANGEVALUE, "CHANGEVALUE", /*true,*/ 0, "ctrl Q");
this.newMethod(debug, DEBUG, "DEBUG", /*true,*/ 0, "ctrl RIGHT");
this.newMethod(find, FIND, "FIND",/* false,*/ 0, "ctrl F");
this.newMethod(swedish, LAN_SW, "LAN_SW",/* false,*/ 1, null);
this.newMethod(english, LAN_EN, "LAN_EN", /*false,*/ 1, null);
this.newMethod("INCLOG", INCLOG, "INCLOG", /*false,*/ -1, "ctrl O");
this.newMethod("DECLOG", DECLOG, "DECLOG", /*false,*/ -1, "ctrl P");
this.newMethod(enterComm, COMM,"COMM",0,"ctrl C");
inputMap.setParent(this.tree.getInputMap(JComponent.WHEN_FOCUSED));
this.tree.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
......@@ -1076,7 +1118,31 @@ public class XttTree extends JPanel
if(e.isPopupTrigger())
{
System.out.println("mouse pressed isPopUpTrigger");
popup.show((Component)e.getSource(), e.getX(), e.getY());
//Mats frndringar: popup borttagen, JopMethodsMenu tillagd.
TreePath tp = tree.getSelectionPath();
if(tp == null) return;
DefaultMutableTreeNode tn = (DefaultMutableTreeNode)(tp.getLastPathComponent());
if(tn == null) return;
try
{
TreeObj obj = (TreeObj)tn.getUserObject();
String name = obj.fullName;
if(name == null)
{
return;
}
new JopMethodsMenu( session,
name,
JopUtility.TRACE,(Component) tree,
e.getX(), e.getY());
}
catch(Exception ex)
{
Logg.logg("Error in showCross() " + ex.toString(),0);
}
Logg.loggToApplet("");
//popup.show((Component)e.getSource(), e.getX(), e.getY());
}
}
}
......@@ -1090,7 +1156,31 @@ public class XttTree extends JPanel
if(e.isPopupTrigger())
{
System.out.println("isPopUpTrigger");
popup.show((Component)e.getSource(), e.getX(), e.getY());
//Mats frndringar: popup borttagen, JopMethodsMenu tillagd.
TreePath tp = tree.getSelectionPath();
if(tp == null) return;
DefaultMutableTreeNode tn = (DefaultMutableTreeNode)(tp.getLastPathComponent());
if(tn == null) return;
try
{
TreeObj obj = (TreeObj)tn.getUserObject();
String name = obj.fullName;
if(name == null)
{
return;
}
new JopMethodsMenu( session,
name,
JopUtility.TRACE,(Component) tree,
e.getX(), e.getY());
}
catch(Exception ex)
{
Logg.logg("Error in showCross() " + ex.toString(),0);
}
Logg.loggToApplet("");
// popup.show((Component)e.getSource(), e.getX(), e.getY());
}
}
});
......@@ -1258,6 +1348,7 @@ public class XttTree extends JPanel
this.openPlc = openPlc_SW;
this.find = find_SW;
this.showCross = showCross_SW;
this.enterComm = enterComm_SW;
this.currentLanguage = SWEDISH;
this.updateMenuLabels();
}
......@@ -1273,6 +1364,7 @@ public class XttTree extends JPanel
this.openPlc = openPlc_EN;
this.find = find_EN;
this.showCross = showCross_EN;
this.enterComm = enterComm_EN;
this.currentLanguage = ENGLISH;
this.updateMenuLabels();
}
......@@ -1290,16 +1382,18 @@ public class XttTree extends JPanel
menuFunctions.getItem(3).setText(changeValue);
menuFunctions.getItem(4).setText(debug);
menuFunctions.getItem(5).setText(find);
menuFunctions.getItem(6).setText(enterComm);
menuLan.setText(language);
menuLan.getItem(0).setText(swedish);
menuLan.getItem(1).setText(english);
MenuElement[] menuElements = popup.getSubElements();
//Mats frndringar: Uppdatering av popup borttagen
/*MenuElement[] menuElements = popup.getSubElements();
((JMenuItem)(menuElements[0])).setText(openObject);
((JMenuItem)(menuElements[1])).setText(openPlc);
((JMenuItem)(menuElements[2])).setText(showCross);
((JMenuItem)(menuElements[3])).setText(changeValue);
((JMenuItem)(menuElements[4])).setText(debug);
((JMenuItem)(menuElements[4])).setText(debug);*/
}
......@@ -1312,7 +1406,11 @@ public class XttTree extends JPanel
Logg.logg("JopXttApplet: changeValue()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
this.messagePanel.remove(labelMessage);
if (enterFieldEnable){
enterFieldEnable = false;
this.messagePanel.remove(userCommandLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userValueLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
......@@ -1332,7 +1430,12 @@ public class XttTree extends JPanel
Logg.logg("JopXttApplet: find()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
this.messagePanel.remove(labelMessage);
//Mats frndringar: Hantering av om enterFieldEnable =true
if (enterFieldEnable){
enterFieldEnable = false;
this.messagePanel.remove(userCommandLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userValueLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
......@@ -1341,7 +1444,30 @@ public class XttTree extends JPanel
this.userValue.requestFocus();
this.findFieldEnable = true;
}
//Mats frndringar: Ny metod enterComm fr att hantera manuellt inskrivna kommandon.
public void enterComm()
{
Logg.loggToApplet(" ");
Logg.logg("JopXttApplet: enterComm()", 6);
userValue.setText(null);
this.tree.setRequestFocusEnabled(false);
if (userValueLabel.isVisible()){
findFieldEnable = false;
this.messagePanel.remove(userValueLabel);
}
else this.messagePanel.remove(labelMessage);
this.messagePanel.add(this.userCommandLabel, BorderLayout.WEST);
this.messagePanel.add(this.userValue, BorderLayout.CENTER);
messagePanel.doLayout();
messagePanel.repaint();
this.userValue.requestFocus();
this.enterFieldEnable = true;
}
//Mats frndringar: ny metod som exekverar kommandot com.
public void enterComm(String com){
session.executeCommand(com);
}
/**
......
......@@ -5,7 +5,11 @@ local_java_sources := \
GeCFormat.java \
GeDyndata.java \
GeColor.java \
Proportion.java\
RatioLayout.java \
AspectRatioListener.java \
JopDynamic.java \
LocalDb.java \
JopEngine.java \
JopSessionIfc.java \
JopUtilityIfc.java \
......@@ -110,13 +114,25 @@ local_java_sources := \
XttTree.java \
JopXttApplet.java \
JopXttFrame.java \
EventTableModel.java \
EventTableCellRender.java \
MhTable.java \
MhClient.java \
MhFrame.java \
JopOpWindow.java \
JopOpWindowFrame.java \
JopOpWindowApplet.java \
JopSessionRep.java
JopSessionRep.java \
HistDateChooser.java \
HistSender.java \
HistStatModel1.java \
HistStatModel2.java \
HistStatistics.java \
HistTable.java \
HistStatModel1.java \
HistStatModel2.java \
HistStatistics.java \
HistSearch.java
-include $(pwre_sroot)/tools/bld/src/$(os_name)/$(hw_name)/$(type_name)_generic.mk
......@@ -134,3 +150,4 @@ endif
/**
* Title: Hist.java Description: Klass som fungerar som en port mot
* Historiska Händelselistan Copyright: <p>
*
* Company SSAB<p>
*
*
*
*@author JN
*@version 1.0
*/
package jpwr.rt;
/**
* Description of the Class
*
*@author Jonas Nylund
*@created July 5, 2004
*/
public class Hist
{
static
{
System.loadLibrary("jpwr_rt_gdh");
initHistIDs();
}
/**
*@author claes
*@created November 26, 2002
*@ingroup MSGH_DS
*@brief Defines a bit pattern.
*@param mh_mEventFlags_Return Setting this flag enables a return
* message associated with this message to be shown in the event list.
*@param mh_mEventFlags_Ack Setting this flag enables an
* acknowledgement message associated with this message to be shown in
* the event list.
*@param mh_mEventFlags_Bell
*@param mh_mEventFlags_Force
*@param mh_mEventFlags_InfoWindow
*@param mh_mEventFlags_Returned
*@param mh_mEventFlags_NoObject
*/
public static final int mh_mEventFlags_Return = 0x01;
public static final int mh_mEventFlags_Ack = 0x02;
public static final int mh_mEventFlags_Bell = 0x04;
public static final int mh_mEventFlags_Force = 0x08;
public static final int mh_mEventFlags_InfoWindow = 0x10;
public static final int mh_mEventFlags_Returned = 0x20;
public static final int mh_mEventFlags_NoObject = 0x40;
public static final int mh_mEventStatus_NotRet = (1 << 0);
public static final int mh_mEventStatus_NotAck = (1 << 1);
public static final int mh_mEventStatus_Block = (1 << 2);
/**
* @ingroup MSGH_DS
* @brief Event prio
*
* This enumeration defines the priority of the event.
* This affects how the message handler treats the generated message.
* For A and B priorities the alarm window displays number of alarms,
* number of unacknowledged alarms, identities of the alarms, and associated
* message texts. For C and D priorities, only number of alarms and number of
* unacknowledged alarms are shown.
* @param mh_eEventPrio_A Priority A, the highest priority.
* Alarm messages of this priority are shown in the upper part of the alarm window.
* @param mh_eEventPrio_B Priority B.
* These messages are shown in the lower part of the alarm window.
* @param mh_eEventPrio_C Priority C.
* @param mh_eEventPrio_D Priority D. This is the lowest priority.
*/
public static final int mh_eEventPrio__ = 0;
public static final int mh_eEventPrio_A = 67;
public static final int mh_eEventPrio_B = 66;
public static final int mh_eEventPrio_C = 65;
public static final int mh_eEventPrio_D = 64;
public static final int mh_eEventPrio_ = 63;
public static final int mh_eEvent__ = 0;
public static final int mh_eEvent_Ack = 1;
public static final int mh_eEvent_Block = 2;
public static final int mh_eEvent_Cancel = 3;
public static final int mh_eEvent_CancelBlock = 4;
public static final int mh_eEvent_Missing = 5;
public static final int mh_eEvent_Reblock = 6;
public static final int mh_eEvent_Return = 7;
public static final int mh_eEvent_Unblock = 8;
public static final int mh_eEvent_Info = 32;
public static final int mh_eEvent_Alarm = 64;
public static final int mh_eEvent_ = 65;
public static final int EventType_ClearAlarmList = 66;
private static boolean initDone = false;
/**
* Constructor for the Hist object
*
*@param root Description of the Parameter
*/
public Hist()
{
if(!initDone)
{
initDone = true;
}
}
private native static void initHistIDs();
/**
* Description of the Method
*
*@param query The query to the HistDB
*@return Vector A Vector containing matching events
*/
public native static MhrEvent[] getHistList(String startTime,
String stopTime,
boolean typeAlarm,
boolean typeInfo,
boolean typeReturn,
boolean typeAck,
boolean prioA,
boolean prioB,
boolean prioC,
boolean prioD,
String name,
String text);
}
package jpwr.rt;
import java.io.Serializable;
/*The HistQuery class represents the search criteria needed to perform a Search
*in the eventlist. It is used as the argument for performing SearchRequest from
*a SearchSender */
public class HistQuery implements Serializable{
public String startTime;
public String stopTime;
public boolean[] type;
public boolean[] priority;
public String name;
public String text;
public HistQuery(String start, String stop, boolean[] ty, boolean[] p, String n,String tx)
{
this.startTime=start;
this.stopTime=stop;
this.type=ty;
this.priority=p;
this.name=n;
this.text=tx;
}
}
package jpwr.rt;
import java.net.*;
import java.io.*;
import java.util.*;
//for test
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.*;
//end for test
/**
* Description of the Class
*
*@author claes, Jonas
*@created November 25, 2002
*@version 0.1 beta: Frsta testversionen
*/
public class HistServer
{
public final static int HISTPORT = 4447;
public final static int __IO_EXCEPTION = 2000;
static boolean ignoreHandler = false;
static boolean log = false;
static boolean logStatistics = false;
static boolean test = false;
boolean keepRunning = true;
/**
* The main program for the HistServer class
*
*@param args The command line arguments
*/
public static void main(String[] args)
{
for(int i = 0; i < args.length; i++)
{
if(args[i].equals("-i"))
{
ignoreHandler = true;
}
else if(args[i].equals("-l"))
{
log = true;
}
else if(args[i].equals("-s"))
{
logStatistics = true;
}
else if(args[i].equals("-t"))
{
test = true;
}
}
if(log)
{
System.out.println("HistServer starting");
}
Hist hist = new Hist();
HistServer hs = new HistServer();
hs.run(hist);
System.out.println("HistServer exiting");
System.exit(0);
}
public void run(Hist hist)
{
boolean keepRunning = true;
ServerSocket serverSocket = null;
if(test)
{
boolean[] type = new boolean[4];
type[0] = type[1] = type[2] = type[3] = false;
type[0] = true;
boolean[] prio = new boolean[4];
prio[0] = prio[1] = prio[2] = prio[3] = false;
HistQuery query = new HistQuery("2003-11-05 09:26:49", "2004-11-05 09:26:49", type, prio, "*", "*");
MhrEvent[] ev = hist.getHistList(query.startTime,
query.stopTime,
query.type[0],
query.type[1],
query.type[2],
query.type[3],
query.priority[0],
query.priority[1],
query.priority[2],
query.priority[3],
query.name,
query.text);
int i = 0;
System.out.println("No events: "+ ev.length);
while(i < ev.length)
{
System.out.println(ev[i].toString());
i++;
}
return;
}
try
{
serverSocket = new ServerSocket(HISTPORT);
serverSocket.setSoTimeout(1000);
}
catch(IOException e)
{
System.out.println("IOException in openServerSocket");
//errh.fatal("Could not listen on port " + HISTPORT);
System.exit(1);
}
// gdh = new Gdh((Object)null);
// errh = new Errh("MhServer", Errh.eAnix_webmonmh);
// errh.setStatus( Errh.PWR__SRVSTARTUP);
if(log)
{
System.out.println("JHist: Before waiting for client");
}
// mh = new Mh((Object)null, maxAlarms, maxEvents);
// errh.setStatus( Errh.PWR__SRUN);
// Qcom qcom = new Qcom();
// QcomrCreateQ qque = qcom.createIniEventQ("MhServer");
// if(qque.evenSts())
// {
// System.out.println("MH:Error during qreateque");
// errh.fatal("MH:Error during qcom.createIniEventQ");
// return;
// }
// QcomrGetIniEvent qrGetIniEv;
while(keepRunning)
{
Socket cliSocket = null;
try
{
if(log)
{
//System.out.println(" Wait for accept ");
}
cliSocket = serverSocket.accept();
}
catch(InterruptedIOException e)
{
continue;
/*
qrGetIniEv = qcom.getIniEvent(qque.qix, qque.nid, 0);
if(qrGetIniEv.timeout)
{
//do nothing
continue;
}
else if(qrGetIniEv.terminate)
{
//Time to die
System.out.println("MhServer received killmess from QCom");
return;
}
else
{
//All other messages is qurrently ignored
//But perhaps we should reinitialize when we get
//swapdone
continue;
}
*/
}
catch(IOException e)
{
//errh.error("Accept failed.");
this.keepRunning = false;
continue;
}
if(log)
{
System.out.println("New client for HistServer");
}
new HistThread(hist, cliSocket);
}
}
private class HistThread extends Thread
{
Hist hist;
Socket socket;
public HistThread(Hist hist, Socket socket)
{
this.hist = hist;
this.socket = socket;
start();
}
public void run()
{
this.handleClient(this.socket);
}
public void handleClient(Socket socket)
{
ObjectInputStream in = null;
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
//wait for the question
HistQuery query = (HistQuery)in.readObject();
if(log)
{
System.out.println("Recieved a query");
System.out.println("query: Prio(ABCD): " + query.priority[0] + query.priority[1] + query.priority[2] + query.priority[3]);
System.out.println(" type(Akt Mess Ret Kvitt): " + query.type[0] + query.type[1] + query.type[2] + query.type[3]);
System.out.println(" startTime: " + query.startTime);
System.out.println(" stopTime: " + query.stopTime);
System.out.println(" name: " + query.name);
System.out.println(" text: " + query.text);
}
//send the answer
out.writeObject(hist.getHistList(query.startTime,
query.stopTime,
query.type[0],
query.type[1],
query.type[2],
query.type[3],
query.priority[0],
query.priority[1],
query.priority[2],
query.priority[3],
query.name,
query.text));
}
catch(IOException e)
{
System.out.println("Exception in hist.handleQuery:" + e.toString());
//errh.error("hist.handleCLient: DataStream failed");
}
catch(Exception e)
{
System.out.println("Exception in hist.handleQuery:" + e.toString());
//errh.error("hist.handleCLient: Exception");
}
finally
{
//System.out.println("finally");
try
{
out.close();
}
catch(Exception e)
{
}
try
{
in.close();
}
catch(Exception e)
{
System.out.println("Closing client socket");
}
try
{
socket.close();
}
catch(Exception e)
{
}
}//finally
}//handleClient
}//HistThread
}//HistServer
......@@ -62,6 +62,10 @@ public class MhrEvent implements Serializable
eventType,
object);
}
public String toString()
{
return new String(eventTime + eventText + eventName + eventFlags + eventPrio + eventType);
}
}
......@@ -5,6 +5,7 @@ local_java_sources = \
PwrtObjid.java \
PwrtRefId.java \
Pwr.java \
Pwrs.java \
Pwrb.java \
CdhrBoolean.java \
CdhrClassId.java \
......@@ -30,11 +31,14 @@ local_java_sources = \
SubElement.java \
GdhServer.java \
GdhServerMonitor.java \
HistQuery.java \
MhrsEventId.java \
MhrEvent.java \
Mh.java \
MhData.java \
MhServer.java
MhServer.java \
Hist.java \
HistServer.java
-include $(pwre_sroot)/tools/bld/src/$(os_name)/$(hw_name)/$(type_name)_generic.mk
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment