/*
newFromPushedData - creating new SW for next dispatch/Runnable.
Xferred context data and classloaders to new SW.
971533
static ServiceWrapper newFromPushedData (AsyncContextImpl asynContext) { // PM90834: added method
      ServiceWrapper orginalServiceWrapper = asynContext.serviceWrapper;
      ServiceWrapper sw = new ServiceWrapper(asynContext);
      sw.setContextData(orginalServiceWrapper.getContextData());
      sw.originalCL = orginalServiceWrapper.originalCL;
      sw.newCL= orginalServiceWrapper.newCL;             //PI92334 newCL is the current thread's classLoader

      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) {           
          logger.logp(Level.FINEST, CLASS_NAME, "newFromPushedData","created ServiceWrapper [" + sw +"] , original ServiceWrapper ["+orginalServiceWrapper+"]");
          logger.logp(Level.FINEST, CLASS_NAME, "newFromPushedData","transferred to new ServiceWrapper, originalCL [" + sw.originalCL +"] , newCL ["+ sw.newCL +"]");
      }

      return sw;
  }
765090
public TransactionQueueData add(TransactionQueueData data) {
        return new TransactionQueueData
            (null,
             Math.min(mSnapshotStart, data.mSnapshotStart),
             Math.max(mSnapshotEnd, data.mSnapshotEnd),
             mQueueSize + data.mQueueSize,
             mThreadCount + data.mThreadCount,
             mServicingCount + data.mServicingCount,
             Math.max(mPeakQueueSize, data.mPeakQueueSize),
             Math.max(mPeakThreadCount, data.mPeakThreadCount),
             Math.max(mPeakServicingCount, data.mPeakServicingCount),
             mTotalEnqueueAttempts + data.mTotalEnqueueAttempts,
             mTotalEnqueued + data.mTotalEnqueued,
             mTotalServiced + data.mTotalServiced,
             mTotalExpired + data.mTotalExpired,
             mTotalServiceExceptions + data.mTotalServiceExceptions,
             mTotalUncaughtExceptions + data.mTotalUncaughtExceptions,
             mTotalQueueDuration + data.mTotalQueueDuration,
             mTotalServiceDuration + data.mTotalServiceDuration
             );
    }
469463
public boolean add(SpdData data) {
        if (data == null)
            return false;
        if (data instanceof SpdDouble) {
            return super.add(data);
        } else {
            return false;
        }
    }
300557
public final InternalFactHandle newFactHandle(int id,
                                                  Object object,
                                                  ObjectTypeConf conf,
                                                  InternalWorkingMemory workingMemory,
                                                  WorkingMemoryEntryPoint wmEntryPoint) {
        return newFactHandle( id,
                              object,
                              getNextRecency(),
                              conf,
                              workingMemory,
                              wmEntryPoint );
    }
333427
@Override
    public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress)
            throws IOException {
        throw new IOException("Create not supported for EmoFileSystem: " + f);
    }
378827
protected void saveNewFunctionToFile(final String newFunctionClass) throws Exception {
        info("");
        info(SAVE_FILE);

        final File packageDir = getPackageDir();

        final File targetFile = getTargetFile(packageDir);

        createPackageDirIfNotExist(packageDir);

        saveToTargetFile(targetFile, newFunctionClass);

        info(SAVE_FILE_DONE + targetFile.getAbsolutePath());
    }
276667
public static GenericResponseBuilderFactory newInstance() {
    ServiceLoader<GenericResponseBuilderFactory> clientBuilderFactoryLoader =
        ServiceLoader.load(GenericResponseBuilderFactory.class);

    Iterator<GenericResponseBuilderFactory> iterator = clientBuilderFactoryLoader.iterator();

    if (!iterator.hasNext()) {
      throw new IllegalStateException(
          "An implementation of GenericResponseBuilderFactory was not found");
    }

    return iterator.next();
  }
799283
protected void restoreFromContinuationData(Map<String, Object> data) {
        //noinspection unchecked
        localProxyBuilder.set((FactoryBuilderSupport) data.get("proxyBuilder"));
        //noinspection unchecked
        contexts.set((LinkedList<Map<String, Object>>) data.get("contexts"));
    }
162144
public void pushContextData(){
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "pushContextData");
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Setting the original thread's class loader and saving off the current one");
        }
        //Set the original Context Class Loader
        this.currentCL = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(originalCL);
                return cl;
            }
        });
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Saving the current thread's context data");
        }
        //We are going to save off the current threads component metadata and context
        //We will restore this when we pop later on
        this.currentCD = saveContextData();
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Setting the original thread's context data : " + this.originalCD);
        }
        if (this.originalCD != null) {

            //Push the data onto the thread that we have hooks into
            ComponentMetaDataAccessorImpl cmdai = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor();
            ComponentMetaData cmd = (ComponentMetaData) this.originalCD.get(ComponentMetaData);
            if (cmd != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Calling begin on the ComponentMetaData : " + cmdai + ", with : " + cmd);
                }
                cmdai.beginContext(cmd);
            }
            
            //Each producer service of the Transfer service is accessed in order to get the thread context data
          Iterator<ITransferContextService> TransferIterator = com.ibm.ws.webcontainer.osgi.WebContainer.getITransferContextServices();
          if (TransferIterator != null) {
            while(TransferIterator.hasNext()){
              ITransferContextService tcs = TransferIterator.next();
              if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                  Tr.debug(tc, "Calling restoreState on: " + tcs);
              }
              tcs.restoreState(this.originalCD);
            }
          }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "pushContextData");
        }
    }
558937
private static RunContext createBottomContext() {
    File spockUserHome = SpockUserHomeUtil.getSpockUserHome();
    DelegatingScript script = new ConfigurationScriptLoader(spockUserHome).loadAutoDetectedScript();
    List<Class<?>> classes = new ExtensionClassesLoader().loadClassesFromDefaultLocation();
    return new RunContext("default", spockUserHome, script, classes);
  }
214582
@Override
    public Mp newInstance() throws DempsyException {
        try {
            return newMp.get();
        } catch(final RuntimeException rte) {
            throw new DempsyException(rte, true);
        }
    }
791578
@SuppressWarnings("all")
	protected Object newInstance(String className) {
		log.debug("Loading class: {}", className);
		Object instance = null;
		Class<?> clazz = null;
		if ("".equals(className) || className == null)
			return instance;
		try {
			// check for special DS class aliases
			if (className.length() == 3) {
				className = classAliases.get(className);
			}
			if (className.startsWith("flex.")) {
				// Use Red5 compatibility class instead
				className = "org.red5.compatibility." + className;
				log.debug("Modified classname: {}", className);
			}
			if (!classAllowed(className)) {
				log.error("Class creation is not allowed {}", className);
			} else {
				clazz = Thread.currentThread().getContextClassLoader()
						.loadClass(className);
				instance = clazz.newInstance();
			}
		} catch (InstantiationException iex) {
			try {
				// check for default ctor
				clazz.getConstructor(null);
				log.error("Error loading class: {}", className);
			} catch (NoSuchMethodException nse) {
				log.error(
						"Error loading class: {}; this can be resolved by adding a default constructor to your class",
						className);
			}
			log.debug("Exception was: {}", iex);
		} catch (Exception ex) {
			log.error("Error loading class: {}", className);
			log.debug("Exception was: {}", ex);
		}
		return instance;
	}
1352413
@Override
	public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
			throws IllegalAccessException, InstantiationException, IOException {

		String bundleName = toBundleName(baseName, locale);
		ResourceBundle bundle = null;
		if (format.equals("java.class")) {
			try {
				@SuppressWarnings("unchecked")
				Class<? extends ResourceBundle> bundleClass = (Class<? extends ResourceBundle>) loader
						.loadClass(bundleName);

				// If the class isn't a ResourceBundle subclass, throw a
				// ClassCastException.
				if (ResourceBundle.class.isAssignableFrom(bundleClass)) {
					bundle = bundleClass.newInstance();
				} else {
					throw new ClassCastException(bundleClass.getName() + " cannot be cast to ResourceBundle");
				}
			} catch (ClassNotFoundException e) {
			}
		} else if (format.equals("java.properties")) {
			final String resourceName = toResourceName(bundleName, "properties");
			final ClassLoader classLoader = loader;
			final boolean reloadFlag = reload;
			InputStream stream = null;
			Reader rd = null;
			try {
				stream = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() {
					public InputStream run() throws IOException {
						InputStream is = null;
						if (reloadFlag) {
							URL url = classLoader.getResource(resourceName);
							if (url != null) {
								URLConnection connection = url.openConnection();
								if (connection != null) {
									// Disable caches to get fresh
									// data for
									// reloading.
									connection.setUseCaches(false);
									is = connection.getInputStream();
								}
							}
						} else {
							is = classLoader.getResourceAsStream(resourceName);
						}
						return is;
					}
				});
			} catch (PrivilegedActionException e) {
				throw (IOException) e.getException();
			}
			if (stream != null) {
				try {
					rd = new InputStreamReader(stream, charset);
					bundle = new PropertyResourceBundle(rd);
				} finally {
					IOUtils.close(rd);
					IOUtils.close(stream);
				}
			}
		} else {
			throw new IllegalArgumentException("unknown format: " + format);
		}
		return bundle;
	}
1319764
public boolean process(final byte[] newData) {
        if (newData != null) {
            buffer.write(newData);
        }

        boolean done = false;
        while (!done) {
            final int index = buffer.getReaderIndex();
            final State currentState = state;
            state = actions[state.ordinal()].apply(buffer);
            done = state == currentState && buffer.getReaderIndex() == index;
        }

        return state == State.DONE;
    }
714666
@Override
    public <T> T getInjectionTargetContextData(Class<T> data)
    {
        if (data.isAssignableFrom(getClass()))
            return data.cast(this);

        // Return null if requested context data is not available
        return null;
    }
202036
@Override
    public Object create(ActionParameter argument, Context context, ParameterFactories engine) {
        if (argument.getRawType().equals(Context.class)) {
            return context;
        }

        // Check whether we have a ParameterFactory that can handle the creation.
        Set<Class> handled = engine.getTypesHandledByFactories();
        if (handled.contains(argument.getRawType())) {
            return engine.newInstance(context, argument.getRawType());
        }

        if (argument.getRawType().equals(Request.class)) {
            return context.request();
        }

        if (argument.getRawType().equals(SessionCookie.class)) {
            return context.session();
        }

        if (argument.getRawType().equals(FlashCookie.class)) {
            return context.flash();
        }

        if (argument.getRawType().equals(Cookie.class)) {
            if (!Strings.isNullOrEmpty(argument.getName())) {
                return context.cookie(argument.getName());
            } else {
                throw new IllegalArgumentException("Missing cookie's name set in the @HttpParameter annotation");
            }
        }

        if (argument.getRawType().equals(Route.class)) {
            return context.route();
        }

        if (argument.getRawType().equals(BufferedReader.class) || argument.getRawType().equals(Reader.class)) {
            try {
                return context.reader();
            } catch (IOException e) {
                throw new IllegalArgumentException("Cannot inject the reader object in the @HttpParameter injected " +
                        "parameter", e);
            }
        }

        // Ran out of possibilities based on the type, check for the request scope and then HTTP headers
        if (Strings.isNullOrEmpty(argument.getName())) {
            throw new IllegalArgumentException("Cannot inject the value of a HTTP header and request scope value in " +
                    "the @HttpParameter - header's name not defined");
        } else {
            final Object requestScopeValue = context.request().data().get(argument.getName());
            if (requestScopeValue != null) {
                return requestScopeValue;
            } else {
                if (context.header(argument.getName()) != null || argument.getDefaultValue() != null) {
                    return engine.convertValues(context.headers(argument.getName()), argument.getRawType(),
                            argument.getGenericType(), argument.getDefaultValue());
                } else {
                    // No value.
                    if (List.class.isAssignableFrom(argument.getRawType())) {
                        return Collections.emptyList();
                    }
                    if (Set.class.isAssignableFrom(argument.getRawType())) {
                        return Collections.emptySet();
                    }
                    if (Collections.class.isAssignableFrom(argument.getRawType())) {
                        return Collections.emptyList();
                    }
                    return null;
                }
            }
        }

    }
676727
@Override
  public void doPushProfileAnswer(ServerCxDxSession appSession, JPushProfileRequest request, JPushProfileAnswer answer)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    logger.info("Diameter Cx/Dx Session Factory :: doPushProfileAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer});
  }