/*
Process Conduits created by Trace and Message due to the CollectorManagerPipelineConfigurator
and CollectorManagerPipelineUtils.
344486
private void processInitializedConduits(Source source) {
        String sourceId = CollectorManagerUtils.getSourceId(source);
        String sourceName = source.getSourceName();
        /*
         * Check that the current source initialized is Log/Message and Trace.
         * These are the unique special sources along with their respective Conduits/BufferManagers
         * that were started before OSGI and thusly were not configured via 'the osgi' way that CollectorManager
         * had in place before the JSON Logging work.
         */
        if (sourceName.equals(CollectorConstants.MESSAGES_SOURCE) || sourceName.equals(CollectorConstants.TRACE_SOURCE)) {
            //Make sure we have a bundleContext, we need this to play with osgi (i.e. register/listen to services)
            if (bundleContext == null) {
                retrieveBundleContext();
            }
            /*
             * We should really check if the source and conduit/bufferManager is already set into the
             * SourceManager and BufferManager maps. If so, no need to continue the rest of this method.
             */
            if (sourceMgrs.containsKey(sourceId) && bufferManagerMap.containsKey(sourceId)) {
                return;
            }

            ServiceReference<BufferManager>[] servRefs;
            try {
                servRefs = (ServiceReference<BufferManager>[]) bundleContext.getServiceReferences(BufferManager.class.getName(), null);
                if (servRefs != null) {
                    for (ServiceReference<BufferManager> servRef : servRefs) {
                        /*
                         * Ensure that the Conduit/BufferManager retrieved is the right one for the source
                         * by checking that the 'source' that the conduit/bufferManager was assinged to
                         * was for the Source that we are registering.
                         */
                        if (sourceName.equals(servRef.getProperty("source"))) {
                            /*
                             * Retrieve the actual Conduit/BufferManager fro mthe service Reference
                             * and put it into the bufferManagerMap.
                             */
                            Object object = bundleContext.getService(servRef);
                            BufferManager conduit = (BufferManager) object;
                            bufferManagerMap.put(sourceId, conduit);
                        }
                    }
                }

            } catch (InvalidSyntaxException e) {
                e.printStackTrace();
            }
        }
    }
625659
private static void processNewTraceComponents() {
        if (allTraceComponentsLock.tryLock()) {
            try {
                TraceComponent tc = newTracecomponents.poll();
                while (tc != null) {
                    allTraceComponents.add(tc);
                    tc = newTracecomponents.poll();
                }
            } finally {
                allTraceComponentsLock.unlock();
            }
        }
    }
705409
function loopThroughHandlers(lastFuture, n) {
            if(n < routes.length) {
                var route = routes[n].route
                var handler = route[handlerProperty]

                if(direction === -1) {
                    var originalIndexFromCurrentRoutes = currentRoutes.length - n - 1
                    var distance = routes.length - n        // divergenceDistance
                } else {
                    var originalIndexFromCurrentRoutes = routeVergenceIndex+n
                    var distance = undefined                // no more leafDistance: routes.length - n - 1    // leafDistance
                }

                return lastFuture.then(function() {
                    if(handler !== undefined) {
                        if(originalIndexFromCurrentRoutes > 0) {
                            var parentRoute = currentRoutes[originalIndexFromCurrentRoutes-1]
                            var lastValue = parentRoute.route.lastValue
                        }

                        var nextFuture = handler.call(route, lastValue, distance)
                        if(nextFuture !== undefined) {
                            nextFuture.then(function(value) {
                                route.lastValue = value
                            }) // no done because nextFuture's errors are handled elsewhere
                        }
                    }

                    if(nextFuture === undefined) {
                        nextFuture = Future(undefined)
                    }

                    return loopThroughHandlers(nextFuture, n+1)

                }).catch(function(e){
                    return handleError(currentRoutes, originalIndexFromCurrentRoutes, type, e, []).then(function() {
                        if(direction === 1) {
                            return Future(n + routeVergenceIndex)
                        } else { // -1 exit handlers
                            return loopThroughHandlers(Future(undefined), n+1)  // continue executing the parent exit handlers
                        }
                    })
                })
            } else {
                return lastFuture.then(function() {
                    return Future(n + routeVergenceIndex)
                }).catch(function(e) {
                    throw e // propagate the error not the value
                })
            }
        }
435331
public void prepareProbePhase(IOManager ioAccess, Channel.Enumerator probeChannelEnumerator,
			LinkedBlockingQueue<MemorySegment> bufferReturnQueue) throws IOException {
		if (isInMemory()) {
			return;
		}
		// ATTENTION: The following lines are duplicated code from finalizeBuildPhase
		this.probeSideChannel = ioAccess.createBlockChannelWriter(probeChannelEnumerator.next(), bufferReturnQueue);
		this.probeSideBuffer = new ChannelWriterOutputView(this.probeSideChannel, this.memorySegmentSize);
	}
1209424
@Override
  public void process(Node externs, Node root) {
    checkState(topLevelStatements.isEmpty(), "process() called more than once");
    NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
    t.traverseRoots(externs, root);
  }
769386
public boolean process(Trace trace, Node node, Direction direction,
            Map<String, ?> headers, Object[] values) {

        if (predicate != null) {
            return predicate.test(trace, node, direction, headers, values);
        }

        return true;
    }
440014
@Override
    public synchronized void processConnect(WebSocketChannel channel, WSURI uri, String[] protocols) {
        LOG.entering(CLASS_NAME, "processConnect", new Object[] { uri, protocols });

        try {
            WebSocketNativeChannel nativeChannel = (WebSocketNativeChannel)channel;
            if (nativeChannel.getProxy() != null) {
                throw new IllegalStateException("Bridge proxy previously set");
            }
            
            Proxy proxy = BridgeUtil.createProxy(uri.getURI(), this);
            proxy.setPeer(channel);
            nativeChannel.setProxy(proxy);
            
            String[] params;
            if (protocols != null) {
                String s = "";
                for (int i=0; i<protocols.length; i++) {
                    if (i>0) {
                        s += ",";
                    }
                    s += protocols[i];
                }
                params = new String[] { "WEBSOCKET", uri.toString(), s, ""};
            } else {
                params = new String[] { "WEBSOCKET", uri.toString() };
            }
            proxy.processEvent(XoaEventKind.CREATE, params);
        }
        catch (Exception e) {
            LOG.log(Level.FINE, "While initializing WebSocket proxy: "+e.getMessage(), e);
            listener.connectionFailed(channel, e);
        }
    }
1243539
@Override
	public void process(Packet message, MessageContext ctx)
	{
		EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer();
		if (message.type == ContainerType.TYPE_TILEENTITY)
		{
			IDirectInventoryProvider inventoryProvider = TileEntityUtils.getTileEntity(	IDirectInventoryProvider.class,
																						Utils.getClientWorld(),
																						message.pos);
			if (inventoryProvider != null)
				MalisisInventory.open(player, inventoryProvider, message.windowId);
		}

		else if (message.type == ContainerType.TYPE_ITEM)
		{
			//TODO: send and use slot number instead of limited to equipped
			ItemStack itemStack = player.getHeldItemMainhand();
			if (itemStack == null || !(itemStack.getItem() instanceof IDeferredInventoryProvider<?>))
				return;

			@SuppressWarnings("unchecked")
			IDeferredInventoryProvider<ItemStack> inventoryProvider = (IDeferredInventoryProvider<ItemStack>) itemStack.getItem();
			MalisisInventory.open(player, inventoryProvider, itemStack, message.windowId);
		}
	}
849690
private synchronized void processProgressEvent(DownstreamChannel channel, WrappedByteBuffer buffer) {
        LOG.entering(CLASS_NAME, "processProgressEvent", buffer);
        try {
            
            // update timestamp that is used to record the timestamp of last received message
            channel.lastMessageTimestamp.set(System.currentTimeMillis());
            channel.buffersToRead.add(buffer);

            WebSocketEmulatedDecoderListener<DownstreamChannel> decoderListener = new WebSocketEmulatedDecoderListener<DownstreamChannel>() {

                @Override
                public void messageDecoded(DownstreamChannel channel, WrappedByteBuffer message) {
                    processMessage(channel, message);
                }

                @Override
                public void messageDecoded(DownstreamChannel channel, String message) {
                    processMessage(channel, message);
                }

                @Override
                public void commandDecoded(DownstreamChannel channel, WrappedByteBuffer command) {
                    int commandByte = command.array()[0];
                    if (commandByte == 0x30 && command.array()[1] == 0x31) { //reconnect
                        // KG-5615: Set flag - but do not reconnect until request has loaded
                        LOG.fine("Reconnect command");
                        channel.reconnecting.set(true);
                    }
                    else if (commandByte == 0x30 && command.array()[1] == 0x32) {
                        channel.closing.set(true);

                        // Cancel the idle timer if running
                        stopIdleTimer(channel);
                        
                        //close frame received
                        int code = CloseCommandMessage.CLOSE_NO_STATUS;
                        String reason = null;
                        command.skip(2); //skip first 2 bytes 0x30, 0x32
                        if (command.hasRemaining()) {
                            code = command.getShort();
                        }
                        if (command.hasRemaining()) {
                            reason = command.getString(Charset.forName("UTF-8"));
                        }
                        CloseCommandMessage message = new CloseCommandMessage(code, reason);
                        listener.commandMessageReceived(channel, message);
                    }
                }

                @Override
                public void pingReceived(DownstreamChannel channel) {
                    listener.pingReceived(channel);
                }
            };

            // Prevent multiple threads from entering
            synchronized (channel.decoder) {
                channel.decoder.decode(channel, in, decoderListener);
            }
        } catch (Exception e) {
            LOG.log(Level.FINE, e.getMessage(), e);
            e.printStackTrace();
            
            listener.downstreamFailed(channel, e);
        }
    }
62787
@Override
	public void process(Packet message, MessageContext ctx)
	{
		Container c = ctx.getServerHandler().player.openContainer;
		if (message.windowId != c.windowId || !(c instanceof MalisisInventoryContainer))
			return;

		MalisisInventoryContainer container = (MalisisInventoryContainer) c;
		container.handleAction(message.action, message.inventoryId, message.slotNumber, message.code);
		container.detectAndSendChanges();
	}
1070985
private void configureHttp2Pipeline(ChannelPipeline pipeline) {
        pipeline.addLast(Constants.CONNECTION_HANDLER, http2ConnectionHandler);
        pipeline.addLast(Constants.HTTP2_TARGET_HANDLER, http2TargetHandler);
        pipeline.addLast(Constants.DECOMPRESSOR_HANDLER, new HttpContentDecompressor());
    }
1206430
private ImmutableSet<Pipeline> selectPipelines(InterpreterListener interpreterListener,
                                                   Set<Tuple2<String, String>> processingBlacklist,
                                                   Message message,
                                                   Set<String> initialStreamIds,
                                                   ImmutableSetMultimap<String, Pipeline> streamConnection) {
        final String msgId = message.getId();

        // if a message-stream combination has already been processed (is in the set), skip that execution
        final Set<String> streamsIds = initialStreamIds.stream()
                .filter(streamId -> !processingBlacklist.contains(tuple(msgId, streamId)))
                .filter(streamConnection::containsKey)
                .collect(Collectors.toSet());
        final ImmutableSet<Pipeline> pipelinesToRun = streamsIds.stream()
                .flatMap(streamId -> streamConnection.get(streamId).stream())
                .collect(ImmutableSet.toImmutableSet());
        interpreterListener.processStreams(message, pipelinesToRun, streamsIds);
        log.debug("[{}] running pipelines {} for streams {}", msgId, pipelinesToRun, streamsIds);
        return pipelinesToRun;
    }
775013
static OcAgentTraceServiceConfigRpcHandler create(
      TraceServiceStub stub, TraceConfig traceConfig) {
    OcAgentTraceServiceConfigRpcHandler configRpcHandler =
        new OcAgentTraceServiceConfigRpcHandler(traceConfig);
    UpdatedLibraryConfigObserver updatedLibraryConfigObserver =
        new UpdatedLibraryConfigObserver(traceConfig, configRpcHandler);
    try {
      StreamObserver<CurrentLibraryConfig> currentConfigObserver =
          stub.config(updatedLibraryConfigObserver);
      configRpcHandler.setCurrentConfigObserver(currentConfigObserver);
    } catch (StatusRuntimeException e) {
      configRpcHandler.onComplete(e);
    }
    return configRpcHandler;
  }
388427
public void processingInstruction(String arg0, String arg1)
        throws SAXException
    {
        if (m_tracer != null)
            super.fireEscapingEvent(arg0, arg1);
    }
45686
private void handlePipeLining() {
        HttpServiceContextImpl sc = getHTTPContext();
        WsByteBuffer buffer = sc.returnLastBuffer();
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Pipelined request found: " + buffer);
        }
        sc.clear();
        // save it back so that we always release it
        sc.storeAllocatedBuffer(buffer);
        sc.disableBufferModification();
        EventEngine events = HttpDispatcher.getEventService();
        if (null != events) {
            Event event = events.createEvent(HttpPipelineEventHandler.TOPIC_PIPELINING);
            event.setProperty(CallbackIDs.CALLBACK_HTTPICL.getName(), this);
            events.postEvent(event);
        } else {
            // unable to dispatch work request, continue on this thread
            ready(getVirtualConnection());
        }
    }
1128173
@Override
  public void sinkPrepare(FlowProcess<? extends Configuration> flowProcess, SinkCall<Corc, OutputCollector> sinkCall)
      throws IOException {
    sinkCall.setContext(new Corc(typeInfo, converterFactory));
  }
1142930
@Override
	public void prepare(Map stormConf, TopologyContext context,
			OutputCollector collector) {
		if(this.jmsProvider == null || this.producer == null){
			throw new IllegalStateException("JMS Provider and MessageProducer not set.");
		}
		this.collector = collector;
		LOG.debug("Connecting JMS..");
		try {
			ConnectionFactory cf = this.jmsProvider.connectionFactory();
			Destination dest = this.jmsProvider.destination();
			this.connection = cf.createConnection();
			this.session = connection.createSession(this.jmsTransactional,
					this.jmsAcknowledgeMode);
			this.messageProducer = session.createProducer(dest);
			
			connection.start();
		} catch (Exception e) {
			LOG.warn("Error creating JMS connection.", e);
		}	
	}