summaryrefslogtreecommitdiff
path: root/src/main/java/org/cristalise/gui/tabs/execution/ActivityViewer.java
blob: 2193916d48ec77bf88dcec82bb4884d36e13337b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package org.cristalise.gui.tabs.execution;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.cristalise.gui.MainFrame;
import org.cristalise.gui.tabs.ExecutionPane;
import org.cristalise.gui.tabs.ItemTabPane;
import org.cristalise.gui.tabs.outcome.InvalidOutcomeException;
import org.cristalise.gui.tabs.outcome.InvalidSchemaException;
import org.cristalise.gui.tabs.outcome.OutcomeHandler;
import org.cristalise.kernel.common.InvalidDataException;
import org.cristalise.kernel.common.ObjectNotFoundException;
import org.cristalise.kernel.entity.agent.Job;
import org.cristalise.kernel.entity.proxy.ItemProxy;
import org.cristalise.kernel.utils.FileStringUtility;
import org.cristalise.kernel.utils.Language;
import org.cristalise.kernel.utils.LocalObjectLoader;
import org.cristalise.kernel.utils.Logger;


public class ActivityViewer extends JPanel implements Runnable {

    ItemProxy item;
    Box outcomeButtons = Box.createHorizontalBox();
    OutcomeHandler outcomePanel;
    OutcomeHandler errorPanel;
    JPanel outcomeView = new JPanel(new GridLayout(1,1));
    JPanel errorView = new JPanel(new GridLayout(2,1));
    ActivityItem thisAct;
    ArrayList<RequestButton> requestButtons = new ArrayList<RequestButton>();
    JLabel noOutcome = new JLabel(Language.translate("No outcome data is required for this activity"));
    ExecutionPane parent;
    JLabel status;
    JComboBox executors;
    JButton saveButton  = new JButton("Save");
    JButton loadButton  = new JButton("Load");
    GridBagLayout gridbag = new GridBagLayout();
    Job executingJob = null;
    static JFileChooser chooser = new JFileChooser();
    static {
        chooser.addChoosableFileFilter(
            new javax.swing.filechooser.FileFilter() {
                @Override
				public String getDescription() {
                    return "XML Files";
                }
                @Override
				public boolean accept(File f) {
                    if (f.isDirectory() || (f.isFile() && f.getName().endsWith(".xml"))) {
                        return true;
                    }
                    return false;
                }
            });
    }

    public ActivityViewer (ActivityItem newAct, ItemProxy item, ExecutionPane parent){
        thisAct = newAct;
        this.item = item;
        this.parent = parent;
        setLayout(gridbag);

        GridBagConstraints c = new GridBagConstraints();
        c.gridx=0; c.gridy=1; c.weightx=1.0; c.weighty=0.0;
        c.insets = new Insets(5,5,5,5);
        c.anchor = GridBagConstraints.NORTHWEST;
        c.fill = GridBagConstraints.HORIZONTAL;

// activity title
        JLabel actTitle = new JLabel(Language.translate("Activity")+": "+newAct.name);
        actTitle.setFont(ItemTabPane.titleFont);
        gridbag.setConstraints(actTitle, c);
        add(actTitle);

        Job firstJob = (thisAct.getJobs().get(0));
// desc
        String desc = firstJob.getDescription();
        if (desc != null && desc.length() > 0) {
            Box descBox = Box.createHorizontalBox();

            String chopDesc = null;
            if(desc.length() >= 40) chopDesc = desc.substring(0,40);
            else chopDesc = desc;

            descBox.add(new JLabel("Description: "+chopDesc));
            if (desc.length()>chopDesc.length()) {
                descBox.add(new JLabel(" ..."));
                descBox.add(Box.createHorizontalStrut(7));
                JButton descButton = new JButton("View");
                descButton.setMargin(new Insets(0,0,0,0));
                descButton.setActionCommand(desc);
                descButton.addActionListener(new ActionListener() {
                    @Override
					public void actionPerformed(ActionEvent e) {
                        JTextArea descArea = new JTextArea(e.getActionCommand());
                        descArea.setLineWrap(true);
                        descArea.setWrapStyleWord(true);
                        JScrollPane descScroll = new JScrollPane(descArea);
                        descScroll.setPreferredSize(new Dimension(400,150));
                        JOptionPane.showMessageDialog(null, descScroll, "Activity Description", JOptionPane.PLAIN_MESSAGE);
                    }
                });
                descBox.add(descButton);
            }

            c.gridy++;
            gridbag.setConstraints(descBox, c);
            add(descBox);
        }


// agentid
        String roleName = firstJob.getAgentRole();
        if (roleName!= null && roleName.length()>0) {
            c.gridy++;
            JLabel role = new JLabel(Language.translate("Agent Role")+": "+roleName);
            gridbag.setConstraints(role, c);
            add(role);
        }

        c.gridy++;
        c.anchor = GridBagConstraints.EAST;
        gridbag.setConstraints(outcomeButtons, c);
        add(outcomeButtons);

        executors = MainFrame.getExecutionPlugins();
        if (executors.getItemCount() > 1) {
            c.gridx++;
            gridbag.setConstraints(executors, c);
            add(executors);
            c.gridx--;
        }

        c.gridy++;

        status = new JLabel(Language.translate("Waiting for request"));
        status.setFont(ItemTabPane.titleFont);
        gridbag.setConstraints(status, c);
        add(status);

        c.gridx++;
        Box fileBox = Box.createHorizontalBox();
        fileBox.add(saveButton); fileBox.add(Box.createHorizontalGlue()); fileBox.add(loadButton);
        gridbag.setConstraints(fileBox, c);
        add(fileBox);
        saveButton.setEnabled(false);
        loadButton.setEnabled(false);
        c.gridx--;
        c.gridwidth = 2;
        for (Object name2 : thisAct.getJobs()) {
            Job thisJob = (Job)name2;
            RequestButton newButton = new RequestButton(thisJob, this);
            requestButtons.add(newButton);
            outcomeButtons.add(newButton);
            outcomeButtons.add(Box.createHorizontalStrut(5));
            newButton.setEnabled(false);
            
            if (thisJob.hasOutcome()) {

        		String schemaName;
				int schemaVersion;
				try {
					schemaName = thisJob.getSchemaName();
					schemaVersion = thisJob.getSchemaVersion();
				} catch (Exception e) {
					newButton.setToolTipText("Could not load schema for this job.");
					continue;
				} 
    
            	if(!schemaName.equals("Errors") && outcomePanel == null) {
            		try {
            			outcomePanel = getOutcomeHandler(thisJob);
						outcomeView = outcomePanel.getPanel();
						newButton.setEnabled(true);
					} catch (ObjectNotFoundException ex) {
						outcomeView.add(new JLabel(Language.translate("Schema not found:")+" "+schemaName+" v"+schemaVersion));
	              	} catch (Exception ex) {
	                    outcomeView.add(new JLabel(Language.translate("ERROR loading outcome editor: ")
	                        +ex.getClass().getName()+" ("+ex.getMessage()+")"));
	                    Logger.error(ex);
	            	}
            	}
            	if (schemaName.equals("Errors")) {
            		try {
            			errorPanel = getOutcomeHandler(thisJob);
            			errorView.add(errorPanel.getPanel());
            			newButton.setEnabled(true);
					} catch (Exception ex) {
						errorView.add(new JLabel(Language.translate("ERROR loading error editor: ")
		                        +ex.getClass().getName()+" ("+ex.getMessage()+")"));
	
					}
            	}
            }
            else
            	newButton.setEnabled(true);
        }
        if (outcomePanel == null)
            outcomeView.add(noOutcome);
        else
        	enableLoadSaveButtons();


        c.gridy++; c.weighty=1.0;
        c.anchor = GridBagConstraints.NORTHWEST;
        c.fill = GridBagConstraints.BOTH;
        gridbag.setConstraints(outcomeView, c);
        add(outcomeView);

    }

    public OutcomeHandler getOutcomeHandler(Job thisJob) throws ObjectNotFoundException, InvalidSchemaException, InvalidOutcomeException, InvalidDataException {
        String schema;
        OutcomeHandler thisForm;
    	schema = LocalObjectLoader.getSchema(thisJob.getSchemaName(), thisJob.getSchemaVersion()).schema;
        thisForm = ItemTabPane.getOutcomeHandler(thisJob.getSchemaName(), thisJob.getSchemaVersion());
        thisForm.setReadOnly(false);
        thisForm.setDescription(schema);
        String outcomeString = thisJob.getOutcomeString();
        if ( outcomeString!= null && outcomeString.length() > 0)
        	thisForm.setOutcome(outcomeString);
        return thisForm;
    }
    
    public void enableLoadSaveButtons() {
    	saveButton.addActionListener(new ActionListener() {
    		@Override
			public void actionPerformed(ActionEvent e) {
    			String output;
    			try {
                    output = outcomePanel.getOutcome();
                    int returnVal = chooser.showSaveDialog(null);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File targetFile = chooser.getSelectedFile();
                        if (!(targetFile.getAbsolutePath().endsWith(".xml")))
                            targetFile = new File(targetFile.getAbsolutePath()+".xml");

                        Logger.msg(2, "ExecutionPane - Exporting outcome to file " + targetFile.getName());
                        FileStringUtility.string2File(targetFile, output);
                    }
    			} catch (Exception ex) {
                     Logger.error(ex);
                     MainFrame.exceptionDialog(ex);
                    }
    		}
    	});
    	saveButton.setEnabled(true);

    	loadButton.addActionListener(new ActionListener() {
    		@Override
			public void actionPerformed(ActionEvent e) {
    			try {
                    int returnVal = chooser.showOpenDialog(null);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File targetFile = chooser.getSelectedFile();

                        Logger.msg(2, "ViewpointPane.actionPerformed() - Reading outcome from file " + targetFile.getName());
                        String outcome = FileStringUtility.file2String(targetFile);
                        outcomePanel.setOutcome(outcome);
                        new Thread(outcomePanel).start();
                    }
    			} catch (Exception ex) {
                     Logger.error(ex);
                     MainFrame.exceptionDialog(ex);
                    }
    		}
    	});
    	loadButton.setEnabled(true);
    }
    
    public void init() {
        if (outcomePanel != null)
            new Thread(outcomePanel).start();
        if (errorPanel != null)
        	new Thread(errorPanel).start();
    }

    public void execute(Job thisJob) {
        try {
            if (thisJob.hasOutcome())
            	if (!thisJob.getSchemaName().equals("Errors"))
            		thisJob.setOutcome(outcomePanel.getOutcome());
            	else {
	            	Box errorBox = Box.createVerticalBox();
	            	errorBox.add(new JLabel("Please give details of the error:"));
	            	errorBox.add(errorView);
	            	int result = JOptionPane.showConfirmDialog(this, errorBox, "Send Error", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);
	            	if (result != JOptionPane.OK_OPTION)
	            		return;
	            	thisJob.setOutcome(errorPanel.getOutcome());
            	}
            executingJob = thisJob;
            new Thread(this).start();
        } catch (Exception ex) {
        	MainFrame.exceptionDialog(ex);
        }

    }

    /**
     *  Submits the job to the database
     */
    @Override
	public void run() {
        Thread.currentThread().setName("Activity Execution");
        enableAllButtons(false);
        try {
            Executor selectedExecutor = (Executor)executors.getSelectedItem();
            selectedExecutor.execute(executingJob, status);
        } catch (Exception e) {
            Logger.error(e);
            MainFrame.progress.stopBouncing(Language.translate("Error during execution"));
            status.setText(Language.translate("Error during execution: "+e.getClass().getSimpleName()));
            MainFrame.exceptionDialog(e);
        }
        enableAllButtons(true);
    }

    private void enableAllButtons(boolean enabled) {

        for (RequestButton thisButton : requestButtons) {
            thisButton.setEnabled(enabled);
        }
    }

    public ActivityItem getActivity() {
        return thisAct;
    }
}