Сравнивайте с английским: нажмите на абзац — оригинал откроется в окне. Кнопка EN под абзацем показывает его прямо в тексте.
Содержание
Введение
JUpdater – это проект, целью которого является создание утилиты, позволяющей разработчикам быстро внедрять проверку версий в Java-приложения. Утилита обеспечивает уведомление пользователя о новых версиях и позволяет легко обновляться до последней версии непосредственно из приложения, без каких-либо дополнительных действий. Утилита загружает только те файлы, которые устарели, экономя трафик. JUpdater состоит из двух частей: небольшого Java-клиента, который легко интегрируется в существующие программы, и серверной части на PHP, которая отслеживает версии и предоставляет клиенту всю необходимую информацию. Проект находится в стадии разработки и может содержать ошибки. Любое приложение, которое должно обновляться через JUpdater, должно быть упаковано в JAR-файл.
JUpdater is a project which aims to create a utility that allows developers to quickly implement version checks into Java programs. The utility ensures that the user can always be notified of new versions, and easily upgrade to the latest version from within the program, without having to do anything. The utility only downloads the files that are out of date, saving bandwidth. JUpdater is split into two parts. A small Java client, which can easily be implemented into existing programs, and a PHP server part, which keeps track of the versions and provides the client with all the info it requires. The project is still in development, possibly containing bugs. Any program that is to be updated via JUpdater has to be contained in a jar file.
Клиент
Небольшой набор классов, клиент JUpdater, необходимо добавить в программы, чтобы они могли сравнивать свои версии с центральным сервером. Клиенту требуется JRE 1.5 или выше. Клиент предоставляет три основные функции: обновление указанного JAR-файла путем сравнения MD5-контрольных сумм всех файлов (это выполняется в несколько этапов, описанных ниже); проверка наличия новой версии на сервере с использованием атрибута Implementation-Version в манифесте JAR; проверка наличия новой версии и получение соответствующего журнала изменений, также с использованием атрибута Implementation-Version. Для отслеживания процесса обновления может быть реализован интерфейс. Эту информацию можно, например, отображать в графическом пользовательском интерфейсе.
A small bundle of classes, a JUpdater client, has to be added to programs so that they can compare their versions with a central server. The client requires JRE 1.5 or greater. The client provides three main operations. Update a specified jar file by comparing all files' MD5 checksums, this is done in several steps described below. Check if a new version is available on the server by using the Implementation Version attribute in the jar manifest. Check if a new version is available and get the corresponding changelog by using the Implementation Version attribute. An interface can optionally be implemented in order to listen to the update process. This information can then for instance be displayed in a GUI for the user.
Сервер
JUpdater требует центральный сервер, содержащий информацию о последней версии. Клиенты подключаются к серверу для проверки наличия новых версий и загрузки обновлений и журнала изменений. Для работы сервера требуется PHP версии 4.3 или выше и MySQL версии 4.0 или выше.
JUpdater requires a central server that contains information about the latest version. The clients connect to the server in order to check if there are new versions and to download the changes and changelog. The server requires PHP 4.3 or greater and MySQL 4.0 or greater.
Как работает обновление
Вот подробное описание того, что на самом деле происходит за кулисами при выполнении полной проверки обновлений. Метод `updateJar` экземпляра `JUpdater` вызывается с именем файла JAR для обновления и соответствующим именем программы. Клиент открывает соединение с сервером и отправляет имя программы (через HTTP Post). Сервер устанавливает сеанс и отвечает идентификатором сеанса и URL-адресом JAR-файла сервера для этой программы. С этого момента клиент и сервер находятся в сеансе, и сервер, следовательно, запоминает, какую программу клиент хочет обновить во время всех последующих запросов, связанных с этим конкретным обновлением. Клиент сохраняет ответ сервера и отправляет запрос на список файлов JAR-файла сервера через XML RPC. Сервер отвечает списком (взятым из базы данных сервера). Клиент вычисляет контрольные суммы MD5 для всех локальных файлов, которые он может найти (просматривая список файлов с сервера), остальным присваивается контрольная сумма 0. Затем клиент отправляет результат на сервер (через XML RPC). Сервер проверяет все контрольные суммы MD5 с записями в базе данных и возвращает список всех файлов, для которых контрольные суммы не совпадают (то есть список всех устаревших файлов). Для каждого устаревшего файла обратно отправляется следующий массив: [имя файла, размер, корректная MD5] (все эти данные считываются из базы данных). Если ничего не устарело, клиент останавливается здесь, иначе продолжает работу. Клиент запрашивает журнал изменений с сервера (через XML RPC). Сервер отвечает всеми изменениями (внесенными администратором) между версиями клиента и последней версией. Клиент отображает изменения и спрашивает слушателя через `shouldStartDownloading`, следует ли загружать файлы. Если метод возвращает `false`, клиент останавливается здесь, иначе продолжает работу. Клиент начинает загружать устаревшие файлы один за другим во временное хранилище. Для каждого файла клиент вычисляет контрольную сумму MD5 и убеждается, что она совпадает, иначе повторяет попытку (пока не исчерпает число попыток). Клиент начинает процесс исправления после загрузки всех устаревших файлов. Он копирует актуальные файлы текущего JAR-файла в новый JAR-файл, а затем записывает загруженные файлы в этот JAR-файл. После успешного завершения без ошибок он заменяет старый JAR-файл на обновленный, завершая тем самым обновление.
Here's an in depth description of what actually happens behind the scenes when performing a complete update check. The JUpdater instance's updateJar method is called with the name of the jar file to update and the relevant program name. The client opens a connection to the server and sends the program name (via HTTP Post). The server establishes a session and responds with the session id and the server's jar URL for that program. From this point on the client and server are in a session and the server therefore remembers what program the client wants to update during all further requests connected to that specific update. The client stores the server's response and sends a request for the file list of the server's jar file via XML RPC. The server responds with a list (taken from the server's database). The client calculates MD5 checksums for all local files that it can find (looking in the file list from the server), the rest are given a checksum of 0. The client then sends the result to the server (via XML RPC). The server checks all MD5 checksums against the entries in the database and returns a list of all the files for which the checksums did not match (i. e. a list of all files that are out of date). The following array is sent back for each file that is out of date: [filename, size, correct md5] (all of those things are read from the database). If nothing is out of date then the client stops here, otherwise it continues. The client requests a changelog from the server (via XML RPC). The server responds with all changes (as entered by the administrator) made between the client's versions and the latest version. The client displays the changes and asks the listener with shouldStartDownloading if it should download the files. If false is returned from the method then the client stops here, otherwise it continues. The client starts downloading the out of date files one by one into a temporary storage. For each file the client calculates the MD5 checksum and make sure that it matches, otherwise it tries again (until it's out of tries). The client begins to patch once all out of date files are downloaded. It copies the current jar's up to date files into a new jar file and then writes the downloaded files into that jar. Once all is done without errors it replaces the old jar with the up to date jar, hence completing the update.