<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel.commands;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Route;
import org.apache.camel.ServiceStatus;
import org.apache.camel.StatefulService;
import org.apache.camel.model.ModelHelper;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.rest.RestDefinition;
import org.apache.camel.model.rest.RestsDefinition;
import org.apache.camel.spi.ManagementAgent;
import org.apache.camel.spi.RestRegistry;
import org.apache.camel.util.JsonSchemaHelper;

/**
 * Abstract {@link org.apache.camel.commands.LocalCamelController} that implementators should extend when implemeting
 * a controller that runs locally in the same JVM as Camel.
 */
public abstract class AbstractLocalCamelController extends AbstractCamelController implements LocalCamelController {

    public CamelContext getLocalCamelContext(String name) throws Exception {
        for (CamelContext camelContext : this.getLocalCamelContexts()) {
            if (camelContext.getName().equals(name)) {
                return camelContext;
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> getCamelContextInformation(String name) throws Exception {
        Map<String, Object> answer = new LinkedHashMap<String, Object>();
        CamelContext context = getLocalCamelContext(name);
        if (context != null) {
            answer.put("name", context.getName());
            answer.put("managementName", context.getManagementName());
            answer.put("version", context.getVersion());
            answer.put("status", context.getStatus().name());
            answer.put("uptime", context.getUptime());
            answer.put("suspended", context.getStatus().isSuspended());
            answer.put("allowUseOriginalMessage", context.isAllowUseOriginalMessage());
            answer.put("messageHistory", context.isMessageHistory());
            answer.put("tracing", context.isTracing());
            answer.put("shutdownTimeout", context.getShutdownStrategy().getTimeUnit().toSeconds(context.getShutdownStrategy().getTimeout()));
            answer.put("classResolver", context.getClassResolver().toString());
            answer.put("packageScanClassResolver", context.getPackageScanClassResolver().toString());
            answer.put("applicationContextClassLoader", context.getApplicationContextClassLoader().toString());

            for (Map.Entry<String, String> entry : context.getProperties().entrySet()) {
                answer.put("property." + entry.getKey(), entry.getValue());
            }

            long activeRoutes = 0;
            long inactiveRoutes = 0;
            List<Route> routeList = context.getRoutes();
            for (Route route : routeList) {
                if (context.getRouteStatus(route.getId()).isStarted()) {
                    activeRoutes++;
                } else {
                    inactiveRoutes++;
                }
            }
            answer.put("startedRoutes", activeRoutes);
            answer.put("totalRoutes", activeRoutes + inactiveRoutes);

            // add type converter details
            answer.put("typeConverter.numberOfTypeConverters", context.getTypeConverterRegistry().size());
            answer.put("typeConverter.statisticsEnabled", context.getTypeConverterRegistry().getStatistics().isStatisticsEnabled());
            answer.put("typeConverter.noopCounter", context.getTypeConverterRegistry().getStatistics().getNoopCounter());
            answer.put("typeConverter.attemptCounter", context.getTypeConverterRegistry().getStatistics().getAttemptCounter());
            answer.put("typeConverter.hitCounter", context.getTypeConverterRegistry().getStatistics().getHitCounter());
            answer.put("typeConverter.missCounter", context.getTypeConverterRegistry().getStatistics().getMissCounter());
            answer.put("typeConverter.failedCounter", context.getTypeConverterRegistry().getStatistics().getFailedCounter());

            // add async processor await manager details
            answer.put("asyncProcessorAwaitManager.size", context.getAsyncProcessorAwaitManager().size());
            answer.put("asyncProcessorAwaitManager.statisticsEnabled", context.getAsyncProcessorAwaitManager().getStatistics().isStatisticsEnabled());
            answer.put("asyncProcessorAwaitManager.threadsBlocked", context.getAsyncProcessorAwaitManager().getStatistics().getThreadsBlocked());
            answer.put("asyncProcessorAwaitManager.threadsInterrupted", context.getAsyncProcessorAwaitManager().getStatistics().getThreadsInterrupted());
            answer.put("asyncProcessorAwaitManager.totalDuration", context.getAsyncProcessorAwaitManager().getStatistics().getTotalDuration());
            answer.put("asyncProcessorAwaitManager.minDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMinDuration());
            answer.put("asyncProcessorAwaitManager.maxDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMaxDuration());
            answer.put("asyncProcessorAwaitManager.meanDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMeanDuration());

            // add stream caching details if enabled
            if (context.getStreamCachingStrategy().isEnabled()) {
                answer.put("streamCachingEnabled", true);
                answer.put("streamCaching.spoolDirectory", context.getStreamCachingStrategy().getSpoolDirectory());
                answer.put("streamCaching.spoolChiper", context.getStreamCachingStrategy().getSpoolChiper());
                answer.put("streamCaching.spoolThreshold", context.getStreamCachingStrategy().getSpoolThreshold());
                answer.put("streamCaching.spoolUsedHeapMemoryThreshold", context.getStreamCachingStrategy().getSpoolUsedHeapMemoryThreshold());
                answer.put("streamCaching.spoolUsedHeapMemoryLimit", context.getStreamCachingStrategy().getSpoolUsedHeapMemoryLimit());
                answer.put("streamCaching.anySpoolRules", context.getStreamCachingStrategy().isAnySpoolRules());
                answer.put("streamCaching.bufferSize", context.getStreamCachingStrategy().getBufferSize());
                answer.put("streamCaching.removeSpoolDirectoryWhenStopping", context.getStreamCachingStrategy().isRemoveSpoolDirectoryWhenStopping());
                answer.put("streamCaching.statisticsEnabled", context.getStreamCachingStrategy().getStatistics().isStatisticsEnabled());

                if (context.getStreamCachingStrategy().getStatistics().isStatisticsEnabled()) {
                    answer.put("streamCaching.cacheMemoryCounter", context.getStreamCachingStrategy().getStatistics().getCacheMemoryCounter());
                    answer.put("streamCaching.cacheMemorySize", context.getStreamCachingStrategy().getStatistics().getCacheMemorySize());
                    answer.put("streamCaching.cacheMemoryAverageSize", context.getStreamCachingStrategy().getStatistics().getCacheMemoryAverageSize());
                    answer.put("streamCaching.cacheSpoolCounter", context.getStreamCachingStrategy().getStatistics().getCacheSpoolCounter());
                    answer.put("streamCaching.cacheSpoolSize", context.getStreamCachingStrategy().getStatistics().getCacheSpoolSize());
                    answer.put("streamCaching.cacheSpoolAverageSize", context.getStreamCachingStrategy().getStatistics().getCacheSpoolAverageSize());
                }
            } else {
                answer.put("streamCachingEnabled", false);
            }
        }

        return answer;
    }

    public String getCamelContextStatsAsXml(String camelContextName, boolean fullStats, boolean includeProcessors) throws Exception {
        CamelContext context = this.getLocalCamelContext(camelContextName);
        if (context == null) {
            return null;
        }

        ManagementAgent agent = context.getManagementStrategy().getManagementAgent();
        if (agent != null) {
            MBeanServer mBeanServer = agent.getMBeanServer();
            ObjectName query = ObjectName.getInstance(agent.getMBeanObjectDomainName() + ":type=context,*");
            Set<ObjectName> set = mBeanServer.queryNames(query, null);
            for (ObjectName contextMBean : set) {
                String camelId = (String) mBeanServer.getAttribute(contextMBean, "CamelId");
                if (camelId != null && camelId.equals(context.getName())) {
                    String xml = (String) mBeanServer.invoke(contextMBean, "dumpRoutesStatsAsXml", new Object[]{fullStats, includeProcessors}, new String[]{"boolean", "boolean"});
                    return xml;
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> browseInflightExchanges(String camelContextName, int limit, boolean sortByLongestDuration) throws Exception {
        CamelContext context = this.getLocalCamelContext(camelContextName);
        if (context == null) {
            return null;
        }

        List<Map<String, Object>> answer = new ArrayList<Map<String, Object>>();

        ManagementAgent agent = context.getManagementStrategy().getManagementAgent();
        if (agent != null) {
            MBeanServer mBeanServer = agent.getMBeanServer();
            ObjectName on = null;
            Set<ObjectName> set = mBeanServer.queryNames(new ObjectName(agent.getMBeanObjectDomainName() + ":type=services,name=DefaultInflightRepository,*"), null);
            if (set.size() == 1) {
                on = set.iterator().next();
            }
            if (mBeanServer.isRegistered(on)) {
                TabularData list = (TabularData) mBeanServer.invoke(on, "browse", new Object[]{limit, sortByLongestDuration}, new String[]{"int", "boolean"});
                Collection<CompositeData> values = (Collection<CompositeData>) list.values();
                for (CompositeData data : values) {
                    Map<String, Object> row = new LinkedHashMap<String, Object>();
                    Object exchangeId = data.get("exchangeId");
                    if (exchangeId != null) {
                        row.put("exchangeId", exchangeId);
                    }
                    Object fromRouteId = data.get("fromRouteId");
                    if (fromRouteId != null) {
                        row.put("fromRouteId", fromRouteId);
                    }
                    Object routeId = data.get("routeId");
                    if (routeId != null) {
                        row.put("routeId", routeId);
                    }
                    Object nodeId = data.get("nodeId");<commit_msg>CAMEL-8841: camel:context-inflight returns 'Object name cannot be null'. Thanks to <NAME> for the patch.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel.commands;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Route;
import org.apache.camel.ServiceStatus;
import org.apache.camel.StatefulService;
import org.apache.camel.model.ModelHelper;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.rest.RestDefinition;
import org.apache.camel.model.rest.RestsDefinition;
import org.apache.camel.spi.ManagementAgent;
import org.apache.camel.spi.RestRegistry;
import org.apache.camel.util.JsonSchemaHelper;

/**
 * Abstract {@link org.apache.camel.commands.LocalCamelController} that implementators should extend when implemeting
 * a controller that runs locally in the same JVM as Camel.
 */
public abstract class AbstractLocalCamelController extends AbstractCamelController implements LocalCamelController {

    public CamelContext getLocalCamelContext(String name) throws Exception {
        for (CamelContext camelContext : this.getLocalCamelContexts()) {
            if (camelContext.getName().equals(name)) {
                return camelContext;
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> getCamelContextInformation(String name) throws Exception {
        Map<String, Object> answer = new LinkedHashMap<String, Object>();
        CamelContext context = getLocalCamelContext(name);
        if (context != null) {
            answer.put("name", context.getName());
            answer.put("managementName", context.getManagementName());
            answer.put("version", context.getVersion());
            answer.put("status", context.getStatus().name());
            answer.put("uptime", context.getUptime());
            answer.put("suspended", context.getStatus().isSuspended());
            answer.put("allowUseOriginalMessage", context.isAllowUseOriginalMessage());
            answer.put("messageHistory", context.isMessageHistory());
            answer.put("tracing", context.isTracing());
            answer.put("shutdownTimeout", context.getShutdownStrategy().getTimeUnit().toSeconds(context.getShutdownStrategy().getTimeout()));
            answer.put("classResolver", context.getClassResolver().toString());
            answer.put("packageScanClassResolver", context.getPackageScanClassResolver().toString());
            answer.put("applicationContextClassLoader", context.getApplicationContextClassLoader().toString());

            for (Map.Entry<String, String> entry : context.getProperties().entrySet()) {
                answer.put("property." + entry.getKey(), entry.getValue());
            }

            long activeRoutes = 0;
            long inactiveRoutes = 0;
            List<Route> routeList = context.getRoutes();
            for (Route route : routeList) {
                if (context.getRouteStatus(route.getId()).isStarted()) {
                    activeRoutes++;
                } else {
                    inactiveRoutes++;
                }
            }
            answer.put("startedRoutes", activeRoutes);
            answer.put("totalRoutes", activeRoutes + inactiveRoutes);

            // add type converter details
            answer.put("typeConverter.numberOfTypeConverters", context.getTypeConverterRegistry().size());
            answer.put("typeConverter.statisticsEnabled", context.getTypeConverterRegistry().getStatistics().isStatisticsEnabled());
            answer.put("typeConverter.noopCounter", context.getTypeConverterRegistry().getStatistics().getNoopCounter());
            answer.put("typeConverter.attemptCounter", context.getTypeConverterRegistry().getStatistics().getAttemptCounter());
            answer.put("typeConverter.hitCounter", context.getTypeConverterRegistry().getStatistics().getHitCounter());
            answer.put("typeConverter.missCounter", context.getTypeConverterRegistry().getStatistics().getMissCounter());
            answer.put("typeConverter.failedCounter", context.getTypeConverterRegistry().getStatistics().getFailedCounter());

            // add async processor await manager details
            answer.put("asyncProcessorAwaitManager.size", context.getAsyncProcessorAwaitManager().size());
            answer.put("asyncProcessorAwaitManager.statisticsEnabled", context.getAsyncProcessorAwaitManager().getStatistics().isStatisticsEnabled());
            answer.put("asyncProcessorAwaitManager.threadsBlocked", context.getAsyncProcessorAwaitManager().getStatistics().getThreadsBlocked());
            answer.put("asyncProcessorAwaitManager.threadsInterrupted", context.getAsyncProcessorAwaitManager().getStatistics().getThreadsInterrupted());
            answer.put("asyncProcessorAwaitManager.totalDuration", context.getAsyncProcessorAwaitManager().getStatistics().getTotalDuration());
            answer.put("asyncProcessorAwaitManager.minDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMinDuration());
            answer.put("asyncProcessorAwaitManager.maxDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMaxDuration());
            answer.put("asyncProcessorAwaitManager.meanDuration", context.getAsyncProcessorAwaitManager().getStatistics().getMeanDuration());

            // add stream caching details if enabled
            if (context.getStreamCachingStrategy().isEnabled()) {
                answer.put("streamCachingEnabled", true);
                answer.put("streamCaching.spoolDirectory", context.getStreamCachingStrategy().getSpoolDirectory());
                answer.put("streamCaching.spoolChiper", context.getStreamCachingStrategy().getSpoolChiper());
                answer.put("streamCaching.spoolThreshold", context.getStreamCachingStrategy().getSpoolThreshold());
                answer.put("streamCaching.spoolUsedHeapMemoryThreshold", context.getStreamCachingStrategy().getSpoolUsedHeapMemoryThreshold());
                answer.put("streamCaching.spoolUsedHeapMemoryLimit", context.getStreamCachingStrategy().getSpoolUsedHeapMemoryLimit());
                answer.put("streamCaching.anySpoolRules", context.getStreamCachingStrategy().isAnySpoolRules());
                answer.put("streamCaching.bufferSize", context.getStreamCachingStrategy().getBufferSize());
                answer.put("streamCaching.removeSpoolDirectoryWhenStopping", context.getStreamCachingStrategy().isRemoveSpoolDirectoryWhenStopping());
                answer.put("streamCaching.statisticsEnabled", context.getStreamCachingStrategy().getStatistics().isStatisticsEnabled());

                if (context.getStreamCachingStrategy().getStatistics().isStatisticsEnabled()) {
                    answer.put("streamCaching.cacheMemoryCounter", context.getStreamCachingStrategy().getStatistics().getCacheMemoryCounter());
                    answer.put("streamCaching.cacheMemorySize", context.getStreamCachingStrategy().getStatistics().getCacheMemorySize());
                    answer.put("streamCaching.cacheMemoryAverageSize", context.getStreamCachingStrategy().getStatistics().getCacheMemoryAverageSize());
                    answer.put("streamCaching.cacheSpoolCounter", context.getStreamCachingStrategy().getStatistics().getCacheSpoolCounter());
                    answer.put("streamCaching.cacheSpoolSize", context.getStreamCachingStrategy().getStatistics().getCacheSpoolSize());
                    answer.put("streamCaching.cacheSpoolAverageSize", context.getStreamCachingStrategy().getStatistics().getCacheSpoolAverageSize());
                }
            } else {
                answer.put("streamCachingEnabled", false);
            }
        }

        return answer;
    }

    public String getCamelContextStatsAsXml(String camelContextName, boolean fullStats, boolean includeProcessors) throws Exception {
        CamelContext context = this.getLocalCamelContext(camelContextName);
        if (context == null) {
            return null;
        }

        ManagementAgent agent = context.getManagementStrategy().getManagementAgent();
        if (agent != null) {
            MBeanServer mBeanServer = agent.getMBeanServer();
            ObjectName query = ObjectName.getInstance(agent.getMBeanObjectDomainName() + ":type=context,*");
            Set<ObjectName> set = mBeanServer.queryNames(query, null);
            for (ObjectName contextMBean : set) {
                String camelId = (String) mBeanServer.getAttribute(contextMBean, "CamelId");
                if (camelId != null && camelId.equals(context.getName())) {
                    String xml = (String) mBeanServer.invoke(contextMBean, "dumpRoutesStatsAsXml", new Object[]{fullStats, includeProcessors}, new String[]{"boolean", "boolean"});
                    return xml;
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> browseInflightExchanges(String camelContextName, int limit, boolean sortByLongestDuration) throws Exception {
        CamelContext context = this.getLocalCamelContext(camelContextName);
        if (context == null) {
            return null;
        }

        List<Map<String, Object>> answer = new ArrayList<Map<String, Object>>();

        ManagementAgent agent = context.getManagementStrategy().getManagementAgent();
        if (agent != null) {
            MBeanServer mBeanServer = agent.getMBeanServer();
            ObjectName on = new ObjectName(agent.getMBeanObjectDomainName() + ":type=services,name=DefaultInflightRepository,context=" + context.getManagementName());
            if (mBeanServer.isRegistered(on)) {
                TabularData list = (TabularData) mBeanServer.invoke(on, "browse", new Object[]{limit, sortByLongestDuration}, new String[]{"int", "boolean"});
                Collection<CompositeData> values = (Collection<CompositeData>) list.values();
                for (CompositeData data : values) {
                    Map<String, Object> row = new LinkedHashMap<String, Object>();
                    Object exchangeId = data.get("exchangeId");
                    if (exchangeId != null) {
                        row.put("exchangeId", exchangeId);
                    }
                    Object fromRouteId = data.get("fromRouteId");
                    if (fromRouteId != null) {
                        row.put("fromRouteId", fromRouteId);
                    }
                    Object routeId = data.get("routeId");
                    if (routeId != null) {
                        row.put("routeId", routeId);
                    }
                    Object nodeId = data.get("nodeId");
{'fraction_non_alphanumeric': 0.11086965606586151, 'fraction_numerical': 0.0007104350369844122, 'mean_word_length': 3.26483692746391, 'pattern_counts': {'":': 4, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7595598', 'n_tokens_mistral': 5857, 'n_tokens_neox': 5710, 'n_words': 1091}