Save This Page
Home » axis2-1.5-src » org.apache » axis2 » util » [javadoc | source]
    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one
    3    * or more contributor license agreements. See the NOTICE file
    4    * distributed with this work for additional information
    5    * regarding copyright ownership. The ASF licenses this file
    6    * to you under the Apache License, Version 2.0 (the
    7    * "License"); you may not use this file except in compliance
    8    * with the License. You may obtain a copy of the License at
    9    *
   10    * http://www.apache.org/licenses/LICENSE-2.0
   11    *
   12    * Unless required by applicable law or agreed to in writing,
   13    * software distributed under the License is distributed on an
   14    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   15    * KIND, either express or implied. See the License for the
   16    * specific language governing permissions and limitations
   17    * under the License.
   18    */
   19   
   20   
   21   package org.apache.axis2.util;
   22   
   23   import org.apache.axiom.om.util.UUIDGenerator;
   24   import org.apache.axiom.soap.SOAPBody;
   25   import org.apache.axiom.soap.SOAPEnvelope;
   26   import org.apache.axiom.soap.SOAPFault;
   27   import org.apache.axis2.AxisFault;
   28   import org.apache.axis2.Constants;
   29   import org.apache.axis2.transport.TransportListener;
   30   import org.apache.axis2.context.ConfigurationContext;
   31   import org.apache.axis2.context.ConfigurationContextFactory;
   32   import org.apache.axis2.context.MessageContext;
   33   import org.apache.axis2.context.ServiceContext;
   34   import org.apache.axis2.context.ServiceGroupContext;
   35   import org.apache.axis2.description.AxisModule;
   36   import org.apache.axis2.description.AxisOperation;
   37   import org.apache.axis2.description.AxisService;
   38   import org.apache.axis2.description.Flow;
   39   import org.apache.axis2.description.HandlerDescription;
   40   import org.apache.axis2.description.InOnlyAxisOperation;
   41   import org.apache.axis2.description.InOutAxisOperation;
   42   import org.apache.axis2.description.OutInAxisOperation;
   43   import org.apache.axis2.description.Parameter;
   44   import org.apache.axis2.description.PhaseRule;
   45   import org.apache.axis2.description.WSDL2Constants;
   46   import org.apache.axis2.engine.AxisConfiguration;
   47   import org.apache.axis2.engine.AxisError;
   48   import org.apache.axis2.engine.Handler;
   49   import org.apache.axis2.engine.MessageReceiver;
   50   import org.apache.axis2.i18n.Messages;
   51   import org.apache.axis2.receivers.RawXMLINOutMessageReceiver;
   52   import org.apache.axis2.wsdl.WSDLConstants;
   53   import org.apache.commons.logging.Log;
   54   import org.apache.commons.logging.LogFactory;
   55   
   56   import javax.xml.namespace.QName;
   57   import java.io.File;
   58   import java.security.AccessController;
   59   import java.security.PrivilegedAction;
   60   import java.util.HashMap;
   61   import java.util.Iterator;
   62   import java.util.Enumeration;
   63   import java.net.SocketException;
   64   import java.net.NetworkInterface;
   65   import java.net.InetAddress;
   66   
   67   public class Utils {
   68       private static final Log log = LogFactory.getLog(Utils.class);
   69   
   70       public static void addHandler(Flow flow, Handler handler, String phaseName) {
   71           HandlerDescription handlerDesc = new HandlerDescription(handler.getName());
   72           PhaseRule rule = new PhaseRule(phaseName);
   73   
   74           handlerDesc.setRules(rule);
   75           handler.init(handlerDesc);
   76           handlerDesc.setHandler(handler);
   77           flow.addHandler(handlerDesc);
   78       }
   79   
   80       /**
   81        * @see org.apache.axis2.util.MessageContextBuilder:createOutMessageContext()
   82        * @deprecated (post1.1branch)
   83        */
   84       public static MessageContext createOutMessageContext(MessageContext inMessageContext)
   85               throws AxisFault {
   86           return MessageContextBuilder.createOutMessageContext(inMessageContext);
   87       }
   88   
   89       public static AxisService createSimpleService(QName serviceName, String className, QName opName)
   90               throws AxisFault {
   91           return createSimpleService(serviceName, new RawXMLINOutMessageReceiver(), className,
   92                                      opName);
   93       }
   94   
   95       public static AxisService createSimpleServiceforClient(QName serviceName, String className,
   96                                                              QName opName)
   97               throws AxisFault {
   98           return createSimpleServiceforClient(serviceName, new RawXMLINOutMessageReceiver(),
   99                                               className,
  100                                               opName);
  101       }
  102   
  103   
  104       public static AxisService createSimpleInOnlyService(QName serviceName,
  105                                                           MessageReceiver messageReceiver,
  106                                                           QName opName)
  107               throws AxisFault {
  108           AxisService service = new AxisService(serviceName.getLocalPart());
  109           service.setClassLoader(getContextClassLoader_DoPriv());
  110   
  111           AxisOperation axisOp = new InOnlyAxisOperation(opName);
  112   
  113           axisOp.setMessageReceiver(messageReceiver);
  114           axisOp.setStyle(WSDLConstants.STYLE_RPC);
  115           service.addOperation(axisOp);
  116           service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(),
  117                                        axisOp);
  118   
  119           return service;
  120       }
  121   
  122       private static ClassLoader getContextClassLoader_DoPriv() {
  123           return (ClassLoader) org.apache.axis2.java.security.AccessController.doPrivileged(
  124                   new PrivilegedAction<ClassLoader>() {
  125                       public ClassLoader run() {
  126                           return Thread.currentThread().getContextClassLoader();
  127                       }
  128                   }
  129           );
  130       }
  131   
  132   
  133       public static AxisService createSimpleService(QName serviceName,
  134                                                     MessageReceiver messageReceiver, String className,
  135                                                     QName opName)
  136               throws AxisFault {
  137           AxisService service = new AxisService(serviceName.getLocalPart());
  138   
  139           service.setClassLoader(getContextClassLoader_DoPriv());
  140           service.addParameter(new Parameter(Constants.SERVICE_CLASS, className));
  141   
  142           AxisOperation axisOp = new InOutAxisOperation(opName);
  143   
  144           axisOp.setMessageReceiver(messageReceiver);
  145           axisOp.setStyle(WSDLConstants.STYLE_RPC);
  146           service.addOperation(axisOp);
  147           service.mapActionToOperation(Constants.AXIS2_NAMESPACE_URI + "/" + opName.getLocalPart(),
  148                                        axisOp);
  149   
  150           return service;
  151       }
  152   
  153       public static AxisService createSimpleServiceforClient(QName serviceName,
  154                                                              MessageReceiver messageReceiver,
  155                                                              String className,
  156                                                              QName opName)
  157               throws AxisFault {
  158           AxisService service = new AxisService(serviceName.getLocalPart());
  159   
  160           service.setClassLoader(getContextClassLoader_DoPriv());
  161           service.addParameter(new Parameter(Constants.SERVICE_CLASS, className));
  162   
  163           AxisOperation axisOp = new OutInAxisOperation(opName);
  164   
  165           axisOp.setMessageReceiver(messageReceiver);
  166           axisOp.setStyle(WSDLConstants.STYLE_RPC);
  167           service.addOperation(axisOp);
  168   
  169           return service;
  170       }
  171   
  172       public static ServiceContext fillContextInformation(AxisService axisService,
  173                                                           ConfigurationContext configurationContext)
  174               throws AxisFault {
  175   
  176           // 2. if null, create new opCtxt
  177           // fill the service group context and service context info
  178           return fillServiceContextAndServiceGroupContext(axisService, configurationContext);
  179       }
  180   
  181       private static ServiceContext fillServiceContextAndServiceGroupContext(AxisService axisService,
  182                                                                              ConfigurationContext configurationContext)
  183               throws AxisFault {
  184           String serviceGroupContextId = UUIDGenerator.getUUID();
  185           ServiceGroupContext serviceGroupContext =
  186                   configurationContext.createServiceGroupContext(axisService.getAxisServiceGroup());
  187   
  188           serviceGroupContext.setId(serviceGroupContextId);
  189           configurationContext.addServiceGroupContextIntoSoapSessionTable(serviceGroupContext);
  190           return serviceGroupContext.getServiceContext(axisService);
  191       }
  192   
  193       /**
  194        * Break a full path into pieces
  195        *
  196        * @return an array where element [0] always contains the service, and element 1, if not null, contains
  197        *         the path after the first element. all ? parameters are discarded.
  198        */
  199       public static String[] parseRequestURLForServiceAndOperation(String path, String servicePath) {
  200           if (log.isDebugEnabled()) {
  201               log.debug("parseRequestURLForServiceAndOperation : [" + path + "][" + servicePath + "]");
  202           }
  203           if (path == null) {
  204               return null;
  205           }
  206           String[] values = new String[2];
  207   
  208           // TODO. This is kind of brittle. Any service with the name /services would cause fun.
  209           int index = path.lastIndexOf(servicePath);
  210           String service;
  211   
  212           if (-1 != index) {
  213               int serviceStart = index + servicePath.length();
  214   
  215               if (path.length() > serviceStart + 1) {
  216                   service = path.substring(serviceStart + 1);
  217   
  218                   int queryIndex = service.indexOf('?');
  219   
  220                   if (queryIndex > 0) {
  221                       service = service.substring(0, queryIndex);
  222                   }
  223   
  224                   int operationIndex = service.indexOf('/');
  225   
  226                   if (operationIndex > 0) {
  227                       values[0] = service.substring(0, operationIndex);
  228                       values[1] = service.substring(operationIndex + 1);
  229                       operationIndex = values[1].lastIndexOf('/');
  230                       if (operationIndex > 0) {
  231                           values[1] = values[1].substring(operationIndex + 1);
  232                       }
  233                   } else {
  234                       values[0] = service;
  235                   }
  236               }
  237           } else {
  238               if (log.isDebugEnabled()) {
  239                   log.debug("Unable to parse request URL [" + path + "][" + servicePath + "]");
  240               }
  241           }
  242   
  243           return values;
  244       }
  245   
  246       public static ConfigurationContext getNewConfigurationContext(String repositry)
  247               throws Exception {
  248           final File file = new File(repositry);
  249           boolean exists = exists(file);
  250           if (!exists) {
  251               throw new Exception("repository directory " + file.getAbsolutePath()
  252                                   + " does not exists");
  253           }
  254           File axis2xml = new File(file, "axis.xml");
  255           String axis2xmlString = null;
  256           if (exists(axis2xml)) {
  257               axis2xmlString = axis2xml.getName();
  258           }
  259           String path = (String) org.apache.axis2.java.security.AccessController.doPrivileged(
  260                   new PrivilegedAction<String>() {
  261                       public String run() {
  262                           return file.getAbsolutePath();
  263                       }
  264                   }
  265           );
  266           return ConfigurationContextFactory
  267                   .createConfigurationContextFromFileSystem(path, axis2xmlString);
  268       }
  269   
  270       private static boolean exists(final File file) {
  271           Boolean exists = (Boolean) org.apache.axis2.java.security.AccessController.doPrivileged(
  272                   new PrivilegedAction<Boolean>() {
  273                       public Boolean run() {
  274                           return new Boolean(file.exists());
  275                       }
  276                   }
  277           );
  278           return exists.booleanValue();
  279       }
  280   
  281       public static String getParameterValue(Parameter param) {
  282           if (param == null) {
  283               return null;
  284           } else {
  285               return (String) param.getValue();
  286           }
  287       }
  288   
  289       /**
  290        * Get the name of the module , where archive name is combination of module name + its version
  291        * The format of the name is as follows:
  292        * moduleName-00.0000
  293        * Example: "addressing-01.0001.mar" would return "addressing"
  294        *
  295        * @param moduleName the name of the module archive
  296        * @return the module name parsed out of the file name
  297        */
  298       public static String getModuleName(String moduleName) {
  299           if (moduleName.endsWith("-SNAPSHOT")) {
  300               return moduleName.substring(0, moduleName.indexOf("-SNAPSHOT"));
  301           }
  302           char delimiter = '-';
  303           int version_index = moduleName.lastIndexOf(delimiter);
  304           if (version_index > 0) {
  305               String versionString = getModuleVersion(moduleName);
  306               if (versionString == null) {
  307                   return moduleName;
  308               } else {
  309                   return moduleName.substring(0, version_index);
  310               }
  311           } else {
  312               return moduleName;
  313           }
  314       }
  315   
  316       public static String getModuleVersion(String moduleName) {
  317           if (moduleName.endsWith("-SNAPSHOT")) {
  318               return "SNAPSHOT";
  319           }
  320           char version_seperator = '-';
  321           int version_index = moduleName.lastIndexOf(version_seperator);
  322           if (version_index > 0) {
  323               String versionString = moduleName.substring(version_index + 1, moduleName.length());
  324               try {
  325                   Float.parseFloat(versionString);
  326                   return versionString;
  327               } catch (NumberFormatException e) {
  328                   return null;
  329               }
  330           } else {
  331               return null;
  332           }
  333       }
  334   
  335       public static String getModuleName(String moduleName, String moduleVersion) {
  336           if (moduleVersion != null && moduleVersion.length() != 0) {
  337               moduleName = moduleName + "-" + moduleVersion;
  338           } 
  339           return moduleName;
  340       }
  341   
  342       /**
  343        * - if he trying to engage the same module then method will returen false
  344        * - else it will return true
  345        *
  346        */
  347       public static boolean checkVersion(String module1version,
  348                                          String module2version) throws AxisFault {
  349           if ((module1version !=null && !module1version.equals(module2version)) ||
  350                   module2version !=null && !module2version.equals(module1version)) {
  351               throw new AxisFault("trying to engage two different module versions " +
  352                       module1version + " : " + module2version);
  353           }
  354           return true;
  355       }
  356   
  357       public static void calculateDefaultModuleVersion(HashMap modules,
  358                                                        AxisConfiguration axisConfig) {
  359           Iterator allModules = modules.values().iterator();
  360           HashMap defaultModules = new HashMap();
  361           while (allModules.hasNext()) {
  362               AxisModule axisModule = (AxisModule) allModules.next();
  363               String moduleName = axisModule.getName();
  364               String moduleNameString;
  365               String moduleVersionString;
  366               if (AxisModule.VERSION_SNAPSHOT.equals(axisModule.getVersion())) {
  367                   moduleNameString = axisModule.getName();
  368                   moduleVersionString = axisModule.getVersion();
  369               } else {
  370                   if (axisModule.getVersion() == null) {
  371                       moduleNameString = getModuleName(moduleName);
  372                       moduleVersionString = getModuleVersion(moduleName);
  373                       if (moduleVersionString != null) {
  374                           try {
  375                               Float.valueOf(moduleVersionString);
  376                               axisModule.setVersion(moduleVersionString);
  377                               axisModule.setName(moduleName);
  378                           } catch (NumberFormatException e) {
  379                               moduleVersionString = null;
  380                           }
  381                       }
  382                   } else {
  383                       moduleNameString = axisModule.getName();
  384                       moduleVersionString = axisModule.getVersion();
  385                   }
  386               }
  387               String currentDefaultVerison = (String) defaultModules.get(moduleNameString);
  388               if (currentDefaultVerison != null) {
  389                   // if the module version is null then , that will be ignore in this case
  390                   if (!AxisModule.VERSION_SNAPSHOT.equals(currentDefaultVerison)) {
  391                       if (moduleVersionString != null &&
  392                           isLatest(moduleVersionString, currentDefaultVerison)) {
  393                           defaultModules.put(moduleNameString, moduleVersionString);
  394                       }
  395                   }
  396               } else {
  397                   defaultModules.put(moduleNameString, moduleVersionString);
  398               }
  399   
  400           }
  401           Iterator def_mod_itr = defaultModules.keySet().iterator();
  402           while (def_mod_itr.hasNext()) {
  403               String moduleName = (String) def_mod_itr.next();
  404               axisConfig.addDefaultModuleVersion(moduleName, (String) defaultModules.get(moduleName));
  405           }
  406       }
  407   
  408       public static boolean isLatest(String moduleVersion, String currentDefaultVersion) {
  409           if (AxisModule.VERSION_SNAPSHOT.equals(moduleVersion)) {
  410               return true;
  411           } else {
  412               float m_version = Float.parseFloat(moduleVersion);
  413               float m_c_vresion = Float.parseFloat(currentDefaultVersion);
  414               return m_version > m_c_vresion;
  415           }
  416       }
  417   
  418       /**
  419        * Check if a MessageContext property is true.
  420        *
  421        * @param messageContext the MessageContext
  422        * @param propertyName   the property name
  423        * @return true if the property is Boolean.TRUE, "true", 1, etc. or false otherwise
  424        * @deprecated please use MessageContext.isTrue(propertyName) instead
  425        */
  426       public static boolean isExplicitlyTrue(MessageContext messageContext, String propertyName) {
  427           Object flag = messageContext.getProperty(propertyName);
  428           return JavaUtils.isTrueExplicitly(flag);
  429       }
  430   
  431       /**
  432        * Maps the String URI of the Message exchange pattern to a integer.
  433        * Further, in the first lookup, it will cache the looked
  434        * up value so that the subsequent method calls are extremely efficient.
  435        */
  436       public static int getAxisSpecifMEPConstant(String messageExchangePattern) {
  437   
  438   
  439           int mepConstant = WSDLConstants.MEP_CONSTANT_INVALID;
  440   
  441           if (WSDL2Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) ||
  442               WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OUT.equals(messageExchangePattern) ||
  443               WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OUT.equals(messageExchangePattern)) {
  444               mepConstant = WSDLConstants.MEP_CONSTANT_IN_OUT;
  445           } else if (
  446                   WSDL2Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) ||
  447                   WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_ONLY.equals(messageExchangePattern) ||
  448                   WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_ONLY
  449                           .equals(messageExchangePattern)) {
  450               mepConstant = WSDLConstants.MEP_CONSTANT_IN_ONLY;
  451           } else if (WSDL2Constants.MEP_URI_IN_OPTIONAL_OUT
  452                   .equals(messageExchangePattern) ||
  453                                                   WSDLConstants.WSDL20_2006Constants.MEP_URI_IN_OPTIONAL_OUT
  454                                                           .equals(messageExchangePattern) ||
  455                                                                                           WSDLConstants.WSDL20_2004_Constants.MEP_URI_IN_OPTIONAL_OUT
  456                                                                                                   .equals(messageExchangePattern)) {
  457               mepConstant = WSDLConstants.MEP_CONSTANT_IN_OPTIONAL_OUT;
  458           } else if (WSDL2Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) ||
  459                      WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_IN.equals(messageExchangePattern) ||
  460                      WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_IN
  461                              .equals(messageExchangePattern)) {
  462               mepConstant = WSDLConstants.MEP_CONSTANT_OUT_IN;
  463           } else if (WSDL2Constants.MEP_URI_OUT_ONLY.equals(messageExchangePattern) ||
  464                      WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_ONLY
  465                              .equals(messageExchangePattern) ||
  466                                                              WSDLConstants.WSDL20_2004_Constants
  467                                                                      .MEP_URI_OUT_ONLY.equals(messageExchangePattern)) {
  468               mepConstant = WSDLConstants.MEP_CONSTANT_OUT_ONLY;
  469           } else if (WSDL2Constants.MEP_URI_OUT_OPTIONAL_IN.equals(messageExchangePattern) ||
  470                      WSDLConstants.WSDL20_2006Constants.MEP_URI_OUT_OPTIONAL_IN
  471                              .equals(messageExchangePattern) ||
  472                                                              WSDLConstants.WSDL20_2004_Constants.MEP_URI_OUT_OPTIONAL_IN
  473                                                                      .equals(messageExchangePattern)) {
  474               mepConstant = WSDLConstants.MEP_CONSTANT_OUT_OPTIONAL_IN;
  475           } else if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(messageExchangePattern) ||
  476                      WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_IN_ONLY
  477                              .equals(messageExchangePattern) ||
  478                                                              WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_IN_ONLY
  479                                                                      .equals(messageExchangePattern)) {
  480               mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_IN_ONLY;
  481           } else if (WSDL2Constants.MEP_URI_ROBUST_OUT_ONLY.equals(messageExchangePattern) ||
  482                      WSDLConstants.WSDL20_2006Constants.MEP_URI_ROBUST_OUT_ONLY
  483                              .equals(messageExchangePattern) ||
  484                                                              WSDLConstants.WSDL20_2004_Constants.MEP_URI_ROBUST_OUT_ONLY
  485                                                                      .equals(messageExchangePattern)) {
  486               mepConstant = WSDLConstants.MEP_CONSTANT_ROBUST_OUT_ONLY;
  487           }
  488   
  489           if (mepConstant == WSDLConstants.MEP_CONSTANT_INVALID) {
  490               throw new AxisError(Messages.getMessage("mepmappingerror"));
  491           }
  492   
  493   
  494           return mepConstant;
  495       }
  496   
  497       /**
  498        * Get an AxisFault object to represent the SOAPFault in the SOAPEnvelope attached
  499        * to the provided MessageContext. This first check for an already extracted AxisFault
  500        * and otherwise does a simple extract.
  501        * <p/>
  502        * MUST NOT be passed a MessageContext which does not contain a SOAPFault
  503        *
  504        * @param messageContext
  505        * @return
  506        */
  507       public static AxisFault getInboundFaultFromMessageContext(MessageContext messageContext) {
  508           // Get the fault if it's already been extracted by a handler
  509           AxisFault result = (AxisFault) messageContext.getProperty(Constants.INBOUND_FAULT_OVERRIDE);
  510           // Else, extract it from the SOAPBody
  511           if (result == null) {
  512               SOAPEnvelope envelope = messageContext.getEnvelope();
  513               SOAPFault soapFault;
  514               SOAPBody soapBody;
  515               if (envelope != null && (soapBody = envelope.getBody()) != null) {
  516                   if ((soapFault = soapBody.getFault()) != null) {
  517                       return new AxisFault(soapFault, messageContext);
  518                   }
  519                   // If its a REST response the content is not a SOAP envelop and hence we will
  520                   // Have use the soap body as the exception
  521                   if (messageContext.isDoingREST() && soapBody.getFirstElement() != null) {
  522                       return new AxisFault(soapBody.getFirstElement().toString());
  523                   }
  524               }
  525               // Not going to be able to
  526               throw new IllegalArgumentException(
  527                       "The MessageContext does not have an associated SOAPFault.");
  528           }
  529           return result;
  530       }
  531       
  532       /**
  533        * This method will provide the logic needed to retrieve an Object's classloader
  534        * in a Java 2 Security compliant manner.
  535        */
  536       public static ClassLoader getObjectClassLoader(final Object object) {
  537           if(object == null) {
  538               return null;
  539           }
  540           else {
  541               return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
  542                   public Object run() {
  543                       return object.getClass().getClassLoader();
  544                   }
  545               });
  546           }
  547       }
  548       
  549       public static int getMtomThreshold(MessageContext msgCtxt){
  550       	Integer value = null;         
  551           if(!msgCtxt.isServerSide()){                
  552   	        value = (Integer)msgCtxt.getProperty(Constants.Configuration.MTOM_THRESHOLD);	        
  553           }else{
  554           	Parameter param = msgCtxt.getParameter(Constants.Configuration.MTOM_THRESHOLD);
  555           	if(param!=null){
  556           		value = (Integer)param.getValue();       		        		
  557           	}        	        	
  558           }
  559           int threshold = (value!=null)?value.intValue():0;
  560           if(log.isDebugEnabled()){
  561           	log.debug("MTOM optimized Threshold value ="+threshold);
  562           }
  563           return threshold;
  564       }
  565        /**
  566        * Returns the ip address to be used for the replyto epr
  567        * CAUTION:
  568        * This will go through all the available network interfaces and will try to return an ip address.
  569        * First this will try to get the first IP which is not loopback address (127.0.0.1). If none is found
  570        * then this will return this will return 127.0.0.1.
  571        * This will <b>not<b> consider IPv6 addresses.
  572        * <p/>
  573        * TODO:
  574        * - Improve this logic to genaralize it a bit more
  575        * - Obtain the ip to be used here from the Call API
  576        *
  577        * @return Returns String.
  578        * @throws java.net.SocketException
  579         */
  580       public static String getIpAddress() throws SocketException {
  581           Enumeration e = NetworkInterface.getNetworkInterfaces();
  582           String address = "127.0.0.1";
  583   
  584           while (e.hasMoreElements()) {
  585               NetworkInterface netface = (NetworkInterface) e.nextElement();
  586               Enumeration addresses = netface.getInetAddresses();
  587   
  588               while (addresses.hasMoreElements()) {
  589                   InetAddress ip = (InetAddress) addresses.nextElement();
  590                   if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) {
  591                       return ip.getHostAddress();
  592                   }
  593               }
  594           }
  595   
  596           return address;
  597       }
  598   
  599       /**
  600        * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) ,
  601        * if it is there then this will retun that as the host name , o.w will return the IP address.
  602        */
  603       public static String getIpAddress(AxisConfiguration axisConfiguration) throws SocketException {
  604           if(axisConfiguration!=null){
  605               Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS);
  606               if (param != null) {
  607                   String  hostAddress = ((String) param.getValue()).trim();
  608                   if(hostAddress!=null){
  609                       return hostAddress;
  610                   }
  611               }
  612           }
  613           return getIpAddress();
  614       }
  615       
  616       /**
  617        * First check whether the hostname parameter is there in AxisConfiguration (axis2.xml) ,
  618        * if it is there then this will return that as the host name , o.w will return the IP address.
  619        * @param axisConfiguration
  620        * @return hostname 
  621        */
  622       public static String getHostname(AxisConfiguration axisConfiguration) {
  623           if(axisConfiguration!=null){
  624               Parameter param = axisConfiguration.getParameter(TransportListener.HOST_ADDRESS);
  625               if (param != null) {
  626                   String  hostAddress = ((String) param.getValue()).trim();
  627                   if(hostAddress!=null){
  628                       return hostAddress;
  629                   }
  630               }
  631           }      
  632           return null;
  633       }
  634   
  635       private static boolean isIP(String hostAddress) {
  636           return hostAddress.split("[.]").length == 4;
  637       }
  638   }

Save This Page
Home » axis2-1.5-src » org.apache » axis2 » util » [javadoc | source]