<commit_before>/*
 * Copyright 2018 ThoughtWorks, Inc.
 *
 * Licensed 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 com.thoughtworks.go.server.service.support;

import com.google.gson.GsonBuilder;
import com.thoughtworks.go.i18n.LocalizedMessage;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.SecurityService;
import com.thoughtworks.go.server.service.result.LocalizedOperationResult;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class ServerStatusService {
    private SecurityService securityService;
    private List<ServerInfoProvider> providers = new ArrayList<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerStatusService.class);

    @Autowired
    public ServerStatusService(SecurityService securityService, ServerInfoProvider... providerArray) throws IOException {
        this.securityService = securityService;

        providers.addAll(Arrays.asList(providerArray));
        Collections.sort(providers, new Comparator<ServerInfoProvider>() {
            @Override
            public int compare(ServerInfoProvider oneProvider, ServerInfoProvider anotherProvider) {
                return Double.compare(oneProvider.priority(), anotherProvider.priority());
            }
        });
        Runtime.getRuntime().addShutdownHook(logServerInfo());
    }

    private Thread logServerInfo() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                LOGGER.info(new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(serverInfoAsJson()));
            }
        });
    }

    public Map<String, Object> asJson(Username username, LocalizedOperationResult result) {
        if (!securityService.isUserAdmin(username)) {
            result.forbidden(LocalizedMessage.forbiddenToEdit(), HealthStateType.forbidden());
            return null;
        }

        return serverInfoAsJson();

    }

    private Map<String, Object> serverInfoAsJson() {
        LinkedHashMap<String, Object> json = new LinkedHashMap<>();
        json.put("Timestamp", DateUtils.formatISO8601(new Date()));

        for (ServerInfoProvider provider : providers) {
            try {
                json.put(provider.name(), provider.asJson());
            } catch (Exception e) {
                json.put(provider.getClass().getCanonicalName(), String.format("Provider %s threw an exception: %s", provider.getClass(), e.getMessage()));
                LOGGER.warn("An API support page provider failed.", e);
            }
        }
        return json;
    }<commit_msg>Do not log server info at shutdown<commit_after>/*
 * Copyright 2018 ThoughtWorks, Inc.
 *
 * Licensed 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 com.thoughtworks.go.server.service.support;

import com.thoughtworks.go.i18n.LocalizedMessage;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.SecurityService;
import com.thoughtworks.go.server.service.result.LocalizedOperationResult;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class ServerStatusService {
    private SecurityService securityService;
    private List<ServerInfoProvider> providers = new ArrayList<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerStatusService.class);

    @Autowired
    public ServerStatusService(SecurityService securityService, ServerInfoProvider... providerArray) throws IOException {
        this.securityService = securityService;

        providers.addAll(Arrays.asList(providerArray));
        Collections.sort(providers, new Comparator<ServerInfoProvider>() {
            @Override
            public int compare(ServerInfoProvider oneProvider, ServerInfoProvider anotherProvider) {
                return Double.compare(oneProvider.priority(), anotherProvider.priority());
            }
        });
    }

    public Map<String, Object> asJson(Username username, LocalizedOperationResult result) {
        if (!securityService.isUserAdmin(username)) {
            result.forbidden(LocalizedMessage.forbiddenToEdit(), HealthStateType.forbidden());
            return null;
        }

        return serverInfoAsJson();

    }

    private Map<String, Object> serverInfoAsJson() {
        LinkedHashMap<String, Object> json = new LinkedHashMap<>();
        json.put("Timestamp", DateUtils.formatISO8601(new Date()));

        for (ServerInfoProvider provider : providers) {
            try {
                json.put(provider.name(), provider.asJson());
            } catch (Exception e) {
                json.put(provider.getClass().getCanonicalName(), String.format("Provider %s threw an exception: %s", provider.getClass(), e.getMessage()));
                LOGGER.warn("An API support page provider failed.", e);
            }
        }
        return json;
    }
{'fraction_non_alphanumeric': 0.09773151025481666, 'fraction_numerical': 0.004972032318210068, 'mean_word_length': 3.451590594744122, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '1224083', 'n_tokens_mistral': 1638, 'n_tokens_neox': 1610, 'n_words': 434}