001/*
002 * Copyright (c) 2003-2010 The Regents of the University of California.
003 * All rights reserved.
004 *
005 * '$Author: crawl $'
006 * '$Date: 2012-09-20 22:41:24 +0000 (Thu, 20 Sep 2012) $' 
007 * '$Revision: 30724 $'
008 * 
009 * Permission is hereby granted, without written agreement and without
010 * license or royalty fees, to use, copy, modify, and distribute this
011 * software and its documentation for any purpose, provided that the above
012 * copyright notice and the following two paragraphs appear in all copies
013 * of this software.
014 *
015 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
016 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
017 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
018 * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
019 * SUCH DAMAGE.
020 *
021 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
022 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
023 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
024 * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
025 * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
026 * ENHANCEMENTS, OR MODIFICATIONS.
027 *
028 */
029
030package org.geon;
031
032import java.io.File;
033import java.net.URL;
034import java.util.Iterator;
035import java.util.Map;
036import java.util.TreeMap;
037import java.util.Vector;
038
039import org.kepler.gui.KeplerInitializer;
040import org.w3c.dom.Element;
041import org.w3c.dom.Node;
042import org.w3c.dom.NodeList;
043
044import ptolemy.actor.CompositeActor;
045import ptolemy.actor.Manager;
046import ptolemy.data.ArrayToken;
047import ptolemy.data.BooleanMatrixToken;
048import ptolemy.data.DoubleMatrixToken;
049import ptolemy.data.DoubleToken;
050import ptolemy.data.IntMatrixToken;
051import ptolemy.data.IntToken;
052import ptolemy.data.LongMatrixToken;
053import ptolemy.data.LongToken;
054import ptolemy.data.RecordToken;
055import ptolemy.data.StringToken;
056import ptolemy.data.Token;
057import ptolemy.data.UnsignedByteToken;
058import ptolemy.data.expr.Variable;
059import ptolemy.data.type.BaseType;
060import ptolemy.kernel.util.Attribute;
061import ptolemy.kernel.util.IllegalActionException;
062import ptolemy.kernel.util.NamedObj;
063import ptolemy.moml.MoMLParser;
064
065//////////////////////////////////////////////////////////////////////////
066////PTModelService
067/**
068 * Invoke a model when the service method is called.
069 * 
070 * @author Efrat Jaeger, Yang Zhao
071 * @deprecated This class is mostly duplicated by org.geon.LidarWorkflowExecute.
072 * Use org.geon.LidarWorkflowExecute instead since it provides more functionality.
073 */
074public class WorkflowExecute {
075        public WorkflowExecute() {
076                // Initialize the cache manager, if it is not present.
077                try {
078                        KeplerInitializer.initializeSystem();
079                } catch (Exception ex) {
080                        ex.printStackTrace();
081                }
082        }
083
084        /**
085         * This method takes a url specifying the model to be execute. The
086         * <i>args<i> argument is a record token that will be used to set
087         * corresponding attributes of the spedified model by naming match, (see
088         * _setAttribute() method). The results of executing the model is returned
089         * back by setting the value of some Attributes. In particular, only
090         * Attributes that have name matches the <i>resultLabels<i> are returned.
091         * The return result is a RecordToken which has the resultLabels as its
092         * feild.
093         * 
094         * @param url
095         *            The Model url.
096         * @param args
097         *            A set of attributes of the specified model.
098         * @param resultLabels
099         *            Labels of the returned result.
100         * @return The execution result.
101         * @exception IllegalActionException
102         *                If can not parse the url or failed to execute the model.
103         */
104
105        public synchronized String execute(String modelURL, Map inputs)
106                        throws Exception {
107                System.out.println(System.getProperty("user.dir"));
108                URL url = new URL(modelURL);
109                if (url != null) {
110                        MoMLParser parser = new MoMLParser();
111                        NamedObj model;
112                        try {
113                                System.out.println("before parsing");
114                                model = parser.parse(null, url);
115                                System.out.println("after parsing");
116                                boolean in = setInputs(model, inputs);
117                                if (!in)
118                                        return null;
119
120                        } catch (Exception ex) {
121                                ex.printStackTrace();
122                                return null;
123                        }
124                        if (model instanceof CompositeActor) {
125                                System.out.println("after parsing model");
126                                return executeModel((CompositeActor) model);
127                        } else {
128                                return null;
129                        }
130                } else {
131                        return null;
132                }
133        }
134
135        /**
136         * This method takes model argument which is type of CompositeActor. The
137         * <i>args<i> argument is a record token that will be used to set
138         * corresponding attributes of the spedified model by naming match, (see
139         * _setAttribute() method). The results of executing the model is returned
140         * back by setting the value of some Attributes. In particular, only
141         * Attributes that have name matches the <i>resultLabels<i> are returned.
142         * The return result is a RecordToken which has the resultLabels as its
143         * feild.
144         * 
145         * @param model
146         *            The Model.
147         * @param args
148         *            A set of attributes of the specified model.
149         * @param resultLabels
150         *            Labels of the returned result.
151         * @return The execution result.
152         * @exception IllegalActionException
153         *                If failed to execute the model.
154         */
155        public String executeModel(CompositeActor model) throws Exception {
156                Manager manager = model.getManager();
157                if (manager == null) {
158                        // System.out.println("create manager for the model");
159                        manager = new Manager(model.workspace(), "Manager");
160                        model.setManager(manager);
161                }
162                // _setAttribute(model, args);
163
164                manager.execute();
165
166                return _getResult(model);
167        }
168
169        // /////////////////////////////////////////////////////////////////
170        // // private methods ////
171
172        /**
173         * Get the output from the parameter (assuming that there is a single output
174         * variable name <i>output</i>
175         * 
176         * @param model
177         *            The model executed.
178         * @param resultLabels
179         *            Labels of the returned result.
180         * @return The execution result.
181         * @exception IllegalActionException
182         *                If reading the ports or setting the parameters causes it.
183         */
184        private String _getResult(CompositeActor model)
185                        throws IllegalActionException {
186
187                String val = "";
188                Iterator atts = model.attributeList().iterator();
189                while (atts.hasNext()) {
190                        Attribute att = (Attribute) atts.next();
191                        if (att instanceof Variable) {
192                                String attName = att.getName();
193                                if (attName.trim().toLowerCase().equals("output")) {
194                                        Variable var = (Variable) att;
195                                        System.out.println(var.getType().toString());
196                                        if (var.getType().equals(BaseType.UNKNOWN)) {
197                                                var.setTypeEquals(BaseType.GENERAL);
198                                        }
199
200                                        val = processToken(var.getToken());
201                                        System.out.println("after process token");
202                                        break;
203                                }
204                        }
205                }
206                return val;
207        }
208
209        private boolean setInputs(NamedObj model, Map inputs) {
210                Iterator atts = model.attributeList().iterator();
211                while (atts.hasNext()) {
212                        Attribute att = (Attribute) atts.next();
213                        if (att instanceof Variable) {
214                                String attName = att.getName();
215                                if (inputs.containsKey(attName)) {
216                                        try {
217                                                Variable var = (Variable) att;
218                                                var.setToken((String) inputs.get(attName));
219                                                System.out.println(attName + ":" + var.getExpression());
220                                        } catch (Exception ex) {
221                                                ex.printStackTrace();
222                                                return false;
223                                        }
224                                }
225
226                        }
227                }
228                return true;
229        }
230
231        /*
232         * private ComponentEntity getEntity(ComponentEntity CE, String inputName) {
233         * int ind = inputName.indexOf("."); while (ind != -1) { String aName =
234         * inputName.substring(0,ind); inputName = inputName.substring(ind+1); ind =
235         * inputName.indexOf("."); CE = ((CompositeActor)CE).getEntity(aName); } CE
236         * = ((CompositeActor)CE).getEntity(inputName); return CE; }
237         */
238        private Token process(Element tag) throws IllegalActionException { // elem =
239                                                                                                                                                // channel..
240                String tagName = tag.getTagName();
241
242                if (tagName.equals("unsignedbyte")) {
243                        String val = tag.getFirstChild().getNodeValue().trim();
244                        UnsignedByteToken t = new UnsignedByteToken(val);
245                        return t;
246                }
247
248                if (tagName.equals("int")) {
249                        String val = tag.getFirstChild().getNodeValue().trim();
250                        IntToken t = new IntToken(val);
251                        return t;
252                }
253
254                if (tagName.equals("double")) {
255                        String val = tag.getFirstChild().getNodeValue().trim();
256                        DoubleToken t = new DoubleToken(val);
257                        return t;
258                }
259
260                if (tagName.equals("long")) {
261                        String val = tag.getFirstChild().getNodeValue().trim();
262                        LongToken t = new LongToken(val);
263                        return t;
264                }
265
266                if (tagName.equals("intmatrix")) {
267                        NodeList rows = tag.getElementsByTagName("row");
268                        int rowNum = rows.getLength();
269                        if (rowNum > 0) {
270                                NodeList tempCols = ((Element) rows.item(0))
271                                                .getElementsByTagName("value");
272                                int colNum = tempCols.getLength();
273                                int[][] Mat = new int[rowNum][colNum];
274                                for (int j = 0; j < rowNum; j++) {
275                                        NodeList Cols = ((Element) rows.item(j))
276                                                        .getElementsByTagName("value");
277                                        for (int k = 0; k < colNum; k++) {
278                                                String val = Cols.item(k).getFirstChild()
279                                                                .getNodeValue().trim();
280                                                Mat[j][k] = Integer.parseInt(val);
281                                        }
282                                }
283                                IntMatrixToken t = new IntMatrixToken(Mat);
284                                return t;
285                        } else
286                                return new IntMatrixToken();
287                }
288
289                if (tagName.equals("doublematrix")) {
290                        NodeList rows = tag.getElementsByTagName("row");
291                        int rowNum = rows.getLength();
292                        if (rowNum > 0) {
293                                NodeList tempCols = ((Element) rows.item(0))
294                                                .getElementsByTagName("value");
295                                int colNum = tempCols.getLength();
296                                double[][] Mat = new double[rowNum][colNum];
297                                for (int j = 0; j < rowNum; j++) {
298                                        NodeList Cols = ((Element) rows.item(j))
299                                                        .getElementsByTagName("value");
300                                        for (int k = 0; k < colNum; k++) {
301                                                String val = Cols.item(k).getFirstChild()
302                                                                .getNodeValue().trim();
303                                                Mat[j][k] = Double.parseDouble(val);
304                                        }
305                                }
306                                DoubleMatrixToken t = new DoubleMatrixToken(Mat);
307                                return t;
308                        } else
309                                return new DoubleMatrixToken();
310                }
311
312                if (tagName.equals("longmatrix")) {
313                        NodeList rows = tag.getElementsByTagName("row");
314                        int rowNum = rows.getLength();
315                        if (rowNum > 0) {
316                                NodeList tempCols = ((Element) rows.item(0))
317                                                .getElementsByTagName("value");
318                                int colNum = tempCols.getLength();
319                                long[][] Mat = new long[rowNum][colNum];
320                                for (int j = 0; j < rowNum; j++) {
321                                        NodeList Cols = ((Element) rows.item(j))
322                                                        .getElementsByTagName("value");
323                                        for (int k = 0; k < colNum; k++) {
324                                                String val = Cols.item(k).getFirstChild()
325                                                                .getNodeValue().trim();
326                                                Mat[j][k] = Long.parseLong(val);
327                                        }
328                                }
329                                LongMatrixToken t = new LongMatrixToken(Mat);
330                                return t;
331                        } else
332                                return new LongMatrixToken();
333                }
334
335                if (tagName.equals("booleanmatrix")) {
336                        NodeList rows = tag.getElementsByTagName("row");
337                        int rowNum = rows.getLength();
338                        if (rowNum > 0) {
339                                NodeList tempCols = ((Element) rows.item(0))
340                                                .getElementsByTagName("value");
341                                int colNum = tempCols.getLength();
342                                boolean[][] Mat = new boolean[rowNum][colNum];
343                                for (int j = 0; j < rowNum; j++) {
344                                        NodeList Cols = ((Element) rows.item(j))
345                                                        .getElementsByTagName("value");
346                                        for (int k = 0; k < colNum; k++) {
347                                                String val = Cols.item(k).getFirstChild()
348                                                                .getNodeValue().trim();
349                                                Mat[j][k] = Boolean.getBoolean(val);
350                                        }
351                                }
352                                BooleanMatrixToken t = new BooleanMatrixToken(Mat);
353                                return t;
354                        } else
355                                return new BooleanMatrixToken();
356                }
357
358                if (tagName.equals("string")) {
359                        String val = tag.getFirstChild().getNodeValue().trim();
360                        StringToken t = new StringToken(val);
361                        return t;
362                }
363
364                if (tagName.equals("array")) {
365                        Vector tVec = new Vector();
366                        NodeList arrChilds = tag.getChildNodes();
367
368                        // find only the element children
369                        for (int j = 0; j < arrChilds.getLength(); j++) {
370                                if (arrChilds.item(j) instanceof Element) {
371
372                                        Token token = process((Element) arrChilds.item(j));
373                                        tVec.add(token);
374                                }
375                        }
376                        Token tArr[] = new Token[tVec.size()];
377                        tVec.toArray(tArr);
378                        ArrayToken t = new ArrayToken(tArr);
379                        return t;
380                }
381
382                if (tagName.equals("record")) {
383                        NodeList labelNodes = tag.getElementsByTagName("label");
384                        NodeList valueNodes = tag.getElementsByTagName("value");
385                        int recLen = labelNodes.getLength();
386                        String[] labels = new String[recLen];
387                        Token[] tokens = new Token[recLen];
388                        for (int j = 0; j < recLen; j++) {
389                                labels[j] = labelNodes.item(j).getFirstChild().getNodeValue()
390                                                .trim();
391                        }
392                        int k = 0;
393                        for (int j = 0; j < valueNodes.getLength(); j++) {
394                                Element value = (Element) valueNodes.item(j);
395                                NodeList childs = value.getChildNodes();
396                                for (int l = 0; l < childs.getLength(); l++) {
397                                        Node node = childs.item(l);
398                                        if (node instanceof Element) {
399                                                tokens[k++] = process((Element) node);
400                                        }
401                                }
402                        }
403                        RecordToken t = new RecordToken(labels, tokens);
404                        return t;
405                }
406
407                Token t = new Token();
408                return t;
409        }
410
411        private String processToken(Token token) {
412
413                String val = "";
414                if (token instanceof UnsignedByteToken) {
415                        val = ((UnsignedByteToken) token).unitsString();
416                        return val;
417
418                } else if (token instanceof IntToken) {
419                        val = ((IntToken) token).toString();
420                        return val;
421
422                } else if (token instanceof DoubleToken) {
423                        val = ((DoubleToken) token).toString();
424                        return val;
425
426                } else if (token instanceof LongToken) {
427                        val = ((LongToken) token).toString();
428                        return val;
429
430                } else if (token instanceof IntMatrixToken) {
431                        val = "[";
432                        int[][] Mat = ((IntMatrixToken) token).intMatrix();
433                        for (int i = 0; i < Mat.length; i++) {
434                                for (int j = 0; j < Mat[0].length; j++) {
435                                        val += Mat[i][j] + ",";
436                                }
437                                val += ":";
438                        }
439                        val += "]";
440                        return val;
441
442                } else if (token instanceof DoubleMatrixToken) {
443                        val = "[";
444                        double[][] Mat = ((DoubleMatrixToken) token).doubleMatrix();
445                        for (int i = 0; i < Mat.length; i++) {
446                                for (int j = 0; j < Mat[0].length; j++) {
447                                        val += Mat[i][j] + ",";
448                                }
449                                val += ":";
450                        }
451                        val += "]";
452                        return val;
453
454                } else if (token instanceof LongMatrixToken) {
455                        val = "[";
456                        long[][] Mat = ((LongMatrixToken) token).longMatrix();
457                        for (int i = 0; i < Mat.length; i++) {
458                                for (int j = 0; j < Mat[0].length; j++) {
459                                        val += Mat[i][j] + ",";
460                                }
461                                val += ":";
462                        }
463                        val += "]";
464                        return val;
465
466                } else if (token instanceof BooleanMatrixToken) {
467                        val = "[";
468                        boolean Mat[][] = ((BooleanMatrixToken) token).booleanMatrix();
469                        for (int i = 0; i < Mat.length; i++) {
470                                for (int j = 0; j < Mat[0].length; j++) {
471                                        val += Mat[i][j] + ",";
472                                }
473                                val += ":";
474                        }
475                        val += "]";
476                        return val;
477
478                } else if (token instanceof StringToken) {
479                        val = ((StringToken) token).stringValue();
480                        return val;
481
482                } else if (token instanceof ArrayToken) {
483                        val = "{";
484                        ArrayToken at = (ArrayToken) token;
485                        Token[] tArr = at.arrayValue();
486                        for (int i = 0; i < tArr.length; i++) {
487                                val += processToken(tArr[i]) + ",";
488                        }
489                        val += "}";
490                        return val;
491
492                } else if (token instanceof RecordToken) {
493                        val = "{";
494                        RecordToken rt = (RecordToken) token;
495                        Object[] labelObjects = rt.labelSet().toArray();
496                        for (int i = 0; i < labelObjects.length; i++) {
497                                String label = (String) labelObjects[i];
498                                val += label + "=";
499                                Token value = rt.get(label);
500                                val += processToken(value);
501                                val += ",";
502                        }
503                        val += "}";
504                        return val;
505                }
506                return val;
507        }
508
509        private String xml = "";
510
511        static public void main(String args[]) throws Exception {
512                System.out.println("init");
513                String inputWF = "file:///C:/Util/jakarta-tomcat-4.1.30/webapps/examples/data/Atype/Original/testAtts.xml";
514                File momlFile = new File(inputWF);
515                System.out.println("BEFORE!!");
516                WorkflowExecute we = new WorkflowExecute();
517
518                Map inputs = new TreeMap();
519                inputs.put("classificationType", "A-type");
520                inputs.put("area", "VA");
521                inputs.put("bodiesType", "Plutonic");
522                inputs.put("diagramsInfo", "diagrams.txt");
523
524                try {
525                        String res = we.execute(inputWF, inputs);
526                        System.out.println(res);
527                        System.out.println("AFTER");
528
529                } catch (Exception ex) {
530                        ex.printStackTrace();
531                }
532        }
533
534}