001/*
002 * Copyright (c) 2009-2010 The Regents of the University of California.
003 * All rights reserved.
004 *
005 * '$Author: crawl $'
006 * '$Date: 2012-11-26 22:19:36 +0000 (Mon, 26 Nov 2012) $' 
007 * '$Revision: 31113 $'
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.camera.service;
031
032import java.io.BufferedReader;
033import java.io.File;
034import java.io.FileNotFoundException;
035import java.io.IOException;
036import java.io.InputStream;
037import java.io.InputStreamReader;
038import java.io.StringReader;
039import java.net.ConnectException;
040import java.net.MalformedURLException;
041import java.net.URL;
042import java.util.ArrayList;
043import java.util.Iterator;
044import java.util.List;
045
046import org.apache.commons.httpclient.HttpClient;
047import org.apache.commons.httpclient.HttpException;
048import org.apache.commons.httpclient.methods.GetMethod;
049import org.apache.commons.httpclient.methods.MultipartPostMethod;
050import org.apache.commons.httpclient.methods.multipart.FilePart;
051import org.apache.commons.httpclient.methods.multipart.Part;
052import org.apache.commons.httpclient.methods.multipart.StringPart;
053import org.apache.commons.logging.Log;
054import org.apache.commons.logging.LogFactory;
055import org.jdom.Document;
056import org.jdom.Element;
057import org.jdom.input.SAXBuilder;
058
059import ptolemy.actor.IOPort;
060import ptolemy.actor.TypedAtomicActor;
061import ptolemy.actor.TypedIOPort;
062import ptolemy.actor.gui.ColorAttribute;
063import ptolemy.actor.lib.Const;
064import ptolemy.actor.parameters.PortParameter;
065import ptolemy.data.BooleanToken;
066import ptolemy.data.StringToken;
067import ptolemy.data.Token;
068import ptolemy.data.expr.FileParameter;
069import ptolemy.data.expr.Parameter;
070import ptolemy.data.expr.StringParameter;
071import ptolemy.data.type.ArrayType;
072import ptolemy.data.type.BaseType;
073import ptolemy.data.type.Type;
074import ptolemy.kernel.CompositeEntity;
075import ptolemy.kernel.util.Attribute;
076import ptolemy.kernel.util.ChangeRequest;
077import ptolemy.kernel.util.IllegalActionException;
078import ptolemy.kernel.util.Location;
079import ptolemy.kernel.util.NameDuplicationException;
080import ptolemy.vergil.icon.ValueIcon;
081import ptolemy.vergil.toolbox.VisibleParameterEditorFactory;
082
083//////////////////////////////////////////////////////////////////////////
084////CAMERARESTService
085/**
086 * This CAMERA specific REST Service automatically generates the
087 * ports and parameters upon reading the URL of the csdl file.
088 * Choices are available for both Get and Post Services.
089 * 
090 *@author Madhu, SDSC  madhu@sdsc.edu
091 *@version $Id
092 */
093public class CAMERARESTService extends TypedAtomicActor {
094        private static final long serialVersionUID = 1L;
095        private static Log log = LogFactory.getLog(CAMERARESTService.class);
096        
097        private StringBuilder messageBldr = null;
098        
099        private static final String GET = "Get";
100        private static final String POST = "Post";
101        
102        /** URL of the csdl file */
103        public StringParameter paramF;
104         
105        /** The REST service URL. */
106        public PortParameter serviceSiteURL;
107        
108        /** old port list. */
109        public List oPortList = null;
110
111        /** The REST service method to use, either GET or POST. */
112    public Parameter methodType;
113    
114    /**
115     * List of the files. It is needed because file are treated
116     * differently.
117     */
118    private List<String> fileList = new ArrayList<String>();
119    
120    /** 
121     * Old display name for the actor,for associates parameters
122     * with the actor, it acts as prefix. 
123     */
124    private String oldDisplayName = null;
125    
126    private String ResName = null;
127    
128    /**
129     * This is the place name for the old file name.
130     * initial value of this parameter is empty sting.
131     * However its vale is updated to the current url
132     * at the end of the attributedChanged method.
133     */
134    private String gFilePath = ServiceUtils.NOSPACE;
135    
136    /** Output of REST service. */
137        public TypedIOPort outputPort;
138
139        public static final int TIMEOUT = 10000;
140        public CompositeEntity con;
141        
142        public CAMERARESTService(CompositeEntity container,  String name)throws NameDuplicationException, IllegalActionException  {
143                super(container, name);
144                con = container;
145                paramF = new StringParameter(this, "Please provide URL");
146                
147                serviceSiteURL = new PortParameter(this, "serviceSiteURL");
148            serviceSiteURL.setExpression(""); 
149            serviceSiteURL.setStringMode(true);
150            
151            methodType = new Parameter(this, "methodType");
152            methodType.setExpression(""); 
153            methodType.setStringMode(true);
154            methodType.addChoice(GET);
155            methodType.addChoice(POST);
156              
157            outputPort = new TypedIOPort(this, "outputPort", false, true);
158                outputPort.setTypeEquals(BaseType.STRING);
159
160        }
161        
162        /* 
163         * Results from the output service are sent to the 
164         * output port.
165         * 
166         * (non-Javadoc)
167         * @see ptolemy.actor.AtomicActor#fire()
168         */
169        @Override
170        public void fire() throws IllegalActionException {
171                super.fire();
172                getContainer().attributeList(org.camera.service.CAMERARESTService.class);
173                serviceSiteURL.update();
174                
175                String ssURL = getServiceSiteURL();
176                
177                if(ServiceUtils.checkEmptyString(ssURL)){
178                        outputPort.send(0, new StringToken("Please provide URL"));
179                        return;
180                }else if(!ssURL.startsWith("http://")){
181                        outputPort.send(0, new StringToken("URL must start with http://"));
182                        return;
183                }
184                List<NameValuePair> completeList = getPortValuePairs();
185                System.out.println("TOTAL ELEMENTS IN THE COMPLETE LIST: " + completeList.size());
186                List<NameValuePair> filePairList = new ArrayList<NameValuePair>();
187                for(NameValuePair nmvlPair: completeList){
188                        if(fileList.contains(nmvlPair.getName())){
189                                filePairList.add(nmvlPair);
190                        }
191                }
192                System.out.println("ELEMENTS IN THE FILE LIST: " + filePairList.size());
193                if(filePairList != null && filePairList.size() > 0){
194                        completeList.removeAll(filePairList);
195                }
196                System.out.println("TOTAL ELEMENTS IN THE COMPLETE LIST AFTER REMOVAL: " + completeList.size());
197                String returnedResults = null;
198                if(methodType.getExpression().equals(GET)){
199                log.debug("CALLING GET METHOD");
200                try{
201                        returnedResults = executeGetMethod(completeList, ssURL);
202                }catch(IllegalActionException ilae){
203                        ilae.printStackTrace();
204                        throw ilae;
205                }
206            }else if(methodType.getExpression().equals(POST)){
207                try{
208                        returnedResults = executePostMethod(completeList, filePairList, ssURL);
209                }catch(IllegalActionException ilae){
210                        ilae.printStackTrace();
211                        throw ilae;
212                }
213                
214            }else {
215                returnedResults = "NO WEB SERVICE CALL MADE";
216                System.out.println("NEITHER GET NOR POST");
217            }
218                
219                messageBldr = null; // messageBldr is set to null again
220                outputPort.send(0, new StringToken(returnedResults));
221                
222        }
223        
224        /**
225         * This method returns the appender that will be added to this
226         * actors display name. It gets the appender from the actors name
227         * that is taken care by kepler when multiple instances of the actor
228         * are added on the canvas.
229         *  
230         *       */
231        private String getAppender(){
232                String actorName = getName();
233                char c1 = actorName.charAt(actorName.length()-1);
234                System.out.println("Character 1: " + Character.toString(c1));
235                char c2 = actorName.charAt(actorName.length()-2);
236                System.out.println("Character 2: " + Character.toString(c2));
237                boolean check2 = false;
238                boolean check1 = false;
239                StringBuilder tmp = new StringBuilder("");
240                if( c2 > 47 && c2 < 58){
241                        check2 = true;
242                }
243                if( c1 > 47 && c1 < 58){
244                        check1 = true;
245                }
246                if(check1 && check2){
247                        return  tmp.append(c2).append(c1).toString();
248                }
249                else if(check1){
250                        return tmp.append(c1).toString();
251                }
252                return "";
253        }
254        
255        /* (non-Javadoc)
256         * @see ptolemy.kernel.util.NamedObj#attributeChanged(ptolemy.kernel.util.Attribute)
257         */
258        @Override
259        public void attributeChanged(Attribute at) throws IllegalActionException {
260                        
261                StringBuilder contents = new StringBuilder();
262                String filePath = paramF.getExpression().trim();
263                if(at == paramF && !ServiceUtils.checkEmptyString(paramF.getExpression())){
264
265                        log.debug("G File path: " + gFilePath + " : " + "FilePath: " + filePath);       
266                        try {   
267                                
268                                BufferedReader input = null;
269                                if(filePath.startsWith("http")){                                        
270                                        URL urlLocation = new URL(filePath);
271                                        input = new BufferedReader(new InputStreamReader(urlLocation.openStream()));
272                                        
273                                }
274
275                            String line = null; //not declared within while loop
276                               
277                            while (( line = input.readLine()) != null){
278                                contents.append(line);
279                                contents.append(System.getProperty("line.separator"));
280                            }
281                            
282                            SAXBuilder builder = new SAXBuilder();
283                                
284                                Document doc = builder.build(new StringReader(contents.toString()));
285                                
286                                Element elementURL = doc.getRootElement().getChild("resources");
287                                String serviceURL = elementURL.getAttributeValue("base_uri");
288                                
289                                Element elementRES = elementURL.getChild("resource");
290                                String resourceName = elementRES.getAttributeValue("name");
291                                ResName = resourceName;
292                                                        
293                                Element elementMethod = elementRES.getChild("method");
294                                String methodName = elementMethod.getAttributeValue("name");
295                                
296                                List<Element> elemParameters = elementMethod.getChild("request").getChildren("parameter");
297//                              Element elemStr = doc
298//                                              .getRootElement().getChild("allNames").getChild("entity").getChild("NAMESTR");
299                                
300                                methodType.setExpression(methodName);
301                                serviceSiteURL.setExpression(serviceURL);
302                                
303                                double [] position = new double[2];
304                                position[0] = 150.0;
305                                position[1] = 110.0;
306                                System.out.println("Elements in the List: " + elemParameters.size());
307                                
308                                if(!filePath.equals(gFilePath)){
309
310                                        ResName = resourceName;
311                                        String appender = getAppender();
312                                        this.setDisplayName(ResName+appender);
313                                        fileList.clear();
314                                        if(!ServiceUtils.checkEmptyString(gFilePath) && !ServiceUtils.checkEmptyString(getOldDisplayName())){
315                                                remAttributes(getOldDisplayName()+"_");
316                                        }
317                                        oPortList = this.inputPortList();
318                                        
319                                        for(Element element: elemParameters){
320                                                String tmp = element.getChild("name").getTextTrim();
321                                                String type = element.getChild("type").getTextTrim();
322                                                String descript = element.getChild("descriptive_name").getTextTrim();
323//                                              System.out.println("TMP: " + tmp + ", i= " + i);
324                                                boolean check = checkIfPortNameExists(tmp);
325                                                if(!check){                                                                             
326                                                        configureActorPort(tmp, descript, type);
327                                                }
328//                                              System.out.println("A: " + tmp);
329                                                
330                                                if(type.equals("file")){
331                                                        fileList.add(tmp);
332                                                }
333                                                if(!ServiceUtils.checkEmptyString(filePath)){
334//                                                              if(!ServiceUtils.checkEmptyString(gFilePath) || (ServiceUtils.checkEmptyString(gFilePath) && (ServiceUtils.checkEmptyString(tmpParam.getExpression())))){
335                                                        position[1] = position[1] +  15.0;
336                                                        System.out.println("B: " + descript);   
337                                                        configureActorParameter(ResName,appender, descript, type, position);
338//                                                      configureActorParameter(ResName+"_"+descript, type, position);
339                                                }                                               
340                                                
341                                        }
342
343                                        gFilePath = filePath;
344                                        System.out.println("AFTER G File path: " + gFilePath + " : " + "FilePath: " + filePath);
345                                        removeMyPorts(); // It removes the remaining ports from the old list, which are redundant.
346                                        setOldDisplayName(ResName);
347                                }
348                        
349                                System.out.println("TOTAL NUMBER OF FILES: " + fileList.size());        
350                                for(String fl: fileList){
351                                        log.debug("File: " + fl);
352                                }
353                                
354                                System.out.println("Total number of elements in the Old p LISt: " + oPortList.size());
355                                
356                        }catch(MalformedURLException mfue){
357                                        mfue.getStackTrace();
358                                        throw new IllegalActionException("MalformedURLEXception thrown");
359                        }catch (IOException ex){
360                                        ex.printStackTrace();
361                                        throw new IllegalActionException("IOException thrown");
362                        }catch(NameDuplicationException nde){
363                                nde.printStackTrace();  
364                                throw new IllegalActionException("NameDuplicationException thrown");
365                        }catch(Exception e){
366                                e.printStackTrace();
367                                throw new IllegalActionException("Exception thrown");                   
368                        }
369
370                }else if(ServiceUtils.checkEmptyString(paramF.getExpression())){
371                        
372                        gFilePath = null;
373                        
374                        try{
375                                removePorts();
376                                if(ResName != null){    
377                                        remAttributes(getOldDisplayName()+"_");
378                                }
379                        }catch(NameDuplicationException nde){
380                                System.out.println("Name is duplicated in....");
381                                nde.printStackTrace();
382                                throw new IllegalActionException("NameDuplicationException thrown");                            
383                        }                               
384
385                }else{
386                        super.attributeChanged(at);
387                }
388                
389        }
390        /**
391         * It returns the oldDisplayName that is needed to remove
392         * parameters from the canvas in response to the changes
393         * user makes to the url parameter on the actor. 
394         * 
395         *       */
396        private String getOldDisplayName(){
397                return oldDisplayName;
398        }
399        /**
400         * @param name
401         */
402        private void setOldDisplayName(String name){
403                oldDisplayName = name;
404        }
405        
406        /**
407     * Issue a ChangeRequest to change the output ports.
408     * @throws ptolemy.kernel.util.IllegalActionException
409     */
410    private void reconfigurePorts(String why) {
411 //       log.debug("Creating reconfigure ports change request " + why);
412        this.requestChange( new ChangeRequest(this,why ) {
413            public void _execute() throws Exception {
414
415            }
416        });
417    }
418                
419        /**
420         * This method checks if the port with the provided name
421         * exists or not.
422         * @param value Port name
423         * @return true if port with the provided name exists else return false
424         */
425        public boolean checkIfPortNameExists(String value){
426                boolean test = false;
427        
428                List pList = oPortList;
429                
430                if (pList != null && pList.size()> 0){
431                        System.out.println("Number of elements in the old list: " + pList.size());
432                        for(int i = 0; i < pList.size(); i++){
433                                if(((IOPort)pList.get(i)).getName().equals(value)){
434                                        System.out.println("Found the port: " + value);
435                                        oPortList.remove(i);
436                                        test = true;
437                                        break;
438                                }
439                        }
440                }
441                
442                return test;
443        }
444        
445        /**
446         * Removes port that were in the old list but not used currently
447         */
448        public void removeMyPorts()throws NameDuplicationException, IllegalActionException{
449                List inPortList = oPortList;
450                Iterator ports = inPortList.iterator();
451                while (ports.hasNext()) {
452                        IOPort p = (IOPort) ports.next();
453                        if (p.isInput()) {
454
455                                if (!(p.getName().equals("serviceSiteURL"))){
456                                        System.out.println("Port removed: " + p.getName());
457                                        p.setContainer(null);
458                                }
459
460                    }
461                }
462        }
463        /**
464         * This method removes all input ports
465         */
466        public void removePorts() throws NameDuplicationException, IllegalActionException{
467                List inPortList = this.inputPortList();
468                Iterator ports = inPortList.iterator();
469                while (ports.hasNext()) {
470                        IOPort p = (IOPort) ports.next();
471                        if (p.isInput()) {
472                                if (!(p.getName().equals("serviceSiteURL"))){
473                                        System.out.println("Port removed: " + p.getName());
474                                        p.setContainer(null);
475                        }
476                       
477                    }
478                }
479        }
480        
481                
482        /**
483         * This method creates Parameters with name as value and data type
484         * it represents as valueType. The location of the parameter depends
485         * upon pos.
486         * 
487         * @param value
488         * @param valueType
489         * @param pos
490         * @throws IllegalActionException
491         * @throws NameDuplicationException
492         */
493        public void configureActorParameter(String value,  String appender, String description,String valueType, double[] pos)throws IllegalActionException{
494//              System.out.println("In method configureActorParameter: " + value);
495        
496                Parameter param = null;
497                try{
498                        if(valueType.equalsIgnoreCase("file")){
499                                param = new FileParameter(getContainer().toplevel(), value+appender+"_"+description);
500                        }else if(valueType.equalsIgnoreCase("string") ||valueType.equalsIgnoreCase("double")){
501                                param = new StringParameter(getContainer().toplevel(), value+appender+"_"+description);
502                        }else{
503                                param = new Parameter(getContainer().toplevel(), value+appender+"_"+description);
504                        }
505                        param.setDisplayName(description.replaceAll("_", ServiceUtils.ANEMPTYSPACE)+ServiceUtils.ANEMPTYSPACE+appender);
506                        Location location = new Location(param, "_location");
507                        location.setLocation(pos);
508                
509                        ValueIcon vIcon = new ValueIcon(param,"_icon");         
510                        ColorAttribute colorAttr = new ColorAttribute(vIcon, "_color");
511                        vIcon.createIcon();
512                        VisibleParameterEditorFactory vpeFactor = new VisibleParameterEditorFactory(param,"_editorFactory");
513                }catch(NameDuplicationException nde){
514                        
515                }
516
517        }
518
519        
520        /**
521         * Currently, this method is not used.
522         * @param name
523         * @param value
524         * @param pos
525         * @throws IllegalActionException
526         * @throws NameDuplicationException
527         */
528        public void configureActorConstant(String name, String value, double[] pos)throws IllegalActionException, NameDuplicationException{
529                System.out.println("Constant: " + value);
530                Const param = new Const(con, name);
531                param.setDisplayName(value);
532                Location location = new Location(param, "_location");
533                location.setLocation(pos);
534                
535        }
536        
537        /**
538         * It dynamically creates port with name as value and display
539         * name as description and port type is set as valueType.
540         *
541         * @param value
542         * @param description
543         * @param valueType
544         * @throws IllegalActionException
545         * @throws NameDuplicationException
546         */
547        public void configureActorPort(String value,String description, String valueType)throws IllegalActionException, NameDuplicationException{
548//              System.out.println("Port: " + value);
549                TypedIOPort port = new TypedIOPort(this, value, true, false);           
550                _setPortType(port, valueType);
551                port.setDisplayName(description);
552//              reconfigurePorts("XXX");
553
554//              _addPort(_port);
555        }
556        
557        /**
558         * Parameters whose names start with resName are removed by this method.
559         * 
560         * @param resName 
561         * @throws IllegalActionException
562         * @throws NameDuplicationException
563         */
564        public void remAttributes(String resName) throws IllegalActionException, NameDuplicationException{
565                
566                List paramList = getContainer().attributeList();
567                System.out.println("Parameters in the LIST: " + paramList.size());
568                List<Attribute> attrList = new ArrayList<Attribute>();
569                Iterator attributes = paramList.iterator();
570                
571                while (attributes.hasNext()) {
572                        Attribute attr = (Attribute) attributes.next();
573//                      try{
574                        if(attr instanceof Parameter && !(attr.getName().equals("_parser"))){
575                                System.out.println("ATTR PARAM: " + attr.getName());
576                                if(resName != null && attr.getName().startsWith(resName)){
577                                        attrList.add(attr);
578                                }
579                        }else{
580                                System.out.println("ATTR: " + attr.getName());
581                        }
582//                      }catch(Exception e){
583//                              e.printStackTrace();
584//                      }
585                }
586                
587                for(Attribute attr: attrList){
588                        attr.setContainer(null);
589                }
590        }
591        
592        /**
593         * It returns the URL provided as a value of <i> serviceSiteURL </i> 
594         * Parameter for RESTService actor as a String.
595         * 
596         * @return ServiceSiteURL as String
597         */
598        private String getServiceSiteURL() throws IllegalActionException{
599                
600                return ((StringToken)serviceSiteURL.getToken()).stringValue().trim();
601                
602        }
603        
604        /**
605         * It works only on user defined/configured ports and excludes actor
606         * defined ports.
607         * @return List of Name, Value pairs of port names and values
608         */             
609        private List<NameValuePair> getPortValuePairs() throws IllegalActionException{
610                
611                List<NameValuePair> nvList = new ArrayList<NameValuePair>();
612                List inPortList = this.inputPortList();
613                Iterator ports = inPortList.iterator();
614                
615                while (ports.hasNext()) {
616                IOPort p = (IOPort) ports.next();
617                if(!p.getName().equals(serviceSiteURL.getName())){              
618                        
619                                String pValue = getPortValue(p);
620                                
621                                
622                                if(pValue != null && pValue.trim().length() != 0){
623                                        if(pValue.startsWith("file:")){
624                                                String altered = null;
625                                                if(ServiceUtils.OS.startsWith("Windows")){
626                                                        altered= pValue.replaceFirst("file:/", "");//.replace("/", "\\");
627                                                }else{
628                                                        altered= pValue.replaceFirst("file:", "");
629                                                }
630                                                pValue = altered;
631                                        }
632                                        nvList.add(new NameValuePair(p.getName(), pValue));
633                                        log.debug("NAME: " + p.getName ()+ " VALUE: " + pValue);
634                                }
635                        
636                }
637        }
638                
639                return nvList;
640
641        }
642        
643        /**
644         * 
645         * @param iop
646         * @return the value associated with a particular port
647         * @throws IllegalActionException
648         */
649        private String getPortValue(IOPort iop) throws IllegalActionException{
650                
651                String result = null;
652                if(iop.getWidth() > 0){
653                        Token tk = iop.get(0);
654                        Type tp = tk.getType();
655                        if(tp == BaseType.INT || tp == BaseType.LONG ||
656                                        tp == BaseType.FLOAT || tp == BaseType.DOUBLE){
657                                
658                                result = tk.toString().trim();
659                                System.out.println("String value of the Token: " + result);
660                        }else if(tp == BaseType.BOOLEAN){
661                                if(((BooleanToken)tk).booleanValue()){
662                                        result = String.valueOf(1);
663                                }else{
664                                        result = String.valueOf(0);
665                                }
666                                        
667                        }else{
668                                result =((StringToken)tk).stringValue().trim();
669                        }
670                        if(_debugging){
671                                _debug("In getPortValue method RESULT: " + result);
672                        }
673                }
674                return result;
675        }
676        
677        /**
678         * 
679         * @param val
680         * @return the File object for the supplied String
681         */
682        private File getFileObject(String val){
683                return new File(val);
684        }
685        
686        
687        /**
688         * File & regular parameters are passed as two separate lists and they are treated
689         * little differently. If flPairList is not null or empty then this method uses Part
690         * Object else no.
691         * @param pmPairList List of the name and value parameters that user has provided
692         * @param flPairList List of the name and value (full file path)of file parameters.
693         *                      It is essentially a list of files that user wishes to attach.
694         * @return  the results after executing the Post service.
695         */
696        public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList, String serSiteURL) throws IllegalActionException{
697                
698                if(_debugging){
699                _debug("I AM IN POST METHOD");
700                }
701                                
702                log.debug("I AM IN POST METHOD");
703        String postAddress = serSiteURL;
704
705        HttpClient client = new HttpClient();
706        MultipartPostMethod method = new MultipartPostMethod(postAddress);
707                List<NameValuePair> fullNameValueList = pmPairList;             
708                if(flPairList != null && flPairList.size() > 0){
709                        fullNameValueList.addAll(flPairList);
710                        int totalSize = fullNameValueList.size();
711                        Part[] parts = new Part[totalSize];
712                        
713                        try{
714                                
715                                for(int i = 0; i < parts.length; i++){
716                        
717                                        String nm = fullNameValueList.get(i).getName();
718                                        String vl = fullNameValueList.get(i).getValue();
719                                
720                                        if(i > totalSize - flPairList.size() - 1){
721                                                System.out.println("FILE NAME: " + nm);
722                                                File file = getFileObject(vl);
723                                                System.out.println("FILE NAME: " + file.getName());
724                                                parts[i] = new FilePart(nm, file);
725                                                method.addPart(parts[i]);
726                                                System.out.println("PARTS: " + i + " " + parts[i].getName());
727                                                System.out.println( "file Name: " + vl);
728                                        
729                                        }else{
730                                                
731                                                System.out.println("PARAMETER NAME: " + nm);
732                                                System.out.println("PARAMETER Value: " + vl);
733                                                parts[i] = new StringPart(nm, vl);
734                                                method.addPart(parts[i]);
735                                                
736                                        }
737                                        if(_debugging){
738                                        _debug("Value of i: " + i);
739                                        }
740                                
741                                }
742                                
743                        
744                        }catch(FileNotFoundException fnfe){
745                                if(_debugging){
746                                _debug("File Not Found Exception: " + fnfe.getMessage());
747                                }
748                                fnfe.printStackTrace();
749                                throw new IllegalActionException("File Not Found: " + fnfe.getMessage());
750                        }
751                }else{
752                        for(NameValuePair nmPair: fullNameValueList){                   
753                                method.addParameter(nmPair.getName(), nmPair.getValue());
754                                System.out.println("Name: " + nmPair.getName()+ "  Value:" + nmPair.getValue());
755                        }
756                }
757                
758                InputStream rstream = null;
759                StringBuilder results = new StringBuilder();
760                try{
761
762                        messageBldr = new StringBuilder();
763                        messageBldr.append("In excutePostMethod, communicating with service: ").
764                        append(serSiteURL).append("   STATUS Code: ");
765                        
766                        int statusCode = client.executeMethod(method);
767                        messageBldr.append(statusCode);
768                        
769                        log.debug("DEBUG: " + messageBldr.toString());
770                        System.out.println(messageBldr.toString());
771                        
772                        rstream = method.getResponseBodyAsStream();
773                        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
774        
775                        log.debug("BEFORE WHILE LOOP");
776                        String s;
777                        while( (s = br.readLine())!= null){                     
778                                results.append(s).append(ServiceUtils.LINESEP);
779                        }
780                        
781        }catch (HttpException httpe) {
782                if(_debugging){
783                        _debug("Fatal protocol violation: " + httpe.getMessage());
784                        }
785                        httpe.printStackTrace();
786//                      return "Protocol Violation";
787                        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
788                }catch(ConnectException conExp){
789                        if(_debugging){
790                        _debug("Perhaps service not reachable: " + conExp.getMessage());
791                        }
792
793                        conExp.printStackTrace();
794                        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
795//                      return "Perhaps service not reachable";
796                }catch (IOException ioe) {
797                        if(_debugging){
798                        _debug("Fatal transport error: " + ioe.getMessage());
799                        }
800
801                        ioe.printStackTrace();
802//                      return "IOException: Perhaps could not connect to the service.";
803                        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
804                }catch (Exception e) {
805                        if(_debugging){
806                        _debug("Unknown error: " + e.getMessage());
807                        }
808                        e.printStackTrace();
809//                      return "Exception: Unknown type error";
810                        throw new IllegalActionException("Error: " + e.getMessage());
811                }finally {
812                          // Release the connection.
813                method.releaseConnection();
814            }
815                return results.toString();
816        }
817        
818        /**
819         *  
820         * @param pmPairList List of the name and value parameters that user has provided
821         * through paramInputPort. However in  method this list is combined with
822         * the user configured ports and the combined list name value pair parameters are
823         * added to the service URL separated by ampersand.
824         * @param nvPairList List of the name and value parameters that user has provided
825         * @return the results after executing the Get service.
826         */
827        public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL)throws IllegalActionException{
828                
829                if(_debugging){
830                _debug("I AM IN GET METHOD");
831        }
832                        
833                HttpClient client = new HttpClient();
834                 
835                StringBuilder  results =new StringBuilder();
836                results.append(serSiteURL);
837                //Files cannot be attached with GET
838                List<NameValuePair> fullPairList = nvPairList;// getCombinedPairList(nvPairList);
839
840                if(fullPairList.size() > 0){
841                        
842                        results.append("?");
843                        
844                        int pairListSize = fullPairList.size();
845                        for(int j = 0; j < pairListSize; j++){
846                                NameValuePair nvPair = fullPairList.get(j);
847                                results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue());
848                                if(j < pairListSize - 1){                       
849                                        results.append("&");
850                                }
851
852                        }
853                }
854                if(_debugging){
855                _debug("RESULTS :"  + results.toString());
856                }
857 
858                // Create a method instance.
859                GetMethod method = new GetMethod(results.toString());
860                InputStream rstream = null;
861                StringBuilder resultsForDisplay = new StringBuilder();                      
862                        
863                try{
864                        
865                        messageBldr = new StringBuilder();
866                        messageBldr.append("In excutePostMethod, communicating with service: ").
867                        append(serSiteURL).append("   STATUS Code: ");
868                        
869                        int statusCode = client.executeMethod(method);
870                        messageBldr.append(statusCode);
871                        
872                        log.debug("DEBUG: " + messageBldr.toString());
873                        System.out.println(messageBldr.toString());
874                                                                
875                        rstream = method.getResponseBodyAsStream();
876                        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));                 
877                                
878                        String s;
879                        while( (s = br.readLine())!= null){                     
880                                resultsForDisplay.append(s).append(ServiceUtils.LINESEP);
881                        }
882                                                
883                }catch (HttpException httpe) {
884                        if(_debugging){
885                        _debug("Fatal protocol violation: " + httpe.getMessage());
886                        }
887                        httpe.printStackTrace();
888//                      return "Protocol Violation";
889                        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
890                }catch(ConnectException conExp){
891                        if(_debugging){
892                        _debug("Perhaps service not reachable: " + conExp.getMessage());
893                        }
894                        conExp.printStackTrace();
895                        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
896                }catch (IOException ioe) {
897                        if(_debugging){
898                        _debug("Fatal transport error: " + ioe.getMessage());
899                        }
900                        ioe.printStackTrace();
901//                      return "IOException: fatal transport error";
902                        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
903                }catch (Exception e) {
904                        if(_debugging){
905                        _debug("Unknown error: " + e.getMessage());
906                        }
907                        e.printStackTrace();
908//                      return "Exception: Unknown type error";
909                        throw new IllegalActionException("Error: " + e.getMessage());
910                }finally {
911                          // Release the connection.
912                method.releaseConnection();
913            }
914                    
915            return resultsForDisplay.toString();
916
917        }
918                
919                
920        /**
921         * Set the type of a port based on a string representation of that type
922         * that was extracted from the WSDL description.
923         *
924         * @param arrayTypes a hash of defined array types by name
925         * @param port the port whose type is to be set
926         * @param typeStr the string representation of the type to be set
927         */
928        private void _setPortType(TypedIOPort port, String typeStr) {
929            
930                  if (typeStr.equals("int")) {
931                          port.setTypeEquals(BaseType.INT);
932                  }
933                  else if (typeStr.equals("boolean")) {
934                          port.setTypeEquals(BaseType.BOOLEAN);
935                  }
936                  else if (typeStr.equals("long")) {
937                          port.setTypeEquals(BaseType.LONG);
938                  }
939                  else if (typeStr.equals("double")) {
940                          port.setTypeEquals(BaseType.DOUBLE);
941                  }
942                  else if (typeStr.equals("float")) { //There is no float in Ptolemy type sys.
943                          port.setTypeEquals(BaseType.DOUBLE);
944                  }
945                  else if (typeStr.equals("byte")) {
946              //->There is no byte in Ptolemy type sys. So I cast the byte to INT.
947                          port.setTypeEquals(BaseType.INT);
948                  }
949                  else if (typeStr.equals("short")) {
950              //->There is no short in Ptolemy type sys. So again cast it to INT
951                          port.setTypeEquals(BaseType.INT);
952                  }
953                  else if (typeStr.equals("string")) {
954                          port.setTypeEquals(BaseType.STRING);
955                  }
956                  else if (typeStr.equals("string[]")) {
957                          port.setTypeEquals(new ArrayType(BaseType.STRING));
958                  }
959                  else if (typeStr.equals("byte[]")) {
960                          port.setTypeEquals(new ArrayType(BaseType.INT));
961                  }
962                  else if (typeStr.equals("short[]")) {
963                          port.setTypeEquals(new ArrayType(BaseType.INT));
964                  }
965                  else if (typeStr.equals("int[]")) {
966                          port.setTypeEquals(new ArrayType(BaseType.INT));
967                  }
968                  else if (typeStr.equals("long[]")) {
969                          port.setTypeEquals(new ArrayType(BaseType.LONG));
970                  }
971                  else if (typeStr.equals("double[]")) {
972                          port.setTypeEquals(new ArrayType(BaseType.DOUBLE));
973                  }
974                  else if (typeStr.equals("float[]")) {
975                          port.setTypeEquals(new ArrayType(BaseType.DOUBLE));
976                  }
977                  else if (typeStr.equals("boolean[]")) {
978                          port.setTypeEquals(new ArrayType(BaseType.BOOLEAN));
979                  }
980                  else {
981                          _debug(
982                        "<WARNING>Could not specify the type. Setting it to string. </WARNING>");
983                          port.setTypeEquals(BaseType.STRING);
984                  }
985          }
986
987}