<commit_before>/*
 * CollabNet Subversion Edge
 * Copyright (C) 2010, CollabNet Inc. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.collabnet.svnedge.console.ui

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.springframework.web.servlet.support.RequestContextUtils as RCU

import com.collabnet.svnedge.console.Server
import com.collabnet.svnedge.console.Repository
import com.collabnet.svnedge.console.CantBindPortException

import com.collabnet.svnedge.replica.manager.Master
import com.collabnet.svnedge.replica.manager.ReplicaConfig
import com.collabnet.svnedge.replica.manager.ApprovalState

import java.net.NoRouteToHostException
import java.text.SimpleDateFormat;

import com.collabnet.svnedge.console.ServerMode

@Secured(['ROLE_USER'])
class StatusController {

    def operatingSystemService
    def networkingService
    def svnRepoService
    def quartzScheduler
    def realTimeStatisticsService
    def lifecycleService
    def packagesUpdateService

    // start and stop actions use POST requests
    static allowedMethods = [start:'POST', stop:'POST']

    def getUpdateMessage() {
        def msg = message(code: 'packagesUpdate.status.updates.available')
        def download = message(code:'packagesUpdate.status.updates.forDownload')
        return msg.replace(download,
            "<a href='/csvn/packagesUpdate/available'>${download}</a>")
    }

    def index = {
       def server = Server.getServer()
       def defaultMaster = Master.getDefaultMaster()
       def currentReplica = ReplicaConfig.getCurrentConfig()
       if (server.replica) { 
           if (!defaultMaster.isActive && !currentReplica.getState()) {
               redirect(controller:"wizard", action:"index")
           }

           if(!currentReplica) {
               flash.error = message(code: 'replica.error.notStarted')
           }
           if (currentReplica.getState() == ApprovalState.PENDING) {
               flash.message = message(code: 'replica.error.notApproved')
           } else if (currentReplica.getState() == ApprovalState.DENIED) {
               flash.error = message(code: 'replica.error.denied')
           } else if (currentReplica.getState() == ApprovalState.NOT_FOUND 
                      || currentReplica.getState() == ApprovalState
                      .REGISTRATION_FAILED) {
               flash.error = message(code: 'replica.error.cantRegister')
           }
        }
        def ctfUrl
        if (server.managedByCtf()) {
            ctfUrl = server.getManagedServer().getWebAppUrl()
        }

        boolean isStarted = lifecycleService.isStarted()
        params.max = 
            Math.min( params.max ? params.max.toInteger() : 10,  100)
        Repository[] repos = Repository.list(params)
        Repository sampleRepo = 
            (repos.length > 0) ? repos[0] : null

        def sfVersion = this.packagesUpdateService.getInstalledVersionNumber()
        def svnVer = this.packagesUpdateService.getInstalledSvnVersionNumber()
        try {
           if (this.packagesUpdateService.hasBeenBootstraped()) {
               if (this.packagesUpdateService.areThereUpdatesAvailable()) {
                   if (!flash.error) {
                       flash.warn = getUpdateMessage()
                   }
               }
               //system restart has priority over the updates
               if (this.packagesUpdateService.systemNeedsRestart()) {
                   flash.warn = message(
                       code: 'packagesUpdate.status.updates.requiresRestart')
               }
               //if the system has recently been updated
               if (this.packagesUpdateService.hasTheSystemBeenUpdated() || 
                       this.packagesUpdateService.hasTheSvnServerBeenUpdated()){
                   this.packagesUpdateService.setTheSystemToNotBeenUpdated()
                   flash.message = message(
                       code: 'packagesUpdate.success.installed.updates')
               } else
               if (this.packagesUpdateService.hasNewPackagesBeenInstalled()) {
                   this.packagesUpdateService.setTheSystemToNotBeenUpdated()
                   flash.message = message(
                       code: 'packagesUpdate.success.installed.newPackages')
               }
           }

       } catch (NoRouteToHostException nrth) {
           if (!flash.error) {
               flash.error = message(
                   code: 'packagesUpdate.error.server.noConnection')
           }
       } catch (Exception e) {
           e.printStackTrace()
           def msg = message(code: 'packagesUpdate.error.general')
           flash.error = msg + ":" + e.getMessage()
       }

       return [isStarted: isStarted,
               isDefaultPortAllowed: lifecycleService.isDefaultPortAllowed(),
               sampleRepo: sampleRepo,
               defaultMaster: defaultMaster, 
               currentReplica: currentReplica,
               server: server,
               perfStats: getPerfStats(currentReplica, server),
               softwareVersion: sfVersion,
               svnVersion: svnVer,
               ctfUrl: ctfUrl
               ]
    }

    def getPerfStats(currentConfig, server) {
       def dateTimeFormat = message(code:"default.dateTime.format.withZone")
       def runningSinceDate = quartzScheduler.getMetaData().runningSince
       def currentLocale = RCU.getLocale(request)
       def model = [
           [label: message(code: 'status.page.status.running_since'),
            value: new SimpleDateFormat(dateTimeFormat, 
                currentLocale).format(runningSinceDate)]]
       if (!server.managedByCtf()) {
           model << [label: message(code: 'status.page.status.repo_health'), 
               value: svnRepoService.formatRepoStatus(realTimeStatisticsService
                   ?.getReposStatus(), currentLocale)]
       }<commit_msg>[artf4986] This revision fixes the broken date reference during functional tests of the status page. * StatusController.groovy - Date instance from functional tests comes null for the status of statistics.<commit_after>/*
 * CollabNet Subversion Edge
 * Copyright (C) 2010, CollabNet Inc. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.collabnet.svnedge.console.ui

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.springframework.web.servlet.support.RequestContextUtils as RCU

import com.collabnet.svnedge.console.Server
import com.collabnet.svnedge.console.Repository
import com.collabnet.svnedge.console.CantBindPortException

import com.collabnet.svnedge.replica.manager.Master
import com.collabnet.svnedge.replica.manager.ReplicaConfig
import com.collabnet.svnedge.replica.manager.ApprovalState

import java.net.NoRouteToHostException
import java.text.SimpleDateFormat;

import com.collabnet.svnedge.console.ServerMode

@Secured(['ROLE_USER'])
class StatusController {

    def operatingSystemService
    def networkingService
    def svnRepoService
    def quartzScheduler
    def realTimeStatisticsService
    def lifecycleService
    def packagesUpdateService

    // start and stop actions use POST requests
    static allowedMethods = [start:'POST', stop:'POST']

    def getUpdateMessage() {
        def msg = message(code: 'packagesUpdate.status.updates.available')
        def download = message(code:'packagesUpdate.status.updates.forDownload')
        return msg.replace(download,
            "<a href='/csvn/packagesUpdate/available'>${download}</a>")
    }

    def index = {
       def server = Server.getServer()
       def defaultMaster = Master.getDefaultMaster()
       def currentReplica = ReplicaConfig.getCurrentConfig()
       if (server.replica) { 
           if (!defaultMaster.isActive && !currentReplica.getState()) {
               redirect(controller:"wizard", action:"index")
           }

           if(!currentReplica) {
               flash.error = message(code: 'replica.error.notStarted')
           }
           if (currentReplica.getState() == ApprovalState.PENDING) {
               flash.message = message(code: 'replica.error.notApproved')
           } else if (currentReplica.getState() == ApprovalState.DENIED) {
               flash.error = message(code: 'replica.error.denied')
           } else if (currentReplica.getState() == ApprovalState.NOT_FOUND 
                      || currentReplica.getState() == ApprovalState
                      .REGISTRATION_FAILED) {
               flash.error = message(code: 'replica.error.cantRegister')
           }
        }
        def ctfUrl
        if (server.managedByCtf()) {
            ctfUrl = server.getManagedServer().getWebAppUrl()
        }

        boolean isStarted = lifecycleService.isStarted()
        params.max = 
            Math.min( params.max ? params.max.toInteger() : 10,  100)
        Repository[] repos = Repository.list(params)
        Repository sampleRepo = 
            (repos.length > 0) ? repos[0] : null

        def sfVersion = this.packagesUpdateService.getInstalledVersionNumber()
        def svnVer = this.packagesUpdateService.getInstalledSvnVersionNumber()
        try {
           if (this.packagesUpdateService.hasBeenBootstraped()) {
               if (this.packagesUpdateService.areThereUpdatesAvailable()) {
                   if (!flash.error) {
                       flash.warn = getUpdateMessage()
                   }
               }
               //system restart has priority over the updates
               if (this.packagesUpdateService.systemNeedsRestart()) {
                   flash.warn = message(
                       code: 'packagesUpdate.status.updates.requiresRestart')
               }
               //if the system has recently been updated
               if (this.packagesUpdateService.hasTheSystemBeenUpdated() || 
                       this.packagesUpdateService.hasTheSvnServerBeenUpdated()){
                   this.packagesUpdateService.setTheSystemToNotBeenUpdated()
                   flash.message = message(
                       code: 'packagesUpdate.success.installed.updates')
               } else
               if (this.packagesUpdateService.hasNewPackagesBeenInstalled()) {
                   this.packagesUpdateService.setTheSystemToNotBeenUpdated()
                   flash.message = message(
                       code: 'packagesUpdate.success.installed.newPackages')
               }
           }

       } catch (NoRouteToHostException nrth) {
           if (!flash.error) {
               flash.error = message(
                   code: 'packagesUpdate.error.server.noConnection')
           }
       } catch (Exception e) {
           e.printStackTrace()
           def msg = message(code: 'packagesUpdate.error.general')
           flash.error = msg + ":" + e.getMessage()
       }

       return [isStarted: isStarted,
               isDefaultPortAllowed: lifecycleService.isDefaultPortAllowed(),
               sampleRepo: sampleRepo,
               defaultMaster: defaultMaster, 
               currentReplica: currentReplica,
               server: server,
               perfStats: getPerfStats(currentReplica, server),
               softwareVersion: sfVersion,
               svnVersion: svnVer,
               ctfUrl: ctfUrl
               ]
    }

    def getPerfStats(currentConfig, server) {
       def dateTimeFormat = message(code:"default.dateTime.format.withZone")
       def runningSinceDate = quartzScheduler.getMetaData().runningSince
       runningSinceDate = runningSinceDate ?: new Date()
       def currentLocale = RCU.getLocale(request)
       def model = [
           [label: message(code: 'status.page.status.running_since'),
            value: new SimpleDateFormat(dateTimeFormat, 
                currentLocale).format(runningSinceDate)]]
       if (!server.managedByCtf()) {
           model << [label: message(code: 'status.page.status.repo_health'), 
               value: svnRepoService.formatRepoStatus(realTimeStatisticsService
                   ?.getReposStatus(), currentLocale)]
       }
{'fraction_non_alphanumeric': 0.08870907319997003, 'fraction_numerical': 0.0020978497040533453, 'mean_word_length': 2.349560853199498, 'pattern_counts': {'":': 2, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1222491', 'n_tokens_mistral': 3478, 'n_tokens_neox': 3415, 'n_words': 779}