Рассчитать разницу времени клиент-сервер в Borland Starteam server 8 - PullRequest
1 голос
/ 24 сентября 2008

Задача . Мне нужен способ найти время сервера Starteam через Starteam Java SDK 8.0. Версия сервера - 8.0.172, поэтому метод Server.getCurrentTime() недоступен, поскольку он был добавлен только в версии сервера 9.0.

Мотивация . Мое приложение должно использовать представления в определенные даты. Таким образом, если существует некоторое различие в системном времени между клиентом (на котором запущено приложение) и сервером, то полученные представления будут неточными. В худшем случае запрашиваемая клиентом дата находится в будущем для сервера, поэтому операция приводит к исключению.

Ответы [ 4 ]

2 голосов
/ 24 сентября 2008

После некоторого расследования я не нашел более чистого решения, чем использование временного предмета. Мое приложение запрашивает время создания элемента и сравнивает его с местным временем. Вот метод, который я использую для получения времени сервера:

public Date getCurrentServerTime() {
    Folder rootFolder = project.getDefaultView().getRootFolder();

    Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder);
    newItem.update();
    newItem.remove();
    newItem.update();
    return newItem.getCreatedTime().createDate();
}
1 голос
/ 09 апреля 2009

Нам нужно было найти способ найти время сервера для использования с CodeCollab. Вот (длинный) пример кода на C #, как это сделать без создания временного файла. Разрешение составляет 1 секунду.

    static void Main(string[] args)
    {
        // ServerTime replacement for pre-2006 StarTeam servers.
        // Picks a date in the future.
        // Gets a view, sets the configuration to the date, and tries to get a property from the root folder.
        // If it cannot retrieve the property, the date is too far in the future.  Roll back the date to an earlier time.

        DateTime StartTime = DateTime.Now;

        Server s = new Server("serverAddress", 49201);
        s.LogOn("User", "Password");

        // Getting a view - doesn't matter which, as long as it is not deleted.
        Project p = s.Projects[0];
        View v = p.AccessibleViews[0]; // AccessibleViews saves checking permissions.

        // Timestep to use when searching.  One hour is fairly quick for resolution.
        TimeSpan deltaTime = new TimeSpan(1, 0, 0);
        deltaTime = new TimeSpan(24 * 365, 0, 0);

        // Invalid calls return faster - start a ways in the future.
        TimeSpan offset = new TimeSpan(24, 0, 0);

        // Times before the view was created are invalid.
        DateTime minTime = v.CreatedTime;
        DateTime localTime = DateTime.Now;

        if (localTime < minTime)
        {
            System.Console.WriteLine("Current time is older than view creation time: " + minTime);

            // If the dates are so dissimilar that the current date is before the creation date,
            // it is probably a good idea to use a bigger delta.
            deltaTime = new TimeSpan(24 * 365, 0, 0);

            // Set the offset to the minimum time and work up from there.
            offset = minTime - localTime;
        }

        // Storage for calculated date.
        DateTime testTime;

        // Larger divisors converge quicker, but might take longer depending on offset.
        const float stepDivisor = 10.0f;

        bool foundValid = false;

        while (true)
        {
            localTime = DateTime.Now;

            testTime = localTime.Add(offset);

            ViewConfiguration vc = ViewConfiguration.CreateFromTime(testTime);

            View tempView = new View(v, vc);

            System.Console.Write("Testing " + testTime + " (Offset " + (int)offset.TotalSeconds + ") (Delta " + deltaTime.TotalSeconds + "): ");

            // Unfortunately, there is no isValid operation.  Attempting to
            // read a property from an invalid date configuration will
            // throw an exception.
            // An alternate to this would be proferred.
            bool valid = true;
            try
            {
                string testname = tempView.RootFolder.Name;
            }
            catch (ServerException)
            {
                System.Console.WriteLine(" InValid");
                valid = false;
            }

            if (valid)
            {
                System.Console.WriteLine(" Valid");

                // If the last check was invalid, the current check is valid, and 
                // If the change is this small, the time is very close to the server time.
                if (foundValid == false && deltaTime.TotalSeconds <= 1)
                {
                    break;
                }

                foundValid = true;
                offset = offset.Add(deltaTime);
            }
            else
            {
                offset = offset.Subtract(deltaTime);

                // Once a valid time is found, start reducing the timestep.
                if (foundValid)
                {
                    foundValid = false;
                    deltaTime = new TimeSpan(0,0,Math.Max((int)(deltaTime.TotalSeconds / stepDivisor), 1));
                }
            }

        }

        System.Console.WriteLine("Run time: " + (DateTime.Now - StartTime).TotalSeconds + " seconds.");
        System.Console.WriteLine("The local time is " + localTime);
        System.Console.WriteLine("The server time is " + testTime);
        System.Console.WriteLine("The server time is offset from the local time by " + offset.TotalSeconds + " seconds.");
    }

Выход:

Testing 4/9/2009 3:05:40 PM (Offset 86400) (Delta 31536000):  InValid
Testing 4/9/2008 3:05:40 PM (Offset -31449600) (Delta 31536000):  Valid
...
Testing 4/8/2009 10:05:41 PM (Offset 25200) (Delta 3):  InValid
Testing 4/8/2009 10:05:38 PM (Offset 25197) (Delta 1):  Valid
Run time: 9.0933426 seconds.
The local time is 4/8/2009 3:05:41 PM
The server time is 4/8/2009 10:05:38 PM
The server time is offset from the local time by 25197 seconds.
1 голос
/ 28 октября 2008

Если ваш сервер StarTeam работает на компьютере с Windows, а ваш код будет выполняться на компьютере с Windows, вы можете выполнить оболочку и выполнить команду NET time , чтобы получить время на этом компьютере и сравнить по местному времени.

net time \\my_starteam_server_machine_name

, который должен вернуть:

"Current time at \\my_starteam_server_machine_name is 10/28/2008 2:19 PM"

"The command completed successfully."
0 голосов
/ 24 сентября 2008

<stab_in_the_dark> Я не знаком с этим SDK, но смотрю на API, если сервер находится в известном часовом поясе, почему бы не создать объект OLEDate, дата которого будет соответствовать времени клиента, соответствующим образом соответствующим часовому поясу сервера? </stab_in_the_dark>

...