Merge the handler chains from webservices.xml file with @HandChain

@param webServices
@param endpointInfo
@throws Exception
338628
public static void mergeHandlerChains(PortComponent portComp,
                                          EndpointInfo endpointInfo) {

        if (endpointInfo == null || portComp == null) {
            return;
        }

        HandlerChainsInfo hChainsInfo = new HandlerChainsInfo();

        List<HandlerChain> handlerChains = portComp.getHandlerChains();

        if (handlerChains == null || handlerChains.size() == 0) {
            return;
        }

        for (HandlerChain hChain : handlerChains) {

            HandlerChainInfo chainInfo = new HandlerChainInfo();

            // set portQName and serviceQName
            QName qName = convertDDQNameToQName(hChain.getPortNamePattern());
            if (qName != null) {
                // If endpointInfo's portQName could match the
                // handlerChain's portName, just ignore the followed
                // handlers
                if (!JaxWsUtils.matchesQName(qName, endpointInfo.getWsdlPort(),
                                             true)) {
                    continue;
                }
                chainInfo.setPortNamePattern(qName);
            }

            qName = convertDDQNameToQName(hChain.getServiceNamePattern());
            if (qName != null) {
                if (!JaxWsUtils.matchesQName(qName, endpointInfo
                                .getWsdlService(), true)) {
                    continue;
                }
                chainInfo.setServiceNamePattern(qName);
            }
            // set protocol bindings
            List<String> bindings = hChain.getProtocolBindings();
            boolean include = false;
            if (bindings != null) {
                for (String binding : bindings) {
                    if (JaxWsUtils.singleProtocolMatches(binding, endpointInfo
                                    .getProtocolBinding())) {
                        include |= true;
                    }
                    chainInfo.addProtocolBinding(JaxWsUtils.getProtocolByToken(binding));
                }
                // if the binding protocol is not support, just ignore the
                // handlers
                if (!include && !bindings.isEmpty()) {
                    continue;
                }
            }
            // set handlers
            for (Handler handler : hChain.getHandlers()) {

                HandlerInfo hInfo = new HandlerInfo();

                // handler-class
                String handlerClass = handler.getHandlerClassName();

                if (handlerClass == null || "".equals(handlerClass)) {
                    Tr.warning(tc, "warn.dd.invalid.handler", "<handler-class>", endpointInfo.getPortComponentName());
                    continue;
                }

                // handler-name
                String handlerName = handler.getHandlerName();

                if (handlerName == null || "".equals(handlerName)) {
                    Tr.warning(tc, "warn.dd.invalid.handler", "<handler-name>", endpointInfo.getPortComponentName());
                    continue;
                }

                hInfo.setHandlerClass(handlerClass);
                hInfo.setHandlerName(handlerName);

                // port-name
                List<String> portNames = handler.getPortNames();

                for (String portName : portNames) {
                    hInfo.addPortName(portName);
                }

                // soap-role
                List<String> soapRoles = handler.getSoapRoles();

                for (String soapRole : soapRoles) {
                    hInfo.addSoapRole(soapRole);
                }

                // soap-header
                List<com.ibm.ws.javaee.dd.common.QName> soapHeaders = handler
                                .getSoapHeaders();

                for (com.ibm.ws.javaee.dd.common.QName soapHeader : soapHeaders) {
                    hInfo.addSoapHeader(new XsdQNameInfo(new QName(
                                                                   soapHeader.getNamespaceURI(), soapHeader
                                                                                   .getLocalPart()), ""));// no id info...
                }

                // init-param(rpc)
                List<ParamValue> initParams = handler.getInitParams();

                for (ParamValue pv : initParams) {
                    hInfo.addInitParam(new ParamValueInfo(pv.getName(), pv
                                    .getValue()));
                }

                chainInfo.addHandlerInfo(hInfo);
            }

            hChainsInfo.addHandlerChainInfo(chainInfo);
        }

        if (!hChainsInfo.getHandlerChainInfos().isEmpty()) {
            /**
             * According to the behavior of tWAS, just replace the handlerChain
             * from @HandlerChain
             * 
             * site here: 582987 per JSR 109 6.2.2.3, handler chains specified
             * in the dd override handler chain annotations. We can not have
             * both HCannotations and HCtypes set in the dbc, so wipe out the
             * annotations here
             */
            endpointInfo.setHandlerChainsInfo(hChainsInfo);
        }
    }
262376
public void endpointActivation(MessageEndpointFactory endpointFactory,
      ActivationSpec spec) throws ResourceException {
    VertxActivation activation = new VertxActivation(this, endpointFactory,
        (VertxActivationSpec) spec);
    activations.put((VertxActivationSpec) spec, activation);
    activation.start();

    log.finest("endpointActivation()");

  }
800828
public void addHandlers(Object... handlers) {
        for ( Object handler : handlers) {
            //assert that this is a Handler
            checkValidHandlerType(handler);

            StepInvokerProvider invokerFactory = new HandlerClassInvokerFactory(handler);
            List<StepInvoker> invokers = invokerFactory.getStepInvokers();

            if (invokers.isEmpty()) {
                Class<?> handlerClass = handler.getClass();
                log.warn(String.format("Cannot export object of type (%s) it either:  1) Has no methods that declare the @Step annotation  " +
                        "2) Returns zero StepInvoker's from a StepInvokerProvider instance", handlerClass.getName()));
            }

            for ( StepInvoker i : invokers) {
                addStepInvoker(i);
            }
        }
    }
593617
static void initChains() {
		if (config != null && config.getChains() != null) {
			// add the chains to the handler list by id list.
			for (String chainName : config.getChains().keySet()) {
				List<String> chain = config.getChains().get(chainName);
				List<HttpHandler> handlerChain = new ArrayList<>();
				for (String chainItemName : chain) {
					HttpHandler chainItem = handlers.get(chainItemName);
					if (chainItem == null)
						throw new RuntimeException("Chain " + chainName + " uses Unknown handler: " + chainItemName);
					handlerChain.add(chainItem);
				}
				handlerListById.put(chainName, handlerChain);
			}
		}
	}
525919
private static Endpoint initServiceEndpoint(EndpointRegistry epRegistry, String contextPath, String servletName)
   {
      if (contextPath.startsWith("/"))
         contextPath = contextPath.substring(1);

      final ObjectName oname = ObjectNameFactory.create(Endpoint.SEPID_DOMAIN + ":" + Endpoint.SEPID_PROPERTY_CONTEXT
            + "=" + contextPath + "," + Endpoint.SEPID_PROPERTY_ENDPOINT + "=" + servletName);
      Endpoint endpoint = epRegistry.getEndpoint(oname);
      if (endpoint == null)
      {
         throw Messages.MESSAGES.cannotObtainEndpoint(oname);
      }

      //Inject the EJB and JNDI resources if possible
      injectServiceAndHandlerResources(endpoint);

      return endpoint;
   }
444776
public static Endpoint merge(Endpoint defaults, Endpoint override) {

        if (defaults == null) {
            defaults = new Endpoint();
        }

        if (override == null) {
            override = new Endpoint();
        }

        final Endpoint merged = new Endpoint();

        merged.setCredentialScope(override.getCredentialScope() != null
                ? override.getCredentialScope()
                : defaults.getCredentialScope());

        merged.setHostName(override.getHostName() != null
                ? override.getHostName()
                : defaults.getHostName());

        merged.setSslCommonName(override.getSslCommonName() != null
                ? override.getSslCommonName()
                : defaults.getSslCommonName());

        merged.setProtocols(override.getProtocols() != null
                ? override.getProtocols()
                : defaults.getProtocols());

        merged.setSignatureVersions(override.getSignatureVersions() != null
                ? override.getSignatureVersions()
                : defaults.getSignatureVersions()
        );

        return merged;

    }
897648
public void merge(StandaloneConfiguration other) {
    if (other == null) {
      return;
    }

    if (isMergeAble(Integer.class, other.browserTimeout, browserTimeout)) {
      browserTimeout = other.browserTimeout;
    }
    if (isMergeAble(Integer.class, other.jettyMaxThreads, jettyMaxThreads)) {
      jettyMaxThreads = other.jettyMaxThreads;
    }
    if (isMergeAble(Integer.class, other.timeout, timeout)) {
      timeout = other.timeout;
    }
    // role, host, port, log, debug, version, enablePassThrough, and help are not merged,
    // they are only consumed by the immediately running process and should never affect a remote
  }
949094
public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {

		// Stop all named services (either Flows or services
		List<Lifecycle> services = new ArrayList<Lifecycle>();
		for (String serviceName : serviceNames) {
			try {
				Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
//				logServiceStatus(service);
//				service.stop();
//				logServiceStatus(service);
				services.add(service);
			} catch (Exception e) {
				logger.error("Error '" + e.getMessage()
						+ "' occured while stopping the service " + serviceName
						+ ". Perhaps the service did not exist in the config?");
				throw e;
			}
		}

		// Now init the directory for each named endpoint, one by one
		for (String endpointName : endpointNames) {
			initEndpointDirectory(muleContext, endpointName);
		}

		// We are done, startup the services again so that the test can begin...
		for (@SuppressWarnings("unused") Lifecycle service : services) {
//			logServiceStatus(service);
//			service.start();
//			logServiceStatus(service);
		}
	}
580088
public void registerHanders(String packageString) {
		List<String> list = AnnotationDetector.scanAsList(ExceptionHandler.class, packageString);
		for (String handler : list) {
//			System.out.println(handler);						
			JKExceptionHandler<? extends Throwable> newInstance = JKObjectUtil.newInstance(handler);
			Class<? extends Throwable> clas = JKObjectUtil.getGenericParamter(handler);
			setHandler(clas, newInstance);
		}
	}
147718
protected static void initEndpointInfo(List<EndpointInfo> endpoints) {
        for (int i = 0; i < endpoints.size(); i++) {
            initEndpointInfo(endpoints.get(i));
        }
    }
601733
private static List<String> loadEndPoints(Map<String, String[]> endpoints) {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();
        final EndPointMgr epm = EndPointMgrImpl.getRef();
        List<String> createdEndpoints = new ArrayList<String>(endpoints.size());

        for (Entry<String, String[]> entry : endpoints.entrySet()) {
            try {
                EndPointInfo ep = defineEndPoint(epm, entry.getKey(), entry.getValue());
                createdEndpoints.add(ep.getName());
            } catch (IllegalArgumentException e) {
                FFDCFilter.processException(e, "ChannelUtils.loadEndPoints",
                                            "create", new Object[] { epm, entry });
                if (bTrace && tc.isEventEnabled()) {
                    Tr.event(tc, "Unable to load endpoint: " + e);
                }
            }
        }

        return createdEndpoints;
    }
66552
static void buildEjbWebServiceEndpointInfos(EndpointInfoBuilder endpointInfoBuilder, EndpointInfoBuilderContext ctx, JaxWsServerMetaData jaxWsServerMetaData,
                                                   List<EJBEndpoint> ejbEndpoints, JaxWsModuleInfo jaxWsModuleInfo) throws UnableToAdaptException {
        Set<String> presentedServices = jaxWsModuleInfo.getEndpointImplBeanClassNames();

        for (EJBEndpoint ejbEndpoint : ejbEndpoints) {
            if (!ejbEndpoint.isWebService()) {
                continue;
            }
            if (presentedServices.contains(ejbEndpoint.getClassName())) {
                continue;
            }

            String ejbName = ejbEndpoint.getJ2EEName().getComponent();
            ctx.addContextEnv(JaxWsConstants.ENV_ATTRIBUTE_ENDPOINT_BEAN_NAME, ejbName);
            EndpointInfo endpointInfo = endpointInfoBuilder.build(ctx, ejbEndpoint.getClassName(), EndpointType.EJB);
            if (endpointInfo != null) {
                jaxWsModuleInfo.addEndpointInfo(ejbEndpoint.getName(), endpointInfo);
                jaxWsServerMetaData.putEndpointNameAndJ2EENameEntry(ejbName, ejbEndpoint.getJ2EEName());
            }
        }
    }
841667
protected void createServletWrappers() throws Exception {
        // NOTE: namespace preinvoke/postinvoke not necessary as the only
        // external
        // code being run is the servlet's init() and that is handled in the
        // ServletWrapper

        // check if an extensionFactory is present for *.jsp:
        // We do this by constructing an arbitrary mapping which
        // will only match the *.xxx extension pattern
        //
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
            logger.entering(CLASS_NAME, "createServletWrappers");

        WebExtensionProcessor jspProcessor = (WebExtensionProcessor) requestMapper.map("/dummyPath.jsp");

        if (jspProcessor == null) {
            // No extension processor present to handle this kind of
            // target. Hence warn, skip.
            // pk435011
            // LIBERTY: changing log level to debug as this is valid if there's no JSP support configured
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                logger.logp(Level.FINE, CLASS_NAME, "createServletWrappers", "No Extension Processor found for handling JSPs");
            //logger.logp(Level.WARNING, CLASS_NAME, "createServletWrappers", "no.jsp.extension.handler.found");

        }

        Iterator<IServletConfig> sortedServletConfigIterator = sortNamesByStartUpWeight(config.getServletInfos());
        Map<String, List<String>> mappings = config.getServletMappings();
        String path = null;
        IServletConfig servletConfig;
        IServletWrapper wrapper = null;
        while (sortedServletConfigIterator.hasNext() && !com.ibm.ws.webcontainer.osgi.WebContainer.isServerStopping()) {
            wrapper = null; // 248871: reset wrapper to null
            servletConfig = sortedServletConfigIterator.next();
            String servletName = servletConfig.getServletName();
            List<String> mapList = mappings.get(servletConfig.getServletName());
            servletConfig.setServletContext(this.getFacade());

            // Begin 650884
            // WARNING!!! We shouldn't map by name only as there is
            // no way to configure a security constraint
            // for a dynamically added path.

            //Consolidate the code to setup a single entry map list when its mapped by name only
            // if (mapList==null){
            // //WARNING!!! We shouldn't map by name only as there is
            // //no way to configure a security constraint
            // //for a dynamically added path.
            // //Also, if there was nothing mapped to the servlet
//                              //in web.xml, we would have never called WebAppConfiguration.addServletMapping
//                              //which sets the mappings on sconfig. Adding the list directly to the hashMap short
//                              //circuits that logic so future calls to addMapping on the ServletConfig wouldn't work
            // //unless there was at least one mapping in web.xml
            //                  
            //                  
            // // hardcode the path, since it had no mappings
            // String byNamePath = BY_NAME_ONLY + servletName;
            //
            // // Add this to the config, because we will be looking at
            // // the mappings in order to get to the servlet through the
            // // mappings in the config.
            // mapList = new ArrayList<String>();
            // mapList.add(byNamePath);
            // mappings.put(servletName, mapList);
            // }
            // End 650884

            if (mapList == null || mapList.isEmpty()) {
                wrapper = jspAwareCreateServletWrapper(jspProcessor,
                                                       servletConfig, servletName);
            }
            else {
                for (String urlPattern : mapList) {
                    path = urlPattern;

                    if (path == null) {
                        // shouldn't happen since there is a mapping specified
                        // but too bad the user can never hit the servlet
                        // pk435011
                        // Begin 650884
                        logger.logp(Level.SEVERE, CLASS_NAME, "createServletWrappers", "illegal.servlet.mapping", servletName); // PK33511
                        // path = "/" + BY_NAME_ONLY + "/" + servletName;
                        // End 650884
                    } else if (path.equals("/")) {
                        path = "/*";
                    }

                    if (wrapper == null) { // 248871: Check to see if we've
                        // already found wrapper for
                        // servletName

                        wrapper = jspAwareCreateServletWrapper(jspProcessor,
                                                               servletConfig, servletName);

                        if (wrapper == null)
                            continue;
                    }
                    try {
                        // Begin:248871: Check to see if we found the wrapper
                        // before adding
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                            logger.logp(Level.FINE, CLASS_NAME, "createServletWrappers"
                                        , "determine whether to add mapping for path[{0}] wrapper[{1}] isEnabled[{2}]"
                                        , new Object[] { path, wrapper, servletConfig.isEnabled() });
                        if (path != null && servletConfig.isEnabled()) {
                            requestMapper.addMapping(path, wrapper);
                        }
                        // End:248871
                    } catch (Exception e) {
                        //TODO: ???? extension processor used to call addMappingTarget after the wrappers had been added.
                        //Now it is done before, and you can get this exception here in the case they call addMappingTarget
                        //and add the mapping to the servletConfig because we'll try to add it again, but it will
                        //already be mapped. You could add a list of paths to ignore and not try to add again. So any
                        //path added via addMappingTarget will be recorded and addMapping can be skipped. It is preferrable
                        //to just have them not call addMappingTarget any more instead of adding the extra check.
                        // pk435011
                        logger.logp(Level.WARNING, CLASS_NAME, "createServletWrappers", "error.while.adding.servlet.mapping.for.path", new Object[] {
                                    path, wrapper, getApplicationName() });
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, CLASS_NAME + ".createServletWrappers", "455", this);
                            // pk435011
                            logger.logp(Level.SEVERE, CLASS_NAME, "createServletWrappers", "error.adding.servlet.mapping.for.servlet", new Object[] {
                                        servletName, getApplicationName(), e }); // PK33511
                        }
                    }
                }
            }

            servletConfig.setServletWrapper(wrapper);

            this.initializeNonDDRepresentableAnnotation(servletConfig);
            // set the servlet wrapper on the
            // servlet config so
            // ServletConfig.addMapping
            // can put it in the
            // requestMapper

        }
    }
337852
private Collection<String> processAllowedEndpoints(Collection<String> endpointIds) {
        if (endpointIds == null || endpointIds.isEmpty())
            return null;

        return endpointIds;
    }
282549
protected void handleInboundHttpHeaders(final SoapMessage message,
                                            final WebServiceEndpointConfiguration endpointConfiguration) {
        final TransportContext transportContext = TransportContextHolder.getTransportContext();
        if (transportContext == null) {
            log.warn("Unable to get complete set of http request headers - no transport context available");
            return;
        }

        final WebServiceConnection connection = transportContext.getConnection();
        if (connection instanceof HttpServletConnection) {
            final UrlPathHelper pathHelper = new UrlPathHelper();
            final HttpServletConnection servletConnection = (HttpServletConnection) connection;
            final HttpServletRequest httpServletRequest = servletConnection.getHttpServletRequest();
            message.setHeader(SoapMessageHeaders.HTTP_REQUEST_URI, pathHelper.getRequestUri(httpServletRequest));
            message.setHeader(SoapMessageHeaders.HTTP_CONTEXT_PATH, pathHelper.getContextPath(httpServletRequest));

            final String queryParams = pathHelper.getOriginatingQueryString(httpServletRequest);
            message.setHeader(SoapMessageHeaders.HTTP_QUERY_PARAMS, queryParams != null ? queryParams : "");

            message.setHeader(SoapMessageHeaders.HTTP_REQUEST_METHOD, httpServletRequest.getMethod());

            if (endpointConfiguration.isHandleAttributeHeaders()) {
                final Enumeration<String> attributeNames = httpServletRequest.getAttributeNames();
                while (attributeNames.hasMoreElements()) {
                    final String attributeName = attributeNames.nextElement();
                    final Object attribute = httpServletRequest.getAttribute(attributeName);
                    message.setHeader(attributeName, attribute);
                }
            }
        } else {
            log.warn("Unable to get complete set of http request headers");

            try {
                message.setHeader(SoapMessageHeaders.HTTP_REQUEST_URI, connection.getUri());
            } catch (final URISyntaxException e) {
                log.warn("Unable to get http request uri from http connection", e);
            }
        }
    }
5779
@Override
    public T addHandlers(ArchiveEventHandler... handlers) {
        for (ArchiveEventHandler handler : handlers) {
            this.getArchive().addHandlers(handler);
        }
        return covarientReturn();
    }
1029627
public void processHttpChainWork(boolean enableEndpoint, boolean isPause) {
        if (enableEndpoint) {
            // enable the endpoint if it is currently disabled
            // it's ok if the endpoint is stopped, the config update will occur @ next start
            endpointState.compareAndSet(DISABLED, ENABLED);

            if (httpPort >= 0) {
                httpChain.enable();
            }
            if (httpsPort >= 0 && sslFactoryProvider.getService() != null) {
                httpSecureChain.enable();
            }

            if (!isPause) {
                // Use an update action so they pick up the new settings
                performAction(updateAction);
            } else {
                updateAction.run();
            }
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "endpoint disabled: " + (String) endpointConfig.get("id"));
            }

            // The endpoint has been disabled-- stop it now
            endpointState.set(DISABLED);
            if (!isPause) {
                performAction(stopAction);
            } else {
                stopAction.run();
            }
        }
    }