290. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/5/2017 12:06:45 PM Central Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

290.1 Files compared

# Location File Last Modified
1 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingExchangeBaseWebProxy\main\src\java\gov\va\med\imaging\proxy ImageXChangeHttpCommonsSender.java Mon Dec 4 21:34:34 2017 UTC
2 IV-eHMP_CIF.zip\IMAG_Source\VISA\Java\ImagingExchangeBaseWebProxy\main\src\java\gov\va\med\imaging\proxy ImageXChangeHttpCommonsSender.java Tue Dec 5 13:21:26 2017 UTC

290.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 2188
Changed 1 2
Inserted 0 0
Removed 0 0

290.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

290.4 Active regular expressions

No regular expressions were active.

290.5 Comparison detail

  1   package go v.va.med.i maging.pro xy;
  2  
  3   /*
  4    * Copyrig ht 2001-20 04 The Apa che Softwa re Foundat ion.
  5    * 
  6    * License d under th e Apache L icense, Ve rsion 2.0  (the "Lice nse");
  7    * you may  not use t his file e xcept in c ompliance  with the L icense.
  8    * You may  obtain a  copy of th e License  at
  9    * 
  10    *      ht tp://www.a pache.org/ licenses/L ICENSE-2.0
  11    * 
  12    * Unless  required b y applicab le law or  agreed to  in writing , software
  13    * distrib uted under  the Licen se is dist ributed on  an "AS IS " BASIS,
  14    * WITHOUT  WARRANTIE S OR CONDI TIONS OF A NY KIND, e ither expr ess or imp lied.
  15    * See the  License f or the spe cific lang uage gover ning permi ssions and
  16    * limitat ions under  the Licen se.
  17    */
  18  
  19   import gov .va.med.im aging.tomc at.vistare alm.VistaR ealmPrinci pal;
  20   import gov .va.med.im aging.tomc at.vistare alm.VistaR ealmSecuri tyContext;
  21  
  22   import jav a.io.*;
  23   import jav a.net.URL;
  24   import jav a.util.*;
  25   import jav a.util.zip .GZIPInput Stream;
  26   import jav a.util.zip .GZIPOutpu tStream;
  27  
  28   import jav ax.xml.soa p.MimeHead er;
  29   import jav ax.xml.soa p.MimeHead ers;
  30   import jav ax.xml.soa p.SOAPExce ption;
  31  
  32   import org .apache.ax is.AxisFau lt;
  33   import org .apache.ax is.Constan ts;
  34   import org .apache.ax is.Message ;
  35   import org .apache.ax is.Message Context;
  36   import org .apache.ax is.compone nts.net.Co mmonsHTTPC lientPrope rties;
  37   import org .apache.ax is.compone nts.net.Co mmonsHTTPC lientPrope rtiesFacto ry;
  38   import org .apache.ax is.compone nts.net.Tr ansportCli entPropert ies;
  39   import org .apache.ax is.compone nts.net.Tr ansportCli entPropert iesFactory ;
  40   import org .apache.ax is.handler s.BasicHan dler;
  41   import org .apache.ax is.soap.SO AP12Consta nts;
  42   import org .apache.ax is.soap.SO APConstant s;
  43   import org .apache.ax is.transpo rt.http.HT TPConstant s;
  44   import org .apache.ax is.utils.J avaUtils;
  45   import org .apache.ax is.utils.M essages;
  46   import org .apache.ax is.utils.N etworkUtil s;
  47   import org .apache.co mmons.http client.*;
  48   import org .apache.co mmons.http client.aut h.AuthScop e;
  49   import org .apache.co mmons.http client.coo kie.Cookie Policy;
  50   import org .apache.co mmons.http client.met hods.GetMe thod;
  51   import org .apache.co mmons.http client.met hods.PostM ethod;
  52   import org .apache.co mmons.http client.met hods.Reque stEntity;
  53   import org .apache.co mmons.http client.par ams.HttpMe thodParams ;
  54   import org .apache.lo gging.log4 j.LogManag er;
  55   import org .apache.lo gging.log4 j.Logger;
  56  
  57   import gov .va.med.im aging.tran sactioncon text.Trans actionCont ext;
  58   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extFactory ;
  59   import gov .va.med.im aging.tran sactioncon text.Trans actionCont extHttpHea ders;
  60  
  61   /**
  62    * This cl ass uses J akarta Com mons's Htt pClient to  call a SO AP server.  This is
  63    * almost  a direct c opy of org .apache.ax is.client. http.Commo nsHTTPSend er with a
  64    * couple  of additio ns to allo w us to ma nipulate t he HTTP he aders to p ass
  65    * authent ication in formation.
  66    * 
  67    * @author  Davanum S rinivas (d ims@yahoo. com)
  68    * @author  Chris Bec key (c.bec key@comcas t.net)
  69    */
  70   public cla ss ImageXC hangeHttpC ommonsSend er 
  71   extends Ba sicHandler  
  72   {
  73           pr ivate stat ic final l ong serial VersionUID  = 5231525 4330649788 60L;
  74  
  75           pu blic final  static St ring ENCOD ING_DEFLAT E = "defla te";
  76           pr ivate stat ic final S tring COMP RESSION_DE FLATE = "d eflate";
  77       protec ted Logger  log = Log Manager.ge tLogger(th is.getClas s().getNam e());
  78       
  79       protec ted HttpCo nnectionMa nager conn ectionMana ger;
  80       protec ted Common sHTTPClien tPropertie s clientPr operties;
  81       boolea n httpChun kStream =  false; //  Use HTTP c hunking by  default o r not.
  82  
  83       public  ImageXCha ngeHttpCom monsSender () {
  84           lo g.debug("< ctor>()");
  85           in itialize() ;
  86           lo g.debug("< ctor>() -  initialize d");
  87       }
  88  
  89       protec ted void i nitialize(
  90       {
  91           Mu ltiThreade dHttpConne ctionManag er cm = ne w MultiThr eadedHttpC onnectionM anager();
  92           th is.clientP roperties  = CommonsH TTPClientP ropertiesF actory.cre ate();
  93           cm .getParams ().setDefa ultMaxConn ectionsPer Host(clien tPropertie s.getMaxim umConnecti onsPerHost ());
  94           cm .getParams ().setMaxT otalConnec tions(clie ntProperti es.getMaxi mumTotalCo nnections( ));
  95           
  96           //  If define d, set the  default t imeouts
  97           //  Can be ov erridden b y the Mess ageContext
  98           if (this.clie ntProperti es.getDefa ultConnect ionTimeout ()>0)
  99               cm.getPar ams().setC onnectionT imeout(thi s.clientPr operties.g etDefaultC onnectionT imeout());
  100           
  101           if (this.clie ntProperti es.getDefa ultSoTimeo ut()>0)
  102               cm.getPar ams().setS oTimeout(t his.client Properties .getDefaul tSoTimeout ());
  103           
  104           th is.connect ionManager  = cm;
  105       }
  106       
  107       /**
  108            *  invoke cr eates a so cket conne ction, sen ds the req uest SOAP  message an d
  109            *  then read s the resp onse SOAP  message ba ck from th e SOAP ser ver
  110            *  
  111            *  @param ms gContext
  112            *              the mess sage conte xt
  113            *  
  114            *  @throws A xisFault
  115            * /
  116       public  void invo ke(Message Context ms gContext) 
  117       throws  AxisFault  
  118       {
  119           Ht tpMethodBa se method  = null;
  120           lo g.debug(Me ssages.get Message("e nter00", " CommonsHtt pSender::i nvoke"));
  121           tr
  122           {
  123                URL targ etURL = ne w URL( msg Context.ge tStrProp(M essageCont ext.TRANS_ URL) );
  124                
  125                // no ne ed to reta in these,  as the coo kies/crede ntials are
  126                // store d in the m essage con text acros s multiple  requests.
  127                // the u nderlying  connection  manager,  however, i s retained
  128                // so so ckets get  recycled w hen possib le.
  129                HttpClie nt httpCli ent = new  HttpClient (this.conn ectionMana ger);
  130                
  131                // the t imeout val ue for all ocation of  connectio ns from th e pool
  132                httpClie nt.getPara ms().setCo nnectionMa nagerTimeo ut(this.cl ientProper ties.getCo nnectionPo olTimeout( ));
  133  
  134                HostConf iguration  hostConfig uration = 
  135                    getH ostConfigu ration(htt pClient, m sgContext,  targetURL );
  136                
  137                boolean  posting =  true;
  138                
  139                // If we 're SOAP 1 .2, allow  the web me thod to be  set from  the
  140                // Messa geContext.
  141                if (msgC ontext.get SOAPConsta nts() == S OAPConstan ts.SOAP12_ CONSTANTS)  
  142                {
  143                    Stri ng webMeth od = msgCo ntext.getS trProp(SOA P12Constan ts.PROP_WE BMETHOD);
  144                    if ( webMethod  != null) 
  145                         posting =  webMethod. equals(HTT PConstants .HEADER_PO ST);
  146                }
  147  
  148                if (post ing) 
  149                {
  150                    Mess age reqMes sage = msg Context.ge tRequestMe ssage();
  151                    meth od = new P ostMethod( targetURL. toString() );
  152                    log. info("POST  message c reated wit h target [ " + target URL.toStri ng() + "]" );
  153                    Tran sactionCon text trans actionCont ext = Tran sactionCon textFactor y.get();
  154                    tran sactionCon text.addDe bugInforma tion("POST  message c reated wit h target [ " + target URL.toStri ng() + "]" );
  155  
  156                    // s et false a s default,  addContet Info can o verwrite
  157                    meth od.getPara ms().setBo oleanParam eter(HttpM ethodParam s.USE_EXPE CT_CONTINU E,
  158                                                               false );
  159                    
  160                    addC ontextInfo (method, h ttpClient,  msgContex t, targetU RL);
  161                    
  162                    Cred entials cr ed = httpC lient.getS tate().get Credential s(AuthScop e.ANY);
  163                    if(c red instan ceof Usern amePasswor dCredentia ls)
  164                    {
  165                             log.tr ace("POST  message cr eated on c lient with  credentia ls [" + 
  166                                      ((Userna mePassword Credential s)cred).ge tUserName( ) + ", " +  ((Usernam ePasswordC redentials )cred).get Password()  +  
  167                                      "].");
  168                    }
  169  
  170                    Mess ageRequest Entity req uestEntity  = null;
  171                    if ( msgContext .isPropert yTrue(HTTP Constants. MC_GZIP_RE QUEST))
  172                    {
  173                             reques tEntity =  new GzipMe ssageReque stEntity(m ethod, req Message, h ttpChunkSt ream);
  174                         log.info(" HTTPCommon sSender -  zipping re quest.");
  175                    }
  176                    else
  177                    {
  178                             reques tEntity =  new Messag eRequestEn tity(metho d, reqMess age, httpC hunkStream );
  179                         log.info(" HTTPCommon sSender -  not zippin g request" );
  180                    }
  181                    ((Po stMethod)m ethod).set RequestEnt ity(reques tEntity);
  182                } 
  183                else 
  184                {
  185                    meth od = new G etMethod(t argetURL.t oString()) ;
  186                    log. info("GET  message cr eated with  target ["  + targetU RL.toStrin g() + "]") ;
  187                    addC ontextInfo (method, h ttpClient,  msgContex t, targetU RL);
  188                }
  189  
  190                if (msgC ontext.isP ropertyTru e(HTTPCons tants.MC_A CCEPT_GZIP ))
  191                    log. info("HTTP CommonsSen der - acce pting GZIP ");
  192                else
  193                    log. info("HTTP CommonsSen der - NOT  accepting  GZIP");
  194                
  195                String h ttpVersion  = msgCont ext.getStr Prop(Messa geContext. HTTP_TRANS PORT_VERSI ON);
  196                if (http Version !=  null && h ttpVersion .equals(HT TPConstant s.HEADER_P ROTOCOL_V1 0))
  197                             method .getParams ().setVers ion(HttpVe rsion.HTTP _1_0);
  198                
  199                // don't  forget th e cookies!
  200                // Cooki es need to  be set on  HttpState , since Ht tpMethodBa se
  201                // overw rites the  cookies fr om HttpSta te
  202                if (msgC ontext.get MaintainSe ssion()) 
  203                {
  204                    Http State stat e = httpCl ient.getSt ate();
  205                    meth od.getPara ms().setCo okiePolicy (CookiePol icy.BROWSE R_COMPATIB ILITY);
  206                    Stri ng host =  hostConfig uration.ge tHost();
  207                    Stri ng path =  targetURL. getPath();
  208                    
  209                    bool ean secure  = hostCon figuration .getProtoc ol().isSec ure();
  210                    fill Headers(ms gContext,  state, HTT PConstants .HEADER_CO OKIE, host , path, se cure);
  211                    fill Headers(ms gContext,  state, HTT PConstants .HEADER_CO OKIE2, hos t, path, s ecure);
  212                    http Client.set State(stat e);
  213                }
  214                
  215                // add H TTP header  fields th at the app lication t hinks are  "interesti ng"
  216                // the e xpectation  is that t hese would  be non-st andard HTT P headers,  
  217                // by co nvention s tarting wi th "xxx-"
  218                VistaRea lmPrincipa l principa l = VistaR ealmSecuri tyContext. get();
  219  
  220                if(princ ipal != nu ll)
  221                {
  222                    log. info("Secu rityContex t credenti als for '"  + princip al.getAcce ssCode() +  "' are av ailable.") ;
  223                    Stri ng duz = p rincipal.g etDuz();
  224                    if(d uz != null  && duz.le ngth() > 0 )
  225                             method .addReques tHeader( T ransaction ContextHtt pHeaders.h ttpHeaderD uz, duz);
  226                    
  227                    Stri ng fullnam e = princi pal.getFul lName();
  228                    if(f ullname !=  null && f ullname.le ngth() > 0 )
  229                             method .addReques tHeader( T ransaction ContextHtt pHeaders.h ttpHeaderF ullName, f ullname);
  230  
  231                    Stri ng sitenam e = princi pal.getSit eName();
  232                    if(s itename !=  null && s itename.le ngth() > 0 )
  233                             method .addReques tHeader( T ransaction ContextHtt pHeaders.h ttpHeaderS iteName, s itename);
  234  
  235                    Stri ng sitenum ber = prin cipal.getS iteNumber( );
  236                    if(s itenumber  != null &&  sitenumbe r.length()  > 0)
  237                             method .addReques tHeader( T ransaction ContextHtt pHeaders.h ttpHeaderS iteNumber,  sitenumbe r);
  238                    
  239                    Stri ng ssn = p rincipal.g etSsn();
  240                    if(s sn != null  && ssn.le ngth() > 0 )
  241                             method .addReques tHeader( T ransaction ContextHtt pHeaders.h ttpHeaderS SN, ssn);
  242                    
  243                    Stri ng securit yToken = p rincipal.g etSecurity Token();
  244                    if(s ecurityTok en != null  && securi tyToken.le ngth() > 0 )
  245                             method .addReques tHeader(Tr ansactionC ontextHttp Headers.ht tpHeaderBr okerSecuri tyTokenId,  securityT oken);
  246                    
  247                    Stri ng cacheLo cationId =  principal .getCacheL ocationId( );
  248                    if(c acheLocati onId != nu ll && cach eLocationI d.length()  > 0)
  249                             method .addReques tHeader(Tr ansactionC ontextHttp Headers.ht tpHeaderCa cheLocatio nId, cache LocationId );
  250                    
  251                    Stri ng userDiv ision = pr incipal.ge tUserDivis ion();
  252                    if(u serDivisio n != null  && userDiv ision.leng th() > 0)
  253                             method .addReques tHeader(Tr ansactionC ontextHttp Headers.ht tpHeaderUs erDivision , userDivi sion);
  254                }            
  255                else
  256                    log. debug("Sec urityConte xt credent ials are N OT availab le.");
  257  
  258                    meth od.addRequ estHeader(  HTTPConst ants.HEADE R_CACHE_CO NTROL, "no -cache,no- store");
  259                    meth od.addRequ estHeader(  HTTPConst ants.HEADE R_PRAGMA,  "no-cache" );
  260  
  261                    try{ log.info(" Executing  method ["  + method.g etPath() +  "] on tar get [" + h ostConfigu ration.get HostURL()  + "]");}
  262                    catc h(IllegalS tateExcept ion isX){}
  263                    
  264                // send  the HTTP r equest and  wait for  a response  
  265                int retu rnCode = h ttpClient. executeMet hod(hostCo nfiguratio n, method,  null);
  266                
  267                Transact ionContext  transacti onContext  = Transact ionContext Factory.ge t();
  268                // don't  set the r esponse co de here -  this is no t the resp onse code  we send ou t, but the  resposne  code we ge t back fro m the data  source
  269                //transa ctionConte xt.setResp onseCode ( String.val ueOf (retu rnCode));
  270                
  271                // How m any bytes  received?
  272                transact ionContext .setDataSo urceBytesR eceived (m ethod.getB ytesReceiv ed ());
  273                
  274                             // How  long did  it take to  start get ting a res ponse comi ng back?
  275                             Long t imeSent =  method.get TimeReques tSent ();
  276                             Long t imeReceive d = method .getTimeFi rstByteRec eived ();
  277                             if (ti meSent !=  null && ti meReceived  != null)
  278                             {
  279                                lon g timeTook  = timeRec eived.long Value () -  timeSent. longValue  ();
  280                                tra nsactionCo ntext.setT imeToFirst Byte (new  Long (time Took));
  281                             }
  282                             
  283                             // Loo ks like it  wasn't fo und in cac he - is th ere a plac e to set t his to tru e if it wa s?
  284                transact ionContext .setItemCa ched (Bool ean.FALSE) ;
  285                             
  286                // extra ct the bas ic HTTP he ader field s for cont ent type,  location a nd length
  287                String c ontentType  = 
  288                    getH eader(meth od, HTTPCo nstants.HE ADER_CONTE NT_TYPE);
  289                String c ontentLoca tion = 
  290                    getH eader(meth od, HTTPCo nstants.HE ADER_CONTE NT_LOCATIO N);
  291                String c ontentLeng th = 
  292                    getH eader(meth od, HTTPCo nstants.HE ADER_CONTE NT_LENGTH) ;
  293  
  294                if ((ret urnCode >  199) && (r eturnCode  < 300)) 
  295                {
  296                    
  297                    // S OAP return  is OK - s o fall thr ough
  298                } 
  299                else if  (msgContex t.getSOAPC onstants()  == SOAPCo nstants.SO AP12_CONST ANTS) 
  300                {
  301                    // F or now, if  we're SOA P 1.2, fal l through,  since the  range of
  302                    // v alid resul t codes is  much grea ter
  303                } 
  304                else if  ((contentT ype != nul l) && !con tentType.e quals("tex t/html")
  305                            && ((re turnCode >  499) && ( returnCode  < 600)))  {
  306                    
  307                    // S OAP Fault  should be  in here -  so fall th rough
  308                } else {
  309                    Stri ng statusM essage = m ethod.getS tatusText( );
  310                    try{ log.warn(" Method ["  + method.g etPath() +  "] on tar get [" + h ostConfigu ration.get HostURL()  +"] failed  - '" + st atusMessag e + "'."); }
  311                    catc h(IllegalS tateExcept ion isX){}
  312                    
  313                    Axis Fault faul t = new Ax isFault("H TTP",
  314                                                       "( " + return Code + ")"
  315                                                       +  statusMess age, null,
  316                                                       nu ll);
  317                    
  318                    try  {
  319                         fault.setF aultDetail String(
  320                              Messa ges.getMes sage("retu rn01",
  321                                                    "" +  returnCode ,
  322                                                    metho d.getRespo nseBodyAsS tring()));
  323                         fault.addF aultDetail (Constants .QNAME_FAU LTDETAIL_H TTPERRORCO DE,
  324                                                Integer.t oString(re turnCode)) ;
  325                         throw faul t;
  326                    } fi nally {
  327                         method.rel easeConnec tion(); //  release c onnection  back to
  328                                                                                                            // p ool.
  329                    }
  330                }
  331                
  332                // wrap  the respon se body st ream so th at close()  also rele ases
  333                // the c onnection  back to th e pool.
  334                InputStr eam releas eConnectio nOnCloseSt ream = 
  335                    crea teConnecti onReleasin gInputStre am(method) ;
  336  
  337                Header c ontentEnco ding = 
  338                    meth od.getResp onseHeader (HTTPConst ants.HEADE R_CONTENT_ ENCODING);
  339                log.info ("HTTPComm onsSender  - " + HTTP Constants. HEADER_CON TENT_ENCOD ING + "=" 
  340                             (conte ntEncoding  == null ?  "null" :  contentEnc oding.getV alue()) );
  341                
  342                if (cont entEncodin g != null)  {
  343                    if(  HTTPConsta nts.COMPRE SSION_GZIP .equalsIgn oreCase(co ntentEncod ing.getVal ue()) ) 
  344                    {
  345                             releas eConnectio nOnCloseSt ream = 
  346                                      new GZIP InputStrea m(releaseC onnectionO nCloseStre am);
  347                             
  348                         log.debug( "HTTPCommo nsSender -  receiving  gzipped s tream.");
  349                    } 
  350                    else  if( ENCOD ING_DEFLAT E.equalsIg noreCase(c ontentEnco ding.getVa lue()) ) 
  351                    {
  352                             releas eConnectio nOnCloseSt ream = 
  353                                      new java .util.zip. InflaterIn putStream( releaseCon nectionOnC loseStream );
  354                             
  355                         log.debug( "HTTPCommo nsSender -  receiving  'deflated ' stream." );
  356                    } 
  357                    else  
  358                    {
  359                         AxisFault  fault = ne w AxisFaul t("HTTP",
  360                                 "u nsupported  content-e ncoding of  '" 
  361                                      + conten tEncoding. getValue()
  362                                 +  "' found",  null, nul l);
  363                         log.warn(f ault.getMe ssage());
  364                         throw faul t;
  365                    }
  366                             
  367                }
  368                try{log. warn("Meth od [" + me thod.getPa th() + "]  on target  [" + hostC onfigurati on.getHost URL() + "]  succeeded , parsing  response." );}
  369                catch(Il legalState Exception  isX){}
  370                
  371                Message  outMsg = n ew Message (releaseCo nnectionOn CloseStrea m,
  372                                                false, co ntentType,  contentLo cation);
  373                // Trans fer HTTP h eaders of  HTTP messa ge to MIME  headers o f SOAP
  374                             // mes sage
  375                Header[]  responseH eaders = m ethod.getR esponseHea ders();
  376                MimeHead ers respon seMimeHead ers = outM sg.getMime Headers();
  377                for (int  i = 0; i  < response Headers.le ngth; i++)  {
  378                    Head er respons eHeader =  responseHe aders[i];
  379                    resp onseMimeHe aders.addH eader(resp onseHeader .getName()
  380                                                     resp onseHeader .getValue( ));
  381                }
  382                outMsg.s etMessageT ype(Messag e.RESPONSE );
  383                msgConte xt.setResp onseMessag e(outMsg);
  384                if (log. isTraceEna bled()) 
  385                {
  386                    if ( null == co ntentLengt h)
  387                         log.trace( "\n" + Mes sages.getM essage("no 00", "Cont ent-Length "));
  388                    log. trace("\n"  + Message s.getMessa ge("xmlRec d00"));
  389                    log. trace("--- ---------- ---------- ---------- ---------- ----");
  390                    log. trace(outM sg.getSOAP PartAsStri ng());
  391                }
  392                
  393                // if we  are maint aining ses sion state ,
  394                // handl e cookies  (if any)
  395                if (msgC ontext.get MaintainSe ssion()) {
  396                    Head er[] heade rs = metho d.getRespo nseHeaders ();
  397  
  398                    for  (int i = 0 ; i < head ers.length ; i++) {
  399                         if (header s[i].getNa me().equal sIgnoreCas e(HTTPCons tants.HEAD ER_SET_COO KIE)) {
  400                             handle Cookie(HTT PConstants .HEADER_CO OKIE, head ers[i].get Value(), m sgContext) ;
  401                         } else if  (headers[i ].getName( ).equalsIg noreCase(H TTPConstan ts.HEADER_ SET_COOKIE 2)) {
  402                             handle Cookie(HTT PConstants .HEADER_CO OKIE2, hea ders[i].ge tValue(),  msgContext );
  403                         }
  404                    }
  405                }
  406  
  407                // alway s release  the connec tion back  to the poo l if
  408                // it wa s one way  invocation
  409                if (msgC ontext.isP ropertyTru e("axis.on e.way")) {
  410                    meth od.release Connection ();
  411                }
  412                
  413           }  catch (Exc eption e)  {
  414                log.debu g(e);
  415                throw Ax isFault.ma keFault(e) ;
  416           }
  417           
  418           if  (log.isDe bugEnabled ()) {
  419                log.debu g(Messages .getMessag e("exit00" ,
  420                                                 "Commons HTTPSender ::invoke") );
  421           }
  422       }
  423       
  424       // All  propertie s that sta rt with an  applicati on specifi c String a re copied  to the
  425       // tra nsport (HT TP) header .
  426       public  final sta tic String  defaultAp plicationT ransportHe aderPrefix  = "xxx-";
  427  
  428       privat e String a pplication TransportH eaderPrefi x = defaul tApplicati onTranspor tHeaderPre fix;
  429       public  String ge tApplicati onTranspor tHeaderPre fix()
  430           {
  431                    retu rn this.ap plicationT ransportHe aderPrefix ;
  432           }
  433  
  434           pu blic void  setApplica tionTransp ortHeaderP refix(
  435                             String  applicati onTranspor tHeaderPre fix)
  436           {
  437                    this .applicati onTranspor tHeaderPre fix = appl icationTra nsportHead erPrefix;
  438           }
  439  
  440       
  441       /**
  442        * Fin d all of t he String  properties  in the me ssage cont ext that s tart with  the value  in applica tionTransp ortHeaderP refix
  443        * The se are the  applicati on specifi c headers  that the t ransport s hould put  in some ou t-of-band  comm chann el.
  444        * In  particular , this cla ss puts th em in HTTP  headers.   
  445        * 
  446        * @pa ram msgCon text
  447        * @re turn a Map  of proper ty names a nd values  or null if  there are  no proper ties of in terest
  448        */
  449       protec ted Map<St ring, Stri ng> getPro pertiesOfI nterest(Me ssageConte xt msgCont ext)
  450       {
  451           Ma p<String,  String> pr opertiesOf Interest =  new HashM ap<String,  String>() ;
  452           St ring prefi x = getApp licationTr ansportHea derPrefix( );           // the p refix that  defines w hat an "in teresting"  property  is
  453           It erator pro pertyNameI ter = msgC ontext.get PropertyNa mes();
  454           wh ile(proper tyNameIter .hasNext() )
  455           {
  456                    try
  457                             {
  458                                      String p ropertyNam e = (Strin g)property NameIter.n ext();
  459                                      if(prope rtyName.st artsWith(p refix))
  460                                      {
  461                                               String pro pertyValue  = (String )msgContex t.getPrope rty(proper tyName);
  462                                               properties OfInterest .put(prope rtyName, p ropertyVal ue);
  463                                      }
  464                             } 
  465                    catc h (ClassCa stExceptio n ccX)
  466                             {
  467                             // eat  the excep tion, it m eans that  there is a  non-Strin g property
  468                             // whi ch we are,  by defini tion, not  interested  in.
  469                             }
  470           }
  471           
  472           //  return nu ll if ther e are no i nteresting  propertie s
  473           re turn prope rtiesOfInt erest.size () > 0 ? p ropertiesO fInterest  : null;
  474       }
  475  
  476           /* *
  477            *  little he lper funct ion for co okies. fil ls up the  message co ntext with  a
  478            *  string or  an array  of strings  (if there  are more  than one S et-Cookie)
  479            *  
  480            *  @param co okieName
  481            *  @param se tCookieNam e
  482            *  @param co okie
  483            *  @param ms gContext
  484            * /
  485       public  void hand leCookie(S tring cook ieName, St ring cooki e,
  486                MessageC ontext msg Context) {
  487           
  488           co okie = cle anupCookie (cookie);
  489           in t keyIndex  = cookie. indexOf("= ");
  490           St ring key =  (keyIndex  != -1) ?  cookie.sub string(0,  keyIndex)  : cookie;
  491           
  492           Ar rayList co okies = ne w ArrayLis t();
  493           Ob ject oldCo okies = ms gContext.g etProperty (cookieNam e);
  494           bo olean alre adyExist =  false;
  495           if (oldCookie s != null)  {
  496                if(oldCo okies inst anceof Str ing[]) {
  497                    Stri ng[] oldCo okiesArray  = (String [])oldCook ies;
  498                    for( int i = 0;  i < oldCo okiesArray .length; i ++) {
  499                         String anO ldCookie =  oldCookie sArray[i];
  500                         if (key !=  null && a nOldCookie .indexOf(k ey) == 0)  { // same
  501                                                                                                                                                                 // coo kie
  502                                                                                                                                                                 // key
  503                             anOldC ookie = co okie;              //  update to  new one
  504                             alread yExist = t rue;
  505                         }
  506                         cookies.ad d(anOldCoo kie);
  507                    }
  508                } else {
  509                                      String o ldCookie =  (String)o ldCookies;
  510                    if ( key != nul l && oldCo okie.index Of(key) ==  0) { // s ame
  511                                                                                                                                                        // c ookie
  512                                                                                                                                                        // k ey
  513                                               oldCookie  = cookie;               // updat e to new o ne
  514                         alreadyExi st = true;
  515                    }
  516                    cook ies.add(ol dCookie);
  517                }
  518           }
  519           
  520           if  (!already Exist) {
  521                cookies. add(cookie );
  522           }
  523           
  524           if (cookies.s ize()==1)  {
  525                msgConte xt.setProp erty(cooki eName, coo kies.get(0 ));
  526           }  else if (c ookies.siz e() > 1) {
  527                msgConte xt.setProp erty(cooki eName, coo kies.toArr ay(new Str ing[cookie s.size()]) );
  528           }
  529       }
  530       
  531       /**
  532            *  Add cooki es from me ssage cont ext
  533            *  
  534            *  @param ms gContext
  535            *  @param st ate
  536            *  @param he ader
  537            *  @param ho st
  538            *  @param pa th
  539            *  @param se cure
  540            * /
  541       privat e void fil lHeaders(M essageCont ext msgCon text, Http State stat e, String  header, St ring host,  String pa th, boolea n secure)  {
  542           Ob ject ck1 =  msgContex t.getPrope rty(header );
  543           if  (ck1 != n ull) {
  544                if (ck1  instanceof  String[])  {
  545                    Stri ng [] cook ies = (Str ing[]) ck1 ;
  546                    for  (int i = 0 ; i < cook ies.length ; i++) {
  547                         addCookie( state, coo kies[i], h ost, path,  secure);
  548                    }
  549                } else {
  550                    addC ookie(stat e, (String ) ck1, hos t, path, s ecure);
  551                }
  552           }
  553       }
  554  
  555       /**
  556            *  add cooki e to state
  557            *  
  558            *  @param st ate
  559            *  @param co okie
  560            * /
  561       privat e void add Cookie(Htt pState sta te, String  cookie,St ring host,  String pa th, boolea n secure)  {
  562           in t index =  cookie.ind exOf('=');
  563           st ate.addCoo kie(new Co okie(host,  cookie.su bstring(0,  index),
  564                    cook ie.substri ng(index +  1), path,
  565                    null , secure)) ;
  566       }
  567  
  568       /**
  569            *  cleanup t he cookie  value.
  570            *  
  571            *  @param co okie
  572            *              initial  cookie val ue
  573            *  
  574            *  @return a  cleaned u p cookie v alue.
  575            * /
  576       privat e String c leanupCook ie(String  cookie) {
  577           co okie = coo kie.trim() ;
  578           //  chop afte r first ;  a la Apach e SOAP (se e HTTPUtil s.java the re)
  579           in t index =  cookie.ind exOf(';');
  580           if  (index !=  -1) {
  581                cookie =  cookie.su bstring(0,  index);
  582           }
  583           re turn cooki e;
  584       }
  585       
  586       protec ted HostCo nfiguratio n getHostC onfigurati on(HttpCli ent client
  587                                                             Message Context co ntext,
  588                                                             URL tar getURL) {
  589           Tr ansportCli entPropert ies tcp = 
  590                Transpor tClientPro pertiesFac tory.creat e(targetUR L.getProto col()); //  http
  591                                                                                                                                                                                   // or
  592                                                                                                                                                                                   // https
  593           in t port = t argetURL.g etPort();
  594           bo olean host InNonProxy List =
  595                isHostIn NonProxyLi st(targetU RL.getHost (), tcp.ge tNonProxyH osts());
  596           
  597           Ho stConfigur ation conf ig = new H ostConfigu ration();
  598           
  599           if  (port ==  -1) {
  600                    if(t argetURL.g etProtocol ().equalsI gnoreCase( "https"))  {
  601                               port =  PORT ;              // default  port for  https bein PORT
  602                    } el se { // it  must be h ttp
  603                             port =  80;               //  default p ort for ht tp being 8 0
  604                    }
  605           }
  606           
  607           if (hostInNon ProxyList) {
  608                config.s etHost(tar getURL.get Host(), po rt, target URL.getPro tocol());
  609           }  else {
  610                if (tcp. getProxyHo st().lengt h() == 0 | |
  611                    tcp. getProxyPo rt().lengt h() == 0)  {
  612                    conf ig.setHost (targetURL .getHost() , port, ta rgetURL.ge tProtocol( ));
  613                } else {
  614                    if ( tcp.getPro xyUser().l ength() !=  0) {
  615                         Credential s proxyCre d = 
  616                             new Us ernamePass wordCreden tials(tcp. getProxyUs er(),
  617                                                                tcp. getProxyPa ssword());
  618                         // if the  username i s in the f orm "user\ domain"
  619                         // then us e NTCreden tials inst ead.
  620                         int domain Index = tc p.getProxy User().ind exOf("\\") ;
  621                         if (domain Index > 0)  {
  622                             String  domain =  tcp.getPro xyUser().s ubstring(0 , domainIn dex);
  623                             if (tc p.getProxy User().len gth() > do mainIndex  + 1) {
  624                                 St ring user  = tcp.getP roxyUser() .substring (domainInd ex + 1);
  625                                 pr oxyCred =  new NTCred entials(us er,
  626                                                   tcp.ge tProxyPass word(),
  627                                                   tcp.ge tProxyHost (), domain );
  628                             }
  629                         }
  630                         client.get State().se tProxyCred entials(Au thScope.AN Y, proxyCr ed);
  631                    }
  632                    int  proxyPort  = new Inte ger(tcp.ge tProxyPort ()).intVal ue();
  633                    conf ig.setProx y(tcp.getP roxyHost() , proxyPor t);
  634                }
  635           }
  636           re turn confi g;
  637       }
  638       
  639       /**
  640            *  Extracts  info from  message co ntext.
  641            *  
  642            *  @param me thod
  643            *              Post met hod
  644            *  @param ht tpClient
  645            *              The clie nt used fo r posting
  646            *  @param ms gContext
  647            *              the mess age contex t
  648            *  @param tm pURL
  649            *              the url  to post to .
  650            *  
  651            *  @throws E xception
  652            * /
  653       privat e void add ContextInf o(HttpMeth odBase met hod, 
  654                                      HttpClie nt httpCli ent, 
  655                                      MessageC ontext msg Context, 
  656                                      URL tmpU RL)
  657           th rows Excep tion {
  658           
  659           //  optionall y set a ti meout for  the reques t
  660           if  (msgConte xt.getTime out() != 0 ) {
  661                /*
  662                              * ISS UE: these  are not th e same, bu t MessageC ontext has  only one
  663                              * def inition of  timeout
  664                              */
  665                // SO_TI MEOUT -- t imeout for  blocking  reads
  666                httpClie nt.getHttp Connection Manager(). getParams( ).setSoTim eout(msgCo ntext.getT imeout());
  667                // timeo ut for ini tial conne ction
  668                httpClie nt.getHttp Connection Manager(). getParams( ).setConne ctionTimeo ut(msgCont ext.getTim eout());
  669           }
  670           
  671           //  Get SOAPA ction, def ault to ""
  672           St ring actio n = msgCon text.useSO APAction()
  673                ? msgCon text.getSO APActionUR I()
  674                : "";
  675           
  676           if  (action = = null) {
  677                action =  "";
  678           }
  679  
  680           Me ssage msg  = msgConte xt.getRequ estMessage ();
  681           if  (msg != n ull){
  682                method.s etRequestH eader(new  Header(HTT PConstants .HEADER_CO NTENT_TYPE ,
  683                                                      msg .getConten tType(msgC ontext.get SOAPConsta nts())));
  684           }
  685           me thod.setRe questHeade r(new Head er(HTTPCon stants.HEA DER_SOAP_A CTION, 
  686                                         "\""  + action +  "\""));
  687           me thod.setRe questHeade r(new Head er(HTTPCon stants.HEA DER_USER_A GENT, Mess ages.getMe ssage("axi sUserAgent ")));
  688           // method.set RequestHea der(
  689           //       new  Header(HTT PConstants .HEADER_US ER_AGENT,  "Mozilla/4 .0 (compat ible; MSIE  6.0; MS W eb Service s Client P rotocol 2. 0.5072)")
  690           // );
  691  
  692           St ring userI D = msgCon text.getUs ername();
  693           St ring passw d = msgCon text.getPa ssword();
  694           // System.out .println(" ImageXChan geHttpComm onsSender  setting cr edentials  = '" + use rID + ". "  + passwd  + "'");
  695           
  696           //  if UserID  is not pa rt of the  context, b ut is in t he URL, us e
  697           //  the one i n the URL.
  698           if  ((userID  == null) & & (tmpURL. getUserInf o() != nul l)) {
  699                String i nfo = tmpU RL.getUser Info();
  700                int sep  = info.ind exOf(':');
  701                
  702                if ((sep  >= 0) &&  (sep + 1 <  info.leng th())) {
  703                    user ID = info. substring( 0, sep);
  704                    pass wd = info. substring( sep + 1);
  705                } else {
  706                    user ID = info;
  707                }
  708           }
  709           if  (userID ! = null) {
  710                Credenti als proxyC red =
  711                    new  UsernamePa sswordCred entials(us erID,
  712                                                       pa sswd);
  713                // if th e username  is in the  form "use r\domain"
  714                // then  use NTCred entials in stead.
  715                int doma inIndex =  userID.ind exOf("\\") ;
  716                if (doma inIndex >  0) {
  717                    Stri ng domain  = userID.s ubstring(0 , domainIn dex);
  718                    if ( userID.len gth() > do mainIndex  + 1) {
  719                         String use r = userID .substring (domainInd ex + 1);
  720                         proxyCred  = new NTCr edentials( user,
  721                                          pass wd,
  722                                          Netw orkUtils.g etLocalHos tname(), d omain);
  723                    }
  724                }
  725                httpClie nt.getStat e().setCre dentials(A uthScope.A NY, proxyC red);
  726                //System .out.print ln("ImageX ChangeHttp CommonsSen der settin g credenti als = '" +  userID +  ". " + pas swd + "'") ;
  727           }
  728           
  729           //  add compr ession hea ders if ne eded
  730           //  if we acc ept GZIP t hen add th e accept-e ncoding he ader
  731           if  (msgConte xt.isPrope rtyTrue(HT TPConstant s.MC_ACCEP T_GZIP)) 
  732           {
  733                    // a ccept both  gzip and  deflate if  the gzip  property i s set
  734                    meth od.addRequ estHeader( HTTPConsta nts.HEADER _ACCEPT_EN CODING, HT TPConstant s.COMPRESS ION_GZIP +  "," + COM PRESSION_D EFLATE);
  735                    //me thod.addRe questHeade r(HTTPCons tants.HEAD ER_ACCEPT_ ENCODING,  COMPRESSIO N_DEFLATE) ;
  736           }
  737           
  738           //  if we wil l gzip the  request t hen add th e content- encoding h eader
  739           if  (msgConte xt.isPrope rtyTrue(HT TPConstant s.MC_GZIP_ REQUEST))  {
  740                    meth od.addRequ estHeader( HTTPConsta nts.HEADER _CONTENT_E NCODING, 
  741                                      HTTPCons tants.COMP RESSION_GZ IP);
  742           }
  743           
  744           //  Transfer  MIME heade rs of SOAP Message to  HTTP head ers.
  745           Mi meHeaders  mimeHeader s = msg.ge tMimeHeade rs();
  746           if  (mimeHead ers != nul l) {
  747                for (Ite rator i =  mimeHeader s.getAllHe aders(); i .hasNext() ; ) {
  748                    Mime Header mim eHeader =  (MimeHeade r) i.next( );
  749                    // H EADER_CONT ENT_TYPE a nd HEADER_ SOAP_ACTIO N are alre ady set.
  750                    // L et's not d uplicate t hem.
  751                    Stri ng headerN ame = mime Header.get Name();
  752                    if ( headerName .equals(HT TPConstant s.HEADER_C ONTENT_TYP E) || head erName.equ als(HTTPCo nstants.HE ADER_SOAP_ ACTION)) 
  753                             contin ue;
  754                    meth od.addRequ estHeader( mimeHeader .getName()
  755                                               mimeHeader .getValue( ));
  756                }
  757           }
  758  
  759           //  process u ser define d headers  for inform ation.
  760           Ha shtable us erHeaderTa ble = (Has htable) ms gContext.g etProperty (HTTPConst ants.REQUE ST_HEADERS );
  761           
  762           if  (userHead erTable !=  null) {
  763                for (Ite rator e =  userHeader Table.entr ySet().ite rator();
  764                     e.h asNext();)  {
  765                    Map. Entry me =  (Map.Entr y) e.next( );
  766                    Obje ct keyObj  = me.getKe y();
  767                    
  768                    if ( null == ke yObj) {
  769                         continue;
  770                    }
  771                    Stri ng key = k eyObj.toSt ring().tri m();
  772                    Stri ng value =  me.getVal ue().toStr ing().trim ();
  773                    
  774                    if ( key.equals IgnoreCase (HTTPConst ants.HEADE R_EXPECT)  &&
  775                         value.equa lsIgnoreCa se(HTTPCon stants.HEA DER_EXPECT _100_Conti nue)) {
  776                         method.get Params().s etBooleanP arameter(H ttpMethodP arams.USE_ EXPECT_CON TINUE,
  777                                                                   t rue);
  778                    } el se if (key .equalsIgn oreCase(HT TPConstant s.HEADER_T RANSFER_EN CODING_CHU NKED)) {
  779                         String val  = me.getV alue().toS tring();
  780                         if (null ! = val)  {
  781                             httpCh unkStream  = JavaUtil s.isTrue(v al);
  782                         }
  783                    } el se {
  784                         method.add RequestHea der(key, v alue);
  785                    }
  786                }
  787           }
  788       }
  789       
  790       /**
  791            *  Check if  the specif ied host i s in the l ist of non  proxy hos ts.
  792            *  
  793            *  @param ho st
  794            *              host nam e
  795            *  @param no nProxyHost s
  796            *              string c ontaining  the list o f non prox y hosts
  797            *  
  798            *  @return t rue/false
  799            * /
  800       protec ted boolea n isHostIn NonProxyLi st(String  host, Stri ng nonProx yHosts) {
  801           
  802           if  ((nonProx yHosts ==  null) || ( host == nu ll)) {
  803                return f alse;
  804           }
  805           
  806           /*
  807                     * T he http.no nProxyHost s system p roperty is  a list en closed in  double
  808                     * q uotes with  items sep arated by  a vertical  bar.
  809                     */
  810           St ringTokeni zer tokeni zer = new  StringToke nizer(nonP roxyHosts,  "|\"");
  811           
  812           wh ile (token izer.hasMo reTokens() ) {
  813                String p attern = t okenizer.n extToken() ;
  814                
  815                if (log. isDebugEna bled()) {
  816                    log. debug(Mess ages.getMe ssage("mat ch00",
  817                    new  String[]{" HTTPSender ",
  818                    host ,
  819                    patt ern}));
  820                }
  821                if (matc h(pattern,  host, fal se)) {
  822                    retu rn true;
  823                }
  824           }
  825           re turn false ;
  826       }
  827       
  828       /**
  829            *  Matches a  string ag ainst a pa ttern. The  pattern c ontains tw o special
  830            *  character s: '*' whi ch means z ero or mor e characte rs,
  831            *  
  832            *  @param pa ttern
  833            *              the (non -null) pat tern to ma tch agains t
  834            *  @param st r
  835            *              the (non -null) str ing that m ust be mat ched again st the pat tern
  836            *  @param is CaseSensit ive
  837            *  
  838            *  @return < code>true< /code> whe n the stri ng matches  against t he pattern ,
  839            *          < code>false </code> ot herwise.
  840            * /
  841       protec ted static  boolean m atch(Strin g pattern,  String st r,
  842                                         boole an isCaseS ensitive)  {
  843           
  844           ch ar[] patAr r = patter n.toCharAr ray();
  845           ch ar[] strAr r = str.to CharArray( );
  846           in t patIdxSt art = 0;
  847           in t patIdxEn d = patArr .length -  1;
  848           in t strIdxSt art = 0;
  849           in t strIdxEn d = strArr .length -  1;
  850           ch ar ch;
  851           bo olean cont ainsStar =  false;
  852           
  853           fo r (int i =  0; i < pa tArr.lengt h; i++) {
  854                if (patA rr[i] == ' *') {
  855                    cont ainsStar =  true;
  856                    brea k;
  857                }
  858           }
  859           if  (!contain sStar) {
  860                
  861                // No '* 's, so we  make a sho rtcut
  862                if (patI dxEnd != s trIdxEnd)  {
  863                    retu rn false;         //  Pattern an d string d o not have  the
  864                                                                                           // same si ze
  865                }
  866                for (int  i = 0; i  <= patIdxE nd; i++) {
  867                    ch =  patArr[i] ;
  868                    if ( isCaseSens itive && ( ch != strA rr[i])) {
  869                         return fal se;    //  Character  mismatch
  870                    }
  871                    if ( !isCaseSen sitive
  872                    && ( Character. toUpperCas e(ch)
  873                    != C haracter.t oUpperCase (strArr[i] ))) {
  874                         return fal se;    //  Character  mismatch
  875                    }
  876                }
  877                return t rue;              //  String mat ches again st pattern
  878           }
  879           if  (patIdxEn d == 0) {
  880                return t rue;    //  Pattern c ontains on ly '*', wh ich matche s anything
  881           }
  882           
  883           //  Process c haracters  before fir st star
  884           wh ile ((ch =  patArr[pa tIdxStart] ) != '*'
  885           &&  (strIdxSt art <= str IdxEnd)) {
  886                if (isCa seSensitiv e && (ch ! = strArr[s trIdxStart ])) {
  887                    retu rn false;     // Char acter mism atch
  888                }
  889                if (!isC aseSensiti ve
  890                && (Char acter.toUp perCase(ch )
  891                != Chara cter.toUpp erCase(str Arr[strIdx Start])))  {
  892                    retu rn false;     // Char acter mism atch
  893                }
  894                patIdxSt art++;
  895                strIdxSt art++;
  896           }
  897           if  (strIdxSt art > strI dxEnd) {
  898                
  899                // All c haracters  in the str ing are us ed. Check  if only '* 's are
  900                // left  in the pat tern. If s o, we succ eeded. Oth erwise fai lure.
  901                for (int  i = patId xStart; i  <= patIdxE nd; i++) {
  902                    if ( patArr[i]  != '*') {
  903                         return fal se;
  904                    }
  905                }
  906                return t rue;
  907           }
  908           
  909           //  Process c haracters  after last  star
  910           wh ile ((ch =  patArr[pa tIdxEnd])  != '*' &&  (strIdxSta rt <= strI dxEnd)) {
  911                if (isCa seSensitiv e && (ch ! = strArr[s trIdxEnd]) ) {
  912                    retu rn false;     // Char acter mism atch
  913                }
  914                if (!isC aseSensiti ve
  915                && (Char acter.toUp perCase(ch )
  916                != Chara cter.toUpp erCase(str Arr[strIdx End]))) {
  917                    retu rn false;     // Char acter mism atch
  918                }
  919                patIdxEn d--;
  920                strIdxEn d--;
  921           }
  922           if  (strIdxSt art > strI dxEnd) {
  923                
  924                // All c haracters  in the str ing are us ed. Check  if only '* 's are
  925                // left  in the pat tern. If s o, we succ eeded. Oth erwise fai lure.
  926                for (int  i = patId xStart; i  <= patIdxE nd; i++) {
  927                    if ( patArr[i]  != '*') {
  928                         return fal se;
  929                    }
  930                }
  931                return t rue;
  932           }
  933           
  934           //  process p attern bet ween stars . padIdxSt art and pa tIdxEnd po int
  935           //  always to  a '*'.
  936           wh ile ((patI dxStart !=  patIdxEnd ) && (strI dxStart <=  strIdxEnd )) {
  937                int patI dxTmp = -1 ;
  938                
  939                for (int  i = patId xStart + 1 ; i <= pat IdxEnd; i+ +) {
  940                    if ( patArr[i]  == '*') {
  941                         patIdxTmp  = i;
  942                         break;
  943                    }
  944                }
  945                if (patI dxTmp == p atIdxStart  + 1) {
  946                    
  947                    // T wo stars n ext to eac h other, s kip the fi rst one.
  948                    patI dxStart++;
  949                    cont inue;
  950                }
  951                
  952                // Find  the patter n between  padIdxStar t & padIdx Tmp in str  between
  953                // strId xStart & s trIdxEnd
  954                int patL ength = (p atIdxTmp -  patIdxSta rt - 1);
  955                int strL ength = (s trIdxEnd -  strIdxSta rt + 1);
  956                int foun dIdx = -1;
  957                
  958                strLoop:
  959                    for  (int i = 0 ; i <= str Length - p atLength;  i++) {
  960                         for (int j  = 0; j <  patLength;  j++) {
  961                             ch = p atArr[patI dxStart +  j + 1];
  962                             if (is CaseSensit ive
  963                             && (ch  != strArr [strIdxSta rt + i + j ])) {
  964                                 co ntinue str Loop;
  965                             }
  966                             if (!i sCaseSensi tive && (C haracter
  967                             .toUpp erCase(ch)  != Charac ter
  968                             .toUpp erCase(str Arr[strIdx Start + i  + j]))) {
  969                                 co ntinue str Loop;
  970                             }
  971                         }
  972                         foundIdx =  strIdxSta rt + i;
  973                         break;
  974                    }
  975                    if ( foundIdx = = -1) {
  976                         return fal se;
  977                    }
  978                    patI dxStart =  patIdxTmp;
  979                    strI dxStart =  foundIdx +  patLength ;
  980           }
  981           
  982           //  All chara cters in t he string  are used.  Check if o nly '*'s a re left
  983           //  in the pa ttern. If  so, we suc ceeded. Ot herwise fa ilure.
  984           fo r (int i =  patIdxSta rt; i <= p atIdxEnd;  i++) {
  985                if (patA rr[i] != ' *') {
  986                    retu rn false;
  987                }
  988           }
  989           re turn true;
  990       }
  991  
  992       privat e static S tring getH eader(Http MethodBase  method, S tring head erName) {
  993           He ader heade r = method .getRespon seHeader(h eaderName) ;
  994           re turn (head er == null ) ? null :  header.ge tValue().t rim();
  995       }
  996  
  997       privat e InputStr eam create Connection ReleasingI nputStream (final Htt pMethodBas e method)  throws IOE xception {
  998           re turn new F ilterInput Stream(met hod.getRes ponseBodyA sStream())  {
  999                    publ ic void cl ose() thro ws IOExcep tion {
  1000                         try {
  1001                             super. close();
  1002                         } finally  {
  1003                             method .releaseCo nnection() ;
  1004                         }
  1005                    }
  1006                };
  1007       }
  1008  
  1009       privat e static c lass Messa geRequestE ntity impl ements Req uestEntity  {
  1010           
  1011           pr ivate Http MethodBase  method;
  1012           pr ivate Mess age messag e;
  1013           bo olean http ChunkStrea m = true;  // Use HTT P chunking  or not.
  1014  
  1015           pu blic Messa geRequestE ntity(Http MethodBase  method, M essage mes sage) {
  1016                this.mes sage = mes sage;
  1017                this.met hod = meth od;
  1018           }
  1019  
  1020           pu blic Messa geRequestE ntity(Http MethodBase  method, M essage mes sage, bool ean httpCh unkStream)  {
  1021                this.mes sage = mes sage;
  1022                this.met hod = meth od;
  1023                this.htt pChunkStre am = httpC hunkStream ;
  1024           }
  1025  
  1026           pu blic boole an isRepea table() {
  1027                return t rue;
  1028           }
  1029  
  1030           pu blic void  writeReque st(OutputS tream out)  throws IO Exception  {
  1031                try {
  1032                    this .message.w riteTo(out );
  1033                } catch  (SOAPExcep tion e) {
  1034                    thro w new IOEx ception(e. getMessage ());
  1035                }
  1036           }
  1037  
  1038           pr otected bo olean isCo ntentLengt hNeeded()  {
  1039                    retu rn this.me thod.getPa rams().get Version()  == HttpVer sion.HTTP_ 1_0 || !ht tpChunkStr eam;
  1040           }
  1041           
  1042           pu blic long  getContent Length() {
  1043                if (isCo ntentLengt hNeeded())  {
  1044                    try  {
  1045                         return mes sage.getCo ntentLengt h();
  1046                    } ca tch (Excep tion e) {
  1047                    }
  1048                } 
  1049                return - 1; /* -1 f or chunked  */
  1050           }
  1051  
  1052           pu blic Strin g getConte ntType() {
  1053                return n ull; // a  separate h eader is a dded
  1054           }
  1055           
  1056       }
  1057       
  1058       privat e static c lass GzipM essageRequ estEntity  extends Me ssageReque stEntity {
  1059  
  1060           pu blic GzipM essageRequ estEntity( HttpMethod Base metho d, Message  message)  {
  1061                    supe r(method,  message);
  1062           }
  1063  
  1064           pu blic GzipM essageRequ estEntity( HttpMethod Base metho d, Message  message,  boolean ht tpChunkStr eam) {
  1065                    supe r(method,  message, h ttpChunkSt ream);
  1066           }
  1067           
  1068           pu blic void  writeReque st(OutputS tream out)  throws IO Exception  {
  1069                    if ( cachedStre am != null ) {
  1070                             cached Stream.wri teTo(out);
  1071                    } el se {
  1072                             GZIPOu tputStream  gzStream  = new GZIP OutputStre am(out);
  1073                             super. writeReque st(gzStrea m);
  1074                             gzStre am.finish( );
  1075                    }
  1076           }
  1077           
  1078           pu blic long  getContent Length() {
  1079                    if(i sContentLe ngthNeeded ()) {
  1080                             ByteAr rayOutputS tream baos  = new Byt eArrayOutp utStream() ;
  1081                             try {
  1082                                      writeReq uest(baos) ;
  1083                                      cachedSt ream = bao s;
  1084                                      return b aos.size() ;
  1085                             } catc h (IOExcep tion e) {
  1086                                      // fall  through to  doing chu nked.
  1087                             }
  1088                    }
  1089                    retu rn -1; //  do chunked
  1090           }
  1091           
  1092           pr ivate Byte ArrayOutpu tStream ca chedStream ;
  1093       }
  1094   }
  1095