/*
(non-Javadoc)

@see
com.ibm.ws.webcontainer.extension.WebExtensionProcessor#createServletWrapper
(com.ibm.ws.webcontainer.servlet.ServletConfig)
337228
public IServletWrapper createServletWrapper(IServletConfig config) throws Exception
  {
    ServletWrapper wrapper = new com.ibm.ws.webcontainer.osgi.servlet.ServletWrapper(extensionContext);

    if (config == null)
      return wrapper;
    try
    {
      wrapper.initialize(config);
    }
    catch (Throwable e)
    {
      // Might be more serious....so first log
      e.printStackTrace(System.out);
    }

    return wrapper;
  }
826875
@Override
  public <T extends Servlet> T createServlet(Class<T> classToCreate) throws ServletException {
      logger.logp(Level.FINE, CLASS_NAME, "createServlet", "called for class: " + classToCreate);
      
      return super.createServlet(classToCreate);
  }
1152928
@Override
    public final EJSWrapperCommon getWrapper(BeanId id) // f111627
    throws CSIException, RemoteException
    {
        return container.getWrapper(id);
    }
267217
@Override
    public Plugin create(final PluginWrapper pluginWrapper) {
        String pluginClassName = pluginWrapper.getDescriptor().getPluginClass();
        log.debug("Create instance for plugin '{}'", pluginClassName);

        Class<?> pluginClass;
        try {
            pluginClass = pluginWrapper.getPluginClassLoader().loadClass(pluginClassName);
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
            return null;
        }

        // once we have the class, we can do some checks on it to ensure
        // that it is a valid implementation of a plugin.
        int modifiers = pluginClass.getModifiers();
        if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)
                || (!Plugin.class.isAssignableFrom(pluginClass))) {
            log.error("The plugin class '{}' is not valid", pluginClassName);
            return null;
        }

        // create the plugin instance
        try {
            Constructor<?> constructor = pluginClass.getConstructor(PluginWrapper.class);
            return (Plugin) constructor.newInstance(pluginWrapper);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
353854
public XmlWrapperParser createParser(InputStream inputStream) {
        try {
			return new XmlWrapperParser(this, inputStream, getSupportedFormat());
		} catch (Exception e) {
			e.printStackTrace();
			throw new KriptonRuntimeException(e);
		}
	}
180164
public ServletMappingType<WebAppDescriptor> getOrCreateServletMapping()
   {
      List<Node> nodeList = model.get("servlet-mapping");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new ServletMappingTypeImpl<WebAppDescriptor>(this, "servlet-mapping", model, nodeList.get(0));
      }
      return createServletMapping();
   }
337644
protected synchronized void createTarget(Servlet s) throws InjectionException{ //596191
        if (s instanceof SingleThreadModel) {
            isSTM = true;
            servletConfig.setSingleThreadModelServlet(isSTM);
            target = new SingleThreadModelServlet(s.getClass());
        } else {
            target = s;
        }
    }
515946
protected ConfigurationWrapper getConfigurationWrapper(InjectionPoint injectionPoint) {
		Configuration configuration = injectionPoint.getAnnotated().getAnnotation(Configuration.class);
		return WrapperFactory.wrap(configuration);
	}
487860
public static ServletContext wrap(final ServletContext pContext, final Object[] pDelegates, final ClassLoader pLoader) {
        ClassLoader cl = pLoader != null ? pLoader : Thread.currentThread().getContextClassLoader();

        // TODO: Create a "static" mapping between methods in the ServletContext
        // and the corresponding delegate

        // TODO: Resolve super-invokations, to delegate to next delegate in
        // chain, and finally invoke pContext  

        return (ServletContext) Proxy.newProxyInstance(cl, new Class[] {ServletContext.class}, new InvocationHandler() {
            public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {
                // TODO: Test if any of the delegates should receive, if so invoke

                // Else, invoke on original object
                return pMethod.invoke(pContext, pArgs);
            }
        });
    }
1185611
public synchronized Servlet getServlet()
        throws ServletException
    {
        // Handle previous unavailability
        if (_unavailable!=0)
        {
            if (_unavailable<0 || _unavailable>0 && System.currentTimeMillis()<_unavailable)
                throw _unavailableEx;
            _unavailable=0;
            _unavailableEx=null;
        }
        
        try
        {
            if (_servlets!=null)
            {
                Servlet servlet=null;
                if (_servlets.size()==0)
                {
                    servlet= (Servlet)newInstance();
                    if (_config==null)
                    	_config=new Config();
                    initServlet(servlet,_config);
                }
                else
                    servlet = (Servlet)_servlets.pop();

                return servlet;
            }
            
            if (_servlet==null)
            {
                _servlet=(Servlet)newInstance();
                if (_config==null)
                	_config=new Config();
                initServlet(_servlet,_config);
            }
        
            return _servlet;
        }
        catch(UnavailableException e)
        {
            _servlet=null;
            _config=null;
            return makeUnavailable(e);
        }
        catch(ServletException e)
        {
            _servlet=null;
            _config=null;
            throw e;
        }
        catch(Throwable e)
        {
            _servlet=null;
            _config=null;
            throw new ServletException("init",e);
        }    
    }
570931
public org.apache.commons.configuration.Configuration getConfiguration(ConfigurationWrapper wrapper) {
		// get input streams
		List<ISource> sources = this.locate(wrapper);
		
		// create configuration combiner
		OverrideCombiner combiner = new OverrideCombiner();
		CombinedConfiguration combined = new CombinedConfiguration(combiner);
		
		// combine configurations
		for(ISource source : sources) {
			// determine mime type in order to create proper commons object
			SupportedType type = MimeGuesser.guess(source);
			
			// if the source isn't available, continue
			if(!source.available()) {
				continue;
			}
			
			InputStream stream = source.stream();
			
			// load properties based on MIME type
			// todo: update for more commons-configuration
			// supported mime types
			if(SupportedType.XML.equals(type)) {
				XMLConfiguration xmlConfiguration = new XMLConfiguration();
				try {
					xmlConfiguration.load(stream);
					combined.addConfiguration(xmlConfiguration);
				} catch(ConfigurationException e) {
					this.logger.error("An error occurred while reading XML properties: {}", e.getMessage());	
				}
			} else {
				PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
				try {
					propertiesConfiguration.load(stream);
					combined.addConfiguration(propertiesConfiguration);
				} catch (ConfigurationException e) {
					this.logger.error("An error occurred while reading properties: {}", e.getMessage());
				}				
			}
			
			// close stream
			try {
				stream.close();
			} catch (IOException e) {
				this.logger.trace("Could not close old stream: {}", stream);
			}
			
			// leave on first loop if merge is on
			if(!wrapper.merge()) {
				break;
			}
		}		
		// return configuration
		return combined;
	}
479970
public DrawerBuilder withAdapterWrapper(@NonNull RecyclerView.Adapter adapterWrapper) {
        if (mAdapter == null) {
            throw new RuntimeException("this adapter has to be set in conjunction to a normal adapter which is used inside this wrapper adapter");
        }
        this.mAdapterWrapper = adapterWrapper;
        return this;
    }
1165788
public void init() throws ServletException {
		ServletContext sc = this.getServletContext();
		String configList = this.getServletConfig().getInitParameter("configList");
		String[] configs = StringUtil.split(configList, ",");
		for (int i = 0; i < configs.length; i++) {
			Debug.logVerbose("[JdonFramework] locate a configuration in web.xml :" + configs[i], module);
			css.prepare(configs[i], new ServletContextWrapper(sc));
		}
	}
384587
public static EmbeddedJettyBuilder.ServletContextHandlerBuilder addWicketHandler(EmbeddedJettyBuilder embeddedJettyBuilder,
                                                                                     String contextPath,
                                                                                     EventListener springContextloader,
                                                                                     Class<? extends WebApplication> wicketApplication,
                                                                                     boolean development){
        EmbeddedJettyBuilder.ServletContextHandlerBuilder wicketHandler = embeddedJettyBuilder.createRootServletContextHandler(contextPath)
                .setClassLoader(Thread.currentThread().getContextClassLoader())
                .addEventListener(springContextloader);
        return addWicketHandler(wicketHandler, wicketApplication, development);
    }
876762
private static Object makeClientWrapper(Class<?> clientType,String clientId,Class<? extends InvokeHandler> handlerClass){
        String clientName = clientType.getSimpleName();
        long id = WRAPPER_COUNTER.getAndIncrement();
        if(clientType==DCW.class){
            throw new IllegalArgumentException("not support generate wrapper for interface "+clientName);
        }
        if(!clientType.isInterface()){
            throw new IllegalArgumentException("only support interface to generate wrapper,but type "+clientName+" is not interface");
        }
        JavassistClassGenerator generator = JavassistClassGenerator.newInstance(clientType.getClassLoader());
        generator.addInterface(clientType.getName());
        generator.addInterface(DCW.class.getName());
        StringBuilder className = new StringBuilder();
        className.append(clientType.getSimpleName()).append("$DCW").append(id);
        generator.setClassName(className.toString());
        Method[] methods = clientType.getDeclaredMethods();
        StringBuilder methodCode = new StringBuilder();
        for(Method method:methods){
            methodCode.append("public ");
            Class<?> returnType = method.getReturnType();
            Class<?>[] argsTypes = method.getParameterTypes();
            if(returnType== Void.TYPE){
                methodCode.append("void ");
            }else{
                methodCode.append(returnType.getName()).append(" ");
            }
            methodCode.append(method.getName()).append("(");
            //append arguments
            if(argsTypes.length!=0){
                for(int i=0;i<argsTypes.length;i++){
                    methodCode.append(argsTypes[i].getName()).append(" arg").append(i).append(",");
                }
                methodCode.setLength(methodCode.length()-1);
            }
            Class<?>[] exceptionTypes = method.getExceptionTypes();
            methodCode.append(")");
            if(exceptionTypes.length!=0){
                methodCode.append("throws ");
                for(Class<?> exceptionType:exceptionTypes){
                    methodCode.append(exceptionType.getName()).append(",");
                }
                methodCode.setLength(methodCode.length()-1);
            }
            methodCode.append("{");
            methodCode.append("try{");
            //append method body
            //handle invoke before
            if(argsTypes.length==0){
                methodCode.append("invokeHandler.beforeInvoke(clientType,\"" + method.getName() + "\",null);");
            }else{
                methodCode.append("invokeHandler.beforeInvoke(clientType,\"" + method.getName() + "\",$args);");
            }
            //handle invoke complete
            if(returnType== Void.TYPE){
                methodCode.append("(($w)clientRef).").append(method.getName()).append("($$);");
                if(argsTypes.length==0){
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",null,null);");
                }else{
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",null,$args);");
                }
            }else{
                methodCode.append("Object result=(($w)clientRef).").append(method.getName()).append("($$);");
                if(argsTypes.length==0){
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",(Object)result,null);");
                }else{
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",(Object)result,$args);");
                }
                methodCode.append("return ($r)result;");
            }
            methodCode.append("}catch(Throwable t){");
            //handle invoke exception
            if(argsTypes.length==0){
                methodCode.append("invokeHandler.caughtException(clientType,\"" + method.getName() + "\",t,null);");
            }else{
                methodCode.append("invokeHandler.caughtException(clientType,\"" + method.getName() + "\",t,$args);");
            }

            methodCode.append("throw new ").append(InvokeTargetException.class.getName()).append("(clientType,\""+method.getName()+"\",t);");
            methodCode.append("}");
            methodCode.append("}");
            generator.addMethod(methodCode.toString());
            methodCode.setLength(0);
        }
        generator.addField("public static "+clientType.getName()+" clientRef;");
        generator.addField("public static "+InvokeHandler.class.getName()+" invokeHandler;");
        generator.addField("public static "+Class.class.getName()+" clientType;");
        Class<?> clazz = generator.toClass();
        try {
            ReferenceConfig config = new ReferenceConfig();
            config.setId(clientId);
            config.setCheck(false);
            config.setInterface(clientType.getName());
            clazz.getField("clientRef").set(null,config.get());
            if(!HANDLER_CACHE.containsKey(handlerClass)){
                HANDLER_CACHE.putIfAbsent(handlerClass,handlerClass.newInstance());
            }
            clazz.getField("invokeHandler").set(null,HANDLER_CACHE.get(handlerClass));
            clazz.getField("clientType").set(null,clientType);
            return clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
216048
public static JClassLoaderWrapper create(ClassLoader loader)
  {
    JClassLoaderWrapper jLoader = _localClassLoader.getLevel(loader);
    
    if (jLoader == null) {
      jLoader = new JClassLoaderWrapper(loader);
      _localClassLoader.set(jLoader, loader);
    }

    return jLoader;
  }
30334
public final SC registerServlet(Class<? extends HttpServlet> servletClass) {

        WebServlet webServlet = servletClass.getAnnotation(WebServlet.class);

        if (webServlet == null)
            throw new IllegalArgumentException(String.format("Missing annotation '%s' for class '%s'", WebFilter.class.getName(), servletClass.getName()));

        String[] urlPatterns = webServlet.value();

        if (urlPatterns.length == 0)
            urlPatterns = webServlet.urlPatterns();

        if (urlPatterns.length == 0)
            throw new IllegalArgumentException(String.format("Missing pattern mapping for '%s'", servletClass.getName()));

        for (String urlPattern : urlPatterns) {
            registerServlet(servletClass, urlPattern);
        }

        return (SC) this;
    }