@Override
  public void getResourceValue(
      final ResolutionContext resolutionContext,
      final ServiceBuilder<?> serviceBuilder,
      final DeploymentPhaseContext phaseContext,
      final Injector<ManagedReferenceFactory> injector)
      throws DeploymentUnitProcessingException {
    final Class<?> type;
    if (targetType != null) {
      type = targetType;
    } else {
      final DeploymentClassIndex index =
          phaseContext
              .getDeploymentUnit()
              .getAttachment(org.jboss.as.server.deployment.Attachments.CLASS_INDEX);
      try {
        type = index.classIndex(targetTypeName).getModuleClass();
      } catch (ClassNotFoundException e) {
        throw new RuntimeException("Could not load EJB type " + targetTypeName, e);
      }
    }

    injector.inject(
        new ManagedReferenceFactory() {
          @Override
          public ManagedReference getReference() {
            try {
              final Object value = new InitialContext().lookup(lookup);

              return new ManagedReference() {
                @Override
                public void release() {}

                @Override
                public Object getInstance() {
                  return PortableRemoteObject.narrow(value, type);
                }
              };
            } catch (NamingException e) {
              throw new RuntimeException(e);
            }
          }
        });
  }
  private void addListener(
      final DeploymentClassIndex classReflectionIndex,
      final ComponentRegistry components,
      final DeploymentInfo d,
      final ListenerMetaData listener)
      throws ClassNotFoundException {

    ListenerInfo l;
    final Class<? extends EventListener> listenerClass =
        (Class<? extends EventListener>)
            classReflectionIndex.classIndex(listener.getListenerClass()).getModuleClass();
    ComponentRegistry.ComponentManagedReferenceFactory creator =
        components.getComponentsByClass().get(listenerClass);
    if (creator != null) {
      InstanceFactory<EventListener> factory = createInstanceFactory(creator);
      l = new ListenerInfo(listenerClass, factory);
    } else {
      l = new ListenerInfo(listenerClass);
    }
    d.addListener(l);
  }
  private void processEjb(
      final EJBComponentDescription componentDescription,
      final DeploymentClassIndex classIndex,
      final DeploymentReflectionIndex deploymentReflectionIndex,
      final Module module,
      final ServiceTarget serviceTarget,
      final IIOPMetaData iiopMetaData) {
    componentDescription.setExposedViaIiop(true);

    // Create bean method mappings for container invoker

    final EJBViewDescription remoteView = componentDescription.getEjbRemoteView();
    final ClassIndex remoteClass;
    try {
      remoteClass = classIndex.classIndex(remoteView.getViewClassName());
    } catch (ClassNotFoundException e) {
      throw EjbLogger.ROOT_LOGGER.failedToLoadViewClassForComponent(
          e, componentDescription.getEJBClassName());
    }
    final EJBViewDescription homeView = componentDescription.getEjbHomeView();
    final ClassIndex homeClass;
    try {
      homeClass = classIndex.classIndex(homeView.getViewClassName());
    } catch (ClassNotFoundException e) {
      throw EjbLogger.ROOT_LOGGER.failedToLoadViewClassForComponent(
          e, componentDescription.getEJBClassName());
    }

    componentDescription
        .getEjbHomeView()
        .getConfigurators()
        .add(new IIOPInterceptorViewConfigurator());
    componentDescription
        .getEjbRemoteView()
        .getConfigurators()
        .add(new IIOPInterceptorViewConfigurator());

    final InterfaceAnalysis remoteInterfaceAnalysis;
    try {
      // TODO: change all this to use the deployment reflection index
      remoteInterfaceAnalysis =
          InterfaceAnalysis.getInterfaceAnalysis(remoteClass.getModuleClass());
    } catch (RMIIIOPViolationException e) {
      throw EjbLogger.ROOT_LOGGER.failedToAnalyzeRemoteInterface(
          e, componentDescription.getComponentName());
    }

    final Map<String, SkeletonStrategy> beanMethodMap = new HashMap<String, SkeletonStrategy>();

    final AttributeAnalysis[] remoteAttrs = remoteInterfaceAnalysis.getAttributes();
    for (int i = 0; i < remoteAttrs.length; i++) {
      final OperationAnalysis op = remoteAttrs[i].getAccessorAnalysis();
      if (op != null) {
        EjbLogger.ROOT_LOGGER.debugf(
            "    %s\n                %s", op.getJavaName(), op.getIDLName());
        // translate to the deployment reflection index method
        // TODO: this needs to be fixed so it just returns the correct method
        final Method method = translateMethod(deploymentReflectionIndex, op);

        beanMethodMap.put(op.getIDLName(), new SkeletonStrategy(method));
        final OperationAnalysis setop = remoteAttrs[i].getMutatorAnalysis();
        if (setop != null) {
          EjbLogger.ROOT_LOGGER.debugf(
              "    %s\n                %s", setop.getJavaName(), setop.getIDLName());
          // translate to the deployment reflection index method
          // TODO: this needs to be fixed so it just returns the correct method
          final Method realSetmethod = translateMethod(deploymentReflectionIndex, setop);
          beanMethodMap.put(setop.getIDLName(), new SkeletonStrategy(realSetmethod));
        }
      }
    }

    final OperationAnalysis[] ops = remoteInterfaceAnalysis.getOperations();
    for (int i = 0; i < ops.length; i++) {
      EjbLogger.ROOT_LOGGER.debugf(
          "    %s\n                %s", ops[i].getJavaName(), ops[i].getIDLName());
      beanMethodMap.put(
          ops[i].getIDLName(),
          new SkeletonStrategy(translateMethod(deploymentReflectionIndex, ops[i])));
    }

    // Initialize repository ids of remote interface
    final String[] beanRepositoryIds = remoteInterfaceAnalysis.getAllTypeIds();

    // Create home method mappings for container invoker
    final InterfaceAnalysis homeInterfaceAnalysis;
    try {
      // TODO: change all this to use the deployment reflection index
      homeInterfaceAnalysis = InterfaceAnalysis.getInterfaceAnalysis(homeClass.getModuleClass());
    } catch (RMIIIOPViolationException e) {
      throw EjbLogger.ROOT_LOGGER.failedToAnalyzeRemoteInterface(
          e, componentDescription.getComponentName());
    }

    final Map<String, SkeletonStrategy> homeMethodMap = new HashMap<String, SkeletonStrategy>();

    final AttributeAnalysis[] attrs = homeInterfaceAnalysis.getAttributes();
    for (int i = 0; i < attrs.length; i++) {
      final OperationAnalysis op = attrs[i].getAccessorAnalysis();
      if (op != null) {
        EjbLogger.ROOT_LOGGER.debugf(
            "    %s\n                %s", op.getJavaName(), op.getIDLName());
        homeMethodMap.put(
            op.getIDLName(), new SkeletonStrategy(translateMethod(deploymentReflectionIndex, op)));
        final OperationAnalysis setop = attrs[i].getMutatorAnalysis();
        if (setop != null) {
          EjbLogger.ROOT_LOGGER.debugf(
              "    %s\n                %s", setop.getJavaName(), setop.getIDLName());
          homeMethodMap.put(
              setop.getIDLName(),
              new SkeletonStrategy(translateMethod(deploymentReflectionIndex, setop)));
        }
      }
    }

    final OperationAnalysis[] homeops = homeInterfaceAnalysis.getOperations();
    for (int i = 0; i < homeops.length; i++) {
      EjbLogger.ROOT_LOGGER.debugf(
          "    %s\n                %s", homeops[i].getJavaName(), homeops[i].getIDLName());
      homeMethodMap.put(
          homeops[i].getIDLName(),
          new SkeletonStrategy(translateMethod(deploymentReflectionIndex, homeops[i])));
    }

    // Initialize repository ids of home interface
    final String[] homeRepositoryIds = homeInterfaceAnalysis.getAllTypeIds();

    final EjbIIOPService service =
        new EjbIIOPService(
            beanMethodMap,
            beanRepositoryIds,
            homeMethodMap,
            homeRepositoryIds,
            settingsService.isUseQualifiedName(),
            iiopMetaData,
            module);
    final ServiceBuilder<EjbIIOPService> builder =
        serviceTarget.addService(
            componentDescription.getServiceName().append(EjbIIOPService.SERVICE_NAME), service);
    builder.addDependency(
        componentDescription.getCreateServiceName(),
        EJBComponent.class,
        service.getEjbComponentInjectedValue());
    builder.addDependency(homeView.getServiceName(), ComponentView.class, service.getHomeView());
    builder.addDependency(
        remoteView.getServiceName(), ComponentView.class, service.getRemoteView());
    builder.addDependency(CorbaORBService.SERVICE_NAME, ORB.class, service.getOrb());
    builder.addDependency(POARegistry.SERVICE_NAME, POARegistry.class, service.getPoaRegistry());
    builder.addDependency(
        CorbaPOAService.INTERFACE_REPOSITORY_SERVICE_NAME, POA.class, service.getIrPoa());
    builder.addDependency(
        CorbaNamingService.SERVICE_NAME, NamingContextExt.class, service.getCorbaNamingContext());
    builder.addDependency(
        IORSecConfigMetaDataService.SERVICE_NAME,
        IORSecurityConfigMetaData.class,
        service.getIORSecConfigMetaDataInjectedValue());
    builder.addDependency(
        Services.JBOSS_SERVICE_MODULE_LOADER,
        ServiceModuleLoader.class,
        service.getServiceModuleLoaderInjectedValue());

    // we need the arjunta transaction manager to be up, as it performs some initialization that is
    // required by the orb interceptors
    builder.addDependency(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER);
    builder.install();
  }
  private DeploymentInfo createServletConfig(
      final JBossWebMetaData mergedMetaData,
      final DeploymentUnit deploymentUnit,
      final Module module,
      final DeploymentClassIndex classReflectionIndex,
      final WebInjectionContainer injectionContainer,
      final ComponentRegistry componentRegistry,
      final ScisMetaData scisMetaData,
      final VirtualFile deploymentRoot)
      throws DeploymentUnitProcessingException {
    try {
      mergedMetaData.resolveAnnotations();
      final DeploymentInfo d = new DeploymentInfo();
      d.setContextPath(mergedMetaData.getContextRoot());
      if (mergedMetaData.getDescriptionGroup() != null) {
        d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName());
      }
      d.setDeploymentName(deploymentUnit.getName());
      d.setResourceLoader(new DeploymentResourceLoader(deploymentRoot));
      d.setClassLoader(module.getClassLoader());
      final String servletVersion = mergedMetaData.getServletVersion();
      if (servletVersion != null) {
        d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + ""));
        d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + ""));
      } else {
        d.setMajorVersion(3);
        d.setMinorVersion(1);
      }

      // for 2.2 apps we do not require a leading / in path mappings
      boolean is22OrOlder;
      if (d.getMajorVersion() == 1) {
        is22OrOlder = true;
      } else if (d.getMajorVersion() == 2) {
        is22OrOlder = d.getMinorVersion() < 3;
      } else {
        is22OrOlder = false;
      }

      HashMap<String, TagLibraryInfo> tldInfo =
          createTldsInfo(deploymentUnit, classReflectionIndex, componentRegistry, d);
      HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData);

      JspServletBuilder.setupDeployment(
          d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(injectionContainer));
      d.setJspConfigDescriptor(
          new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values()));
      d.setDefaultServletConfig(new DefaultServletConfig(true, Collections.<String>emptySet()));

      // default JSP servlet
      final ServletInfo jspServlet =
          new ServletInfo("Default JSP Servlet", JspServlet.class)
              .addMapping("*.jsp")
              .addMapping("*.jspx")
              .addInitParam("development", "false"); // todo: make configurable
      d.addServlet(jspServlet);

      final Set<String> jspPropertyGroupMappings = propertyGroups.keySet();
      for (final String mapping : jspPropertyGroupMappings) {
        jspServlet.addMapping(mapping);
      }

      d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry));

      final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>();

      if (mergedMetaData.getServletMappings() != null) {
        for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) {
          List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName());
          if (list == null) {
            servletMappings.put(mapping.getServletName(), list = new ArrayList<>());
          }
          list.add(mapping);
        }
      }
      final Set<String> seenMappings = new HashSet<>(jspPropertyGroupMappings);
      if (mergedMetaData.getServlets() != null) {
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
          final ServletInfo s;

          if (servlet.getJspFile() != null) {
            // TODO: real JSP support
            s = new ServletInfo(servlet.getName(), JspServlet.class);
            s.addHandlerChainWrapper(new JspFileWrapper(servlet.getJspFile()));
          } else {
            Class<? extends Servlet> servletClass =
                (Class<? extends Servlet>)
                    classReflectionIndex.classIndex(servlet.getServletClass()).getModuleClass();
            ComponentRegistry.ComponentManagedReferenceFactory creator =
                componentRegistry.getComponentsByClass().get(servletClass);
            if (creator != null) {
              InstanceFactory<Servlet> factory = createInstanceFactory(creator);
              s = new ServletInfo(servlet.getName(), servletClass, factory);
            } else {
              s = new ServletInfo(servlet.getName(), servletClass);
            }
          }
          s.setAsyncSupported(servlet.isAsyncSupported())
              .setJspFile(servlet.getJspFile())
              .setEnabled(servlet.isEnabled());
          if (servlet.getRunAs() != null) {
            s.setRunAs(servlet.getRunAs().getRoleName());
          }
          if (servlet
              .getLoadOnStartupSet()) { // todo why not cleanup api and just use int everywhere
            s.setLoadOnStartup(servlet.getLoadOnStartupInt());
          }

          List<ServletMappingMetaData> mappings = servletMappings.get(servlet.getName());
          if (mappings != null) {
            for (ServletMappingMetaData mapping : mappings) {
              for (String pattern : mapping.getUrlPatterns()) {
                if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) {
                  pattern = "/" + pattern;
                }
                if (!seenMappings.contains(pattern)) {
                  s.addMapping(pattern);
                  seenMappings.add(pattern);
                }
              }
            }
          }
          if (servlet.getInitParam() != null) {
            for (ParamValueMetaData initParam : servlet.getInitParam()) {
              if (!s.getInitParams().containsKey(initParam.getParamName())) {
                s.addInitParam(initParam.getParamName(), initParam.getParamValue());
              }
            }
          }
          if (servlet.getServletSecurity() != null) {
            ServletSecurityInfo securityInfo = new ServletSecurityInfo();
            s.setServletSecurityInfo(securityInfo);
            securityInfo
                .setEmptyRoleSemantic(
                    servlet.getServletSecurity().getEmptyRoleSemantic()
                            == EmptyRoleSemanticType.PERMIT
                        ? PERMIT
                        : DENY)
                .setTransportGuaranteeType(
                    transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee()))
                .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed());
            if (servlet.getServletSecurity().getHttpMethodConstraints() != null) {
              for (HttpMethodConstraintMetaData method :
                  servlet.getServletSecurity().getHttpMethodConstraints()) {
                securityInfo.addHttpMethodSecurityInfo(
                    new HttpMethodSecurityInfo()
                        .setEmptyRoleSemantic(
                            method.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT
                                ? PERMIT
                                : DENY)
                        .setTransportGuaranteeType(
                            transportGuaranteeType(method.getTransportGuarantee()))
                        .addRolesAllowed(method.getRolesAllowed())
                        .setMethod(method.getMethod()));
              }
            }
          }
          if (servlet.getSecurityRoleRefs() != null) {
            for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) {
              s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink());
            }
          }

          d.addServlet(s);
        }
      }

      if (mergedMetaData.getFilters() != null) {
        for (final FilterMetaData filter : mergedMetaData.getFilters()) {
          Class<? extends Filter> filterClass =
              (Class<? extends Filter>)
                  classReflectionIndex.classIndex(filter.getFilterClass()).getModuleClass();
          ComponentRegistry.ComponentManagedReferenceFactory creator =
              componentRegistry.getComponentsByClass().get(filterClass);
          FilterInfo f;
          if (creator != null) {
            InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator);
            f = new FilterInfo(filter.getName(), filterClass, instanceFactory);
          } else {
            f = new FilterInfo(filter.getName(), filterClass);
          }
          f.setAsyncSupported(filter.isAsyncSupported());
          d.addFilter(f);

          if (filter.getInitParam() != null) {
            for (ParamValueMetaData initParam : filter.getInitParam()) {
              f.addInitParam(initParam.getParamName(), initParam.getParamValue());
            }
          }
        }
      }
      if (mergedMetaData.getFilterMappings() != null) {
        for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) {
          if (mapping.getUrlPatterns() != null) {
            for (String url : mapping.getUrlPatterns()) {
              if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) {
                url = "/" + url;
              }
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {

                  d.addFilterUrlMapping(
                      mapping.getFilterName(),
                      url,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterUrlMapping(
                    mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
          if (mapping.getServletNames() != null) {
            for (String servletName : mapping.getServletNames()) {
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {
                  d.addFilterServletNameMapping(
                      mapping.getFilterName(),
                      servletName,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterServletNameMapping(
                    mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
        }
      }

      if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) {
        for (final Map.Entry<ServletContainerInitializer, Set<Class<?>>> sci :
            scisMetaData.getHandlesTypes().entrySet()) {
          final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory =
              new ImmediateInstanceFactory<>(sci.getKey());
          d.addServletContainerInitalizer(
              new ServletContainerInitializerInfo(
                  sci.getKey().getClass(), instanceFactory, sci.getValue()));
        }
      }

      if (mergedMetaData.getListeners() != null) {
        for (ListenerMetaData listener : mergedMetaData.getListeners()) {
          addListener(classReflectionIndex, componentRegistry, d, listener);
        }
      }
      if (mergedMetaData.getContextParams() != null) {
        for (ParamValueMetaData param : mergedMetaData.getContextParams()) {
          d.addInitParameter(param.getParamName(), param.getParamValue());
        }
      }

      if (mergedMetaData.getWelcomeFileList() != null
          && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) {
        d.addWelcomePages(mergedMetaData.getWelcomeFileList().getWelcomeFiles());
      } else {
        d.addWelcomePages("index.html", "index.htm", "index.jsp");
      }

      if (mergedMetaData.getErrorPages() != null) {
        for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) {
          final ErrorPage errorPage;
          if (page.getExceptionType() == null || page.getExceptionType().isEmpty()) {
            errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode()));
          } else {
            errorPage =
                new ErrorPage(
                    page.getLocation(),
                    (Class<? extends Throwable>)
                        classReflectionIndex.classIndex(page.getExceptionType()).getModuleClass());
          }
          d.addErrorPages(errorPage);
        }
      }

      if (mergedMetaData.getMimeMappings() != null) {
        for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) {
          d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType()));
        }
      }

      if (mergedMetaData.getSecurityConstraints() != null) {
        for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) {
          SecurityConstraint securityConstraint =
              new SecurityConstraint()
                  .setTransportGuaranteeType(
                      transportGuaranteeType(constraint.getTransportGuarantee()))
                  .addRolesAllowed(constraint.getRoleNames());

          if (constraint.getAuthConstraint() == null) {
            // no auth constraint means we permit the empty roles
            securityConstraint.setEmptyRoleSemantic(PERMIT);
          }

          if (constraint.getResourceCollections() != null) {
            for (final WebResourceCollectionMetaData resourceCollection :
                constraint.getResourceCollections()) {
              securityConstraint.addWebResourceCollection(
                  new WebResourceCollection()
                      .addHttpMethods(resourceCollection.getHttpMethods())
                      .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions())
                      .addUrlPatterns(resourceCollection.getUrlPatterns()));
            }
          }
          d.addSecurityConstraint(securityConstraint);
        }
      }
      final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig();
      if (loginConfig != null) {
        String authMethod = authMethod(loginConfig.getAuthMethod());
        if (loginConfig.getFormLoginConfig() != null) {
          d.setLoginConfig(
              new LoginConfig(
                  authMethod,
                  loginConfig.getRealmName(),
                  loginConfig.getFormLoginConfig().getLoginPage(),
                  loginConfig.getFormLoginConfig().getErrorPage()));
        } else {
          d.setLoginConfig(new LoginConfig(authMethod, loginConfig.getRealmName()));
        }
      }

      d.addSecurityRoles(mergedMetaData.getSecurityRoleNames());

      if (mergedMetaData.getSecurityDomain() != null) {

        String contextId = deploymentUnit.getName();
        if (deploymentUnit.getParent() != null) {
          contextId = deploymentUnit.getParent().getName() + "!" + contextId;
        }
        d.addOuterHandlerChainWrapper(
            SecurityContextCreationHandler.wrapper(mergedMetaData.getSecurityDomain()));
        d.addDispatchedHandlerChainWrapper(
            SecurityContextAssociationHandler.wrapper(
                mergedMetaData.getPrincipalVersusRolesMap(), contextId));
      }

      // Setup an deployer configured ServletContext attributes
      final List<ServletContextAttribute> attributes =
          deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY);
      for (ServletContextAttribute attribute : attributes) {
        d.addServletContextAttribute(attribute.getName(), attribute.getValue());
      }

      if (mergedMetaData.getLocalEncodings() != null
          && mergedMetaData.getLocalEncodings().getMappings() != null) {
        for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) {
          d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding());
        }
      }

      return d;
    } catch (ClassNotFoundException e) {
      throw new DeploymentUnitProcessingException(e);
    }
  }