edit

Settings

Also include relevant parts to the design decision input document (is now implemented) <<Development/Settingsstructure|settings structure>>

Settings are read using methods in the class dk.netarkivet.common.utils.Settings.The declaration of the settings themselves, however, have been moved to new settings classes in each of the modules. Every module except for the Deploy module have its own Settings class and a settings.xml file containing the default values for the module settings.

In addition to that, every plug-in is intended to declare its own settings inside itself, and be associated with an xml-file containing the default values of these settings placed in the same directory as the plugin itself. For more information, please refer to the <<Configuration Manual 3.14/Configuration Basics|Configuration Basics description in the Configuration Manual>>.

Associated with most of the NetarchiveSuite plug-ins, there are also factory classes that hides the complexity behind selecting the correct plugin according to the chosen settings. The names of these classes all ends on Factory, e.g. JMSConnectionFactory, RemoteFileFactory.

Almost all configuration of NetarchiveSuite is done through the main module Settings classes as for example the dk.netarkivet.common.Settings class. It provides a simple interface to the settings.xml file as well as definitions of all current configuration default settings. The settings.xml file itself is an XML file with a structure reminiscent of the package structure.

Settings are referred to inside NetarchiveSuite by their path in the XML structure. For instance, the storeRetries setting in arcrepositoryClient under common is referred to with the string "settings.common.arcrepositoryClient.storeRetries". However, to avoid typos, each known setting has its path defined as a String constant in the Settings class, which is used throughout the code (also deploy in checks of whether the settings are known). The Settings class file also includes description of the setting in their javadoc.

To add a new general setting, the following steps need to be taken:

  1. The Settings class should get a definition for the path of the setting. This String, although a constant, must mot be declared final since settings are initialised by a static initialiser in the class

  2. Javadoc for the definition must including the path name of the setting as well as description of the setting.
  3. all default settings.xml files must be updated (including those in the unit tests).

  4. examples/settings_example.xml must be updated.

Note that there are no XML Schema to be updated, because the use of default settings means that a settings file does not need to be there, and in the case of settings for plug-ins we generally do not know which setting will be used. Note also the <<Configuration Manual 3.14|Configuration Manual>> includes a description of how deploy can be used to validate whether the settings in a settings file are valid (not necessarily exhaustive!).

JMS Channels

edit

Placement in NetarchiveSuite software

Every channel is named after the set of applications instances that are expected to receive messages sent to it. All channel names are constructed privately in the dk.netarkivet.distribute.ChannelID class. To get a channel, you must use one of the public methods in dk.netarkivet.distribute.Channels.

Channel Behavior

There are used to types of channels:

  • Queue where only one listener takes a message from the queue. For example a queue where request for doing a harvest is only received by one harvester.

  • Topic where all listeners takes a copy of the message. For example a batch job which has to be executed by all bitarchive applications.

The type of channel is not affecting the channel name directly. It is indicated by the Channel Prefix, since only channel names starting with ALL are topics, while the rest are queues.

The channel type for different queues is given in a table in the next section.

Naming Conventions

The structure of channel names are as follows:

<Environment Name>_<Channel Prefix>_<Replica Annotation>[_<Machine>][_<Application Instance>]

  • Environment Name value must be the same for all channels on all JVMs belonging to a single NetarchiveSuite installation. It identifies the environment for the queue, e.g.: "DEV", "TEST", "RELEASETEST", "CLOVER", "PROD" or initials on developer running personal environment for e.g. sanity tests. It is read from the setting settings.common.environmentName of the NetarchiveSuite installation.

  • Channel Prefix is constructed by a convention for channel behavior together with denotation of the concerned application(s). For example THE_SCHED uses the convention THE for SCHED denoting the scheduler of the harvester.

  • The conventions for channel behavior are:
    • THE - communicate with singleton in the system.

    • THIS - communicate with one uniquely identified instance of a number of distributed listeners.

    • ANY - has all instances listening to the same queue.

    • ALL - is used for topics only, i.e. topics are sent to all listeners on the channel.

  • Use Replica Id will result in a channel name with the replica identifier in question (which must match possible replicas in settings). In case of no use of replica id the COMMON will be used.

  • Use IP Node will result in a channel name with the IP address of the machine whether the application in question is placed. It is read directly from the running system.

  • In case of no use of IP Node, nothing will be written.
  • Use Application Instance Id is used, if only one process is expected to listen to the queue. It will result in a channel name with an identification of the individual application instance. It consists of the application abbreviation (uppercase letters of application name) and the application instance identifier from the settings. It is read from the common settings: settings.common.applicationName and settings.common.applicationInstanceId.

  • In case of no use of Application Instance Id, nothing will be written.
  • Channel Type is only here to complete the picture. Please refer to the section on channel behavior.

Channel names are constructed as described in the below table (columns described after the table).

Channel Prefix

Use Replica Id
(for Replica Annotation)

Use IP Node
(for Machine)

Use Application Instance Identification

Channel Type

Example

THE_SCHED

No

No

No

Queue

PROD_THE_SCHED_COMMON

ANY_HIGHPRIORITY_HACO

No

No

No

Queue

PROD_ANY_HIGHPRIORITY_HACO_COMMON

ANY_LOWPRIORITY_HACO

No

No

No

Queue

PROD_ANY_LOWPRIORITY_HACO_COMMON

THIS_REPOS_CLIENT

No

Yes

Yes

Queue

PROD_THIS_REPOS_CLIENT_COMMON_130_226_258_7_HCA_HIGH

THE_REPOS

No

No

No

Queue

PROD_THE_REPOS_COMMON

THE_BAMON

Yes

No

No

Queue

PROD_THE_BAMON_TWO

ALL_BA

Yes

No

No

Topic

PROD_ALL_BA_TWO

ANY_BA

Yes

No

No

Queue

PROD_ANY_BA_TWO

THIS_INDEX_CLIENT

No

Yes

Yes

Queue

PROD_THIS_INDEX_CLIENT_COMMON_130_226_258_7_ISA

INDEX_SERVER

No

No

No

Queue

PROD_INDEX_SERVER_COMMON

MONITOR

No

No

No

Queue

PROD_MONITOR_COMMON

ERROR

No

No

No

Queue

PROD_ERROR_COMMON

THE_CR

Yes

No

No

Queue

PROD_THE_CR_THREE

The examples are using values

  • Environment name PROD

  • Possible replica identifiers ONE or TWO

  • IP on machine 130.226.258.7

  • Application instances
    • HCA_HIGH (for HarvestControllerApplication with instance id "HIGH" )

    • ISA (for IndexServerApplication with instance id "" )

Design Notes

Note that creation of channel names for the ANY xxx_HACO-queues are designed in a way so extension to more priorities is easy.

Localization

edit

The NetarchiveSuite web pages are internationalized, that is they are ready to be translated into other languages. The default distribution contains a default (English) version and Danish, Italian, French and German versions, but adding a new language does not take any coding. All translatable strings are collected in five resource bundles, one for each of the five main modules mentioned above. The default translation files are src/dk/netarkivet/common/Translations.properties, src/dk/netarkivet/archive/Translations.properties, src/dk/netarkivet/harvester/Translations.properties, src/dk/netarkivet/viewerproxy/Translations.properties, and src/dk/netarkivet/monitor/Translations.properties.

To translate to a new language, first copy each of these files to a file in the same directory, but with _XX after Translations, where XX is the Unicode language code for the language you're going to translate into, e.g. if you're translating into Limburgish, use Translations_li.properties. If you're translating into a language that has different versions for different countries, you may need to use _XX_YY, where XX is the language code and YY is the ISO country code, e.g. Translations_fr_CA.properties for Canadian French. Then edit each of the new files to have your translation instead of the English translation for each line. Most of the important syntax should be evident from the original, but for details consult the XXX. According to the Java documentation (specifically the Javadoc of the Properties class) resource bundles should use iso-8859-1 with escaped Unicode for all other characters. It is good practice to use escaped Unicode for all non-ASCII characters as this results in files which are more-easily shared between different text-editing environments.

The translation has not been done throughout the code, only in the web-related parts. Thus log messages and unexpected error messages are in English and cannot be translated through the resource bundles.

JSP

edit

The webpages in NetarchiveSuite are written using JSP (Java Server Pages) with Apache I18N Taglib for internationalization. To support a unified look across pages from different modules, we have divided the pages into SiteSections as described in the next section. Any processing of requests happens in Java code before the web page is displayed, such that update errors can be handled with a uniform error page. Internationalization is primarily done with the taglib tags <fmt:message>, <fmt:date> etc.

The main feature of JSP is that ordinary Java (not JavaScript) can be used at server-side to generate HTML. The special tags <%...%> indicate a piece of Java code to run, while the tags <%=...> indicates a Java expression to run whose value will be inserted (as is, see escape mechanisms below) in the HTML. While it is possible to output to HTML from Java code using out.print(), it is discouraged as it a) is confusing to read, and b) does not allow for using taglibs for internationalization.

We use a number of standard methods defined in dk.common.webinterface.HTMLUtils. Of particular note are the following methods:

generateHeader()

This method takes a PageContext and generates the full header part of the HTML page, including the starting <body> tag. It should always be used to create the header, as it also creates the menu and language selection links. After this method has been called, redirection or forwarding is no longer possible, so any processing that can cause fatal errors must be done before calling generateHeader(). The title of the page is taken from the SiteSection information based on the URL used in the request.

generateFooter()
This closes the HTML page and should be called as the last thing on any JSP page.
setUTF8()
This method must be called at the very start of the JSP page to ensure that reading from the request is handled in UTF-8.
encode()

This encodes any character that is not legal to have in a URL. It should be used whenever an unknown string (or a string with known illegal characters) is made part of a URL. Note that it is not idempotent, calling it twice on a string is likely to create a mess.

escapeHTML()

This escapes any character that has special meaning in HTML (such as < or &). It should be used any time a unknown string (or a string with known special characters) is being put into HTML. Note that it is not idempotent: If you escape something twice, you get a horrible-looking mess.

encodeAndEscape()

This method combines encode() and escapeHTML() in one, which is useful when you're putting unknown strings directly into URLs in HTML.

The SiteSection system

Each part of the web site (as identified by the top-level menu items on the left side) is defined by one subclass of the SiteSection class. These sections are loaded through the <siteSection> settings, each of which connect one SiteSection class with its WAR file and the path it will appear under in the URL.

Each SiteSection subclass defines the name used in the left-hand menu, the prefix of all its pages, the number of pages visible in the left-hand menu when within this section, a suffix and title for each page in the section (including hidden pages), the directory that the section should be deployed under, and a resource bundle name for translations. Furthermore, the SiteSections have hooks for code that needs to be run on deployment and undeployment. If you want to add a new page to the section, you will only need to add a new line to the list of pages with a unique (within the SiteSection) suffix and a key for the page title, plus a default translation in the corresponding Translation.properties file. If you want it to appear in the left-hand menu, update the number of visible pages to n+1 and put your new pages as one of the first n+1 lines.

This is an example of what a simple SiteSection can look like. Note that only the first two pages from the list have entries in the left-hand menu. This class does no special initialisation and shutdown.

    public HistorySiteSection() {
        super("sitesection;history", "Harveststatus", 2,
              new String[][]{
                      {"alljobs", "pagetitle;all.jobs"},
                      {"perdomain", "pagetitle;all.jobs.per.domain"},
                      {"perhd", "pagetitle;all.jobs.per.harvestdefinition"},
                      {"perharvestrun", "pagetitle;all.jobs.per.harvestrun"},
                      {"jobdetails", "pagetitle;details.for.job"}
              }, "History",
                 dk.netarkivet.harvester.Constants.TRANSLATIONS_BUNDLE);
    }
    
    public void intitialize() {}
    public void close() {}

Processing updates

Some JSP sites cause updates when posted with specific parameters. Such parameters should always be specified in the beginning of the JSP file. All updates of underlying file systems, databases etc should happen before generateHeader() is called, so processing errors can be properly redirected. The preferred way to process updates is to create a method processRequest() in a class corresponding to the web page, but under the webinterface package of the corresponding module. This method should take the pageContext and I18N parameters from the JSP page, together they contain all the information needed from there.

In case of processing errors, the processing method should call HTMLUtils.forwardToErrorPage() and then throw a ForwardedToErrorPage exception. The JSP code should always enclose the processRequest() call in a try-catch block and return immediately if ForwardedToErrorPage is thrown. This mechanism should be used for "expected" errors, mainly illegal parameters. Errors of the "this can never happen" nature should just cause normal exceptions. Like in other code, the processRequest() method should check its parameters, but it should also check the parameters posted in the request to check that they conform to the requirements. Some methods for that purpose can be found in HTMLUtils.

I18n

We use the Apache I18n taglib for most internationalization on the web pages. This means that instead of writing different versions of a web page for different languages, we replace all natural language parts of the page with special formatting instructions. These are then used to look up translations to the language in effect in translation resource bundles.

Normal strings can be handled with the <fmt:message/> tag. If variable paratemers are introduced, such as object names or domain names, they can be passed as parameters using <fmt:message key="translation.key"><fmt:param value="<%myVal>"/></fmt:message>. Note that while the message retrieved for the key gets any HTML-specific characters escaped, the values do not and should be manually escaped. It is possible if necessary to pass HTML as parameters.

Dates should in general be entered using <fmt:formatDate type="both">, though a few places use a more explicit handling of formats. This lets the date be expressed in the native language's favorite style.

Integers and longs are handled in Java properties files with {0, number, integer} or {0, number, long} as described in MessageFormat. In JSP files we handled integer/long to strings with HTMLUtils.localiseLong(long, PageContext) or HTMLUtil.localiseLong(long, Locale).

Note the boilerplate code at the start of every page that defines output encoding, taglib usage, translation bundle, and a general-purpose I18N object. It is important that the translation bundles from the Constants class for the module you're in is used, or incomprehensible errors will occur.

    pageEncoding="UTF-8"
%><%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"
%><fmt:setLocale value="<%=HTMLUtils.getLocale(request)%>" scope="page"
/><fmt:setBundle scope="page" basename="<%=dk.netarkivet.archive.Constants.TRANSLATIONS_BUNDLE%>"/><%!
    private static final I18n I18N
            = new I18n(dk.netarkivet.archive.Constants.TRANSLATIONS_BUNDLE);
%><%

Pluggable parts

edit

Some points in NetarchiveSuite can be swapped out for other implementations, in a way similar to what Heritrix uses.

Also include relevant parts of design document that was basis for implementation of plug-ins

[To be introduced more]

How pluggability works

Factories [To be described more]

...request for suggestions on pluggability areas [To be described more]

RemoteFile

The RemoteFile interface defines how large chunks of data are transferred between machines in a NetarchiveSuite installation. This is necessary because JMS has a relatively low limit on the size of messages, well below the several hundred megabytes to over a gigabyte that is easily stored in an ARC file. There are two current implementations available in the default distribution:

  • FTPRemoteFile - this implementation uses one or more FTP servers for transfer. While this requires more setup and causes extra copying of data, the method has the advantage of allowing more protective network configurations.
  • HTTPRemoteFile - this implementation uses an embedded HTTP server in each application that wants to send a RemoteFile. Additionally, it will detect when a file transfer happens within the same machine and use local copying or renaming as applicable. For single-machine installations, this is the implementation to use. In a multi-machine installation, it does require that all machines that can send RemoteFile objects (including the bitarchive machines) must have a port accessible from the rest of the system, which may go against security polices.

  • HTTPSRemoteFile - This is an extension of HTTPRemoteFile that ensures that the communication is secure and encrypted. It is implemented with a shared certificate scheme, and only clients with access to the certificate will be able to contact the embedded HTTP server.

All three implementations will detect when 0 bytes are to be transferred and avoid creating unnecessary file in this case.

The RemoteFile interface is defined by the Java interface dk.netarkivet.common.distribute.RemoteFile:

/**
 *  RemoteFile: Interface for encapsulating remote files.
 *  Enables us to transmit large files between system components situated
 *  on different machines.
 *  Our current JMS broker(s) does not allow large message
 *  (i.e. messages > 70 MB).
 */
public interface RemoteFile extends Serializable {
    /**
     * Copy remotefile to local disk storage.
     * Used by the data recipient
     * @param destFile local File
     * @throws IOFailure on communication trouble.
     * @throws ArgumentNotValid on null parameter or non-writable file
     */
    public void copyTo(File destFile);
    /**
     * Write the contents of this remote file to an output stream.
     * @param out OutputStream that the data will be written to.  This stream
     * will not be closed by this operation.
     * @throws IOFailure If append operation fails
     * @throws ArgumentNotValid on null parameter
     */
    public void appendTo(OutputStream out);
    /**
     * Get an inputstream that contains the data transferred in this RemoteFile.
     * @return A stream object with the data in the object.  Note that the
     * close() method of this may throw exceptions if e.g. a transmission error
     * is detected.
     * @throws IOFailure on communication trouble.
     */
    public InputStream getInputStream();
    /**
     * Return the file name.
     * @return the file name
     */
    public String getName();
    /**
     * Returns a MD5 Checksum on the file. May return null, if checksums not
     * supported for this operation.
     * @return MD5 checksum
     */
    public String getChecksum();
    /**
     * Cleanup this remote file. The file is invalid after this.
     */
    public void cleanup();
    /** Returns the total size of the remote file.
     * @return Size of the remote file.
     */
    public long getSize();
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/common/distribute/RemoteFile.java?root=netarchivesuite (requires access to our code repository).

JMSConnection

The JMSConnection provides access to a specific JMS connection. The default NetarchiveSuite distribution contains only one implementation, namely JMSConnectionSunMQ which uses Sun's OpenMQ. We recommend using this implementation, as other implementations have previously been found to violate some assumptions that NetarchiveSuite depends on.

The JMSConnection interface is defined by the abstract Java class dk.netarkivet.common.distribute.JMSConnection

Implementations of this interface needs to implement the three abstract methods in this interface

ConnectionFactory getConnectionFactory() throws JMSException;
Destination getDestination(String destinationName)throws JMSException;
void onException(JMSException e);

There are more fully explained in the following transcript of the interface.

/**
 * Handles the communication with a JMS broker. Note on Thread-safety: the
 * methods and fields of JMSConnection are not accessed by multiple threads
 * (though JMSConnection itself creates threads). Thus no synchronization is
 * needed on methods and fields of JMSConnection. A shutdown hook is also added,
 * which closes the connection. Class JMSConnection is now also a
 * exceptionhandler for the JMS Connections
 */
public abstract class JMSConnection implements ExceptionListener, CleanupIF {
    /** The log. */
    private static final Log log = LogFactory.getLog(JMSConnection.class);
    /**
     * Separator used in the consumer key. Separates the ChannelName from the
     * MessageListener.toString().
     */
    protected static final String CONSUMER_KEY_SEPARATOR = "##";
    /** The number to times to (re)try whenever a JMSException is thrown. */
    protected static final int JMS_MAXTRIES = 3;
    /** The JMS Connection. */
    protected Connection connection;
    /**
     * The Session handling messages sent to / received from the NetarchiveSuite
     * queues and topics.
     */
    protected Session session;
    /** Map for caching message producers. */
    protected final Map<String, MessageProducer> producers
            = Collections.synchronizedMap(
            new HashMap<String, MessageProducer>());
    /**
     * Map for caching message consumers (topic-subscribers and
     * queue-receivers).
     */
    protected final Map<String, MessageConsumer> consumers
            = Collections.synchronizedMap(
            new HashMap<String, MessageConsumer>());
    /**
     * Map for caching message listeners (topic-subscribers and
     * queue-receivers).
     */
    protected final Map<String, MessageListener> listeners
            = Collections.synchronizedMap(
            new HashMap<String, MessageListener>());
    /**
     * Lock for the connection. Locked for read on adding/removing listeners and
     * sending messages. Locked for write when connection, releasing and
     * reconnecting.
     */
    protected final ReentrantReadWriteLock connectionLock
            = new ReentrantReadWriteLock();
    /** Shutdown hook that closes the JMS connection. */
    protected Thread closeHook;
    /**
     * Singleton pattern is be used for this class. This is the one and only
     * instance.
     */
    protected static JMSConnection instance;
    /**
     * Should be implemented according to a specific JMS broker.
     *
     * @return QueueConnectionFactory
     *
     * @throws JMSException If unable to get QueueConnectionFactory
     */
    protected abstract ConnectionFactory getConnectionFactory()
            throws JMSException;
    /**
     * Should be implemented according to a specific JMS broker.
     *
     * @param destinationName the name of the wanted Queue
     *
     * @return The destination. Note that the implementation should make sure
     *         that this is a Queue or a Topic, as required by the
     *         NetarchiveSuite design. {@link Channels#isTopic(String)}
     *
     * @throws JMSException If unable to get a destination.
     */
    protected abstract Destination getDestination(String destinationName)
            throws JMSException;
    /**
     * Exceptionhandler for the JMSConnection. Implemented according to a
     * specific JMS broker. Should try to reconnect if at all possible.
     *
     * @param e a JMSException
     */
    public abstract void onException(JMSException e);
    /** Class constructor. */
    protected JMSConnection() {
    }
    /**
     * Initializes the JMS connection. Creates and starts connection and
     * session. Adds a shutdown hook that closes down JMSConnection. Adds this
     * object as ExceptionListener for the connection.
     *
     * @throws IOFailure if initialization fails.
     */
    protected void initConnection() throws IOFailure {
        log.debug("Initializing a JMS connection " + getClass().getName());
        connectionLock.writeLock().lock();
        try {
            int tries = 0;
            JMSException lastException = null;
            boolean operationSuccessful = false;
            while (!operationSuccessful && tries < JMS_MAXTRIES) {
                tries++;
                try {
                    establishConnectionAndSession();
                    operationSuccessful = true;
                } catch (JMSException e) {
                    closeConnection();
                    log.debug("Connect failed (try " + tries + ")", e);
                    lastException = e;
                    if (tries < JMS_MAXTRIES) {
                        log.debug("Will sleep a while before trying to"
                                  + " connect again");
                        TimeUtils.exponentialBackoffSleep(tries,
                                                          Calendar.MINUTE);
                    }
                }
            }
            if (!operationSuccessful) {
                log.warn("Could not initialize JMS connection "
                         + getClass(), lastException);
                cleanup();
                throw new IOFailure("Could not initialize JMS connection "
                                    + getClass(), lastException);
            }
            closeHook = new CleanupHook(this);
            Runtime.getRuntime().addShutdownHook(closeHook);
        } finally {
            connectionLock.writeLock().unlock();
        }
    }
    /**
     * Submit an object to the destination queue. This method cannot be
     * overridden. Override the method sendMessage to change functionality.
     *
     * @param msg The NetarkivetMessage to send to the destination queue (null
     *            not allowed)
     *
     * @throws ArgumentNotValid if nMsg is null.
     * @throws IOFailure        if the operation failed.
     */
    public final void send(NetarkivetMessage msg) {
        ArgumentNotValid.checkNotNull(msg, "msg");
        log.trace("Sending message (" + msg.toString() + ") to " + msg.getTo());
        sendMessage(msg, msg.getTo());
    }
    /**
     * Sends a message msg to the channel defined by the parameter to - NOT the
     * channel defined in the message.
     *
     * @param msg Message to be sent
     * @param to  The destination channel
     */
    public final void resend(NetarkivetMessage msg, ChannelID to) {
        ArgumentNotValid.checkNotNull(msg, "msg");
        ArgumentNotValid.checkNotNull(to, "to");
        log.trace("Resending message (" + msg.toString() + ") to "
                  + to.getName());
        sendMessage(msg, to);
    }
    /**
     * Submit an object to the reply queue.
     *
     * @param msg The NetarkivetMessage to send to the reply queue (null not
     *            allowed)
     *
     * @throws ArgumentNotValid if nMsg is null.
     * @throws PermissionDenied if message nMsg has not been sent yet.
     * @throws IOFailure        if unable to reply.
     */
    public final void reply(NetarkivetMessage msg) {
        ArgumentNotValid.checkNotNull(msg, "msg");
        log.trace("Reply on message (" + msg.toString() + ") to "
                  + msg.getReplyTo().getName());
        if (!msg.hasBeenSent()) {
            throw new PermissionDenied("Message has not been sent yet");
        }
        sendMessage(msg, msg.getReplyTo());
    }
    /**
     * Method adds a listener to the given queue or topic.
     *
     * @param mq the messagequeue to listen to
     * @param ml the messagelistener
     *
     * @throws IOFailure if the operation failed.
     */
    public void setListener(ChannelID mq, MessageListener ml) throws IOFailure {
        ArgumentNotValid.checkNotNull(mq, "ChannelID mq");
        ArgumentNotValid.checkNotNull(ml, "MessageListener ml");
        setListener(mq.getName(), ml);
    }
    /**
     * Removes the specified MessageListener from the given queue or topic.
     *
     * @param mq the given queue or topic
     * @param ml a messagelistener
     *
     * @throws IOFailure On network trouble
     */
    public void removeListener(ChannelID mq, MessageListener ml)
            throws IOFailure {
        ArgumentNotValid.checkNotNull(mq, "ChannelID mq");
        ArgumentNotValid.checkNotNull(ml, "MessageListener ml");
        removeListener(ml, mq.getName());
    }
    /**
     * Clean up. Remove close connection, remove shutdown hook and null the
     * instance.
     */
    public void cleanup() {
        connectionLock.writeLock().lock();
        try {
            //Remove shutdown hook
            log.info("Starting cleanup");
            try {
                if (closeHook != null) {
                    Runtime.getRuntime().removeShutdownHook(closeHook);
                }
            } catch (IllegalStateException e) {
                //Okay, it just means we are already shutting down.
            }
            closeHook = null;
            //Close session
            closeConnection();
            //Clear list of listeners
            listeners.clear();
            instance = null;
            log.info("Cleanup finished");
        } finally {
            connectionLock.writeLock().unlock();
        }
    }
    /**
     * Close connection, session and listeners. Will ignore trouble, and simply
     * log it.
     */
    private void closeConnection() {
        // Close terminates all pending message received on the
        // connection's session's consumers.
        if (connection != null) { // close connection
            try {
                connection.close();
            } catch (JMSException e) {
                // Just ignore it
                log.warn("Error closing JMS Connection.", e);
            }
        }
        connection = null;
        session = null;
        consumers.clear();
        producers.clear();
    }
    /**
     * Unwraps a NetarkivetMessage from an ObjectMessage.
     *
     * @param msg a javax.jms.ObjectMessage
     *
     * @return a NetarkivetMessage
     *
     * @throws ArgumentNotValid when msg in valid or format of JMS Object
     *                          message is invalid
     */
    public static NetarkivetMessage unpack(Message msg)
            throws ArgumentNotValid {
        ArgumentNotValid.checkNotNull(msg, "msg");
        ObjectMessage objMsg;
        try {
            objMsg = (ObjectMessage) msg;
        } catch (ClassCastException e) {
            log.warn("Invalid message type: " + msg.getClass());
            throw new ArgumentNotValid("Invalid message type: "
                                       + msg.getClass());
        }
        NetarkivetMessage netMsg;
        String classname = "Unknown class"; // for error reporting purposes
        try {
            classname = objMsg.getObject().getClass().getName();
            netMsg = (NetarkivetMessage) objMsg.getObject();
            // Note: Id is only updated if the message does not already have an
            // id. On unpack, this means the first time the message is received.
            netMsg.updateId(msg.getJMSMessageID());
        } catch (ClassCastException e) {
            log.warn("Invalid message type: " + classname, e);
            throw new ArgumentNotValid("Invalid message type: " + classname, e);
        } catch (Exception e) {
            String message = "Message invalid. Unable to unpack "
                             + "message: " + classname;
            log.warn(message, e);
            throw new ArgumentNotValid(message, e);
        }
        log.trace("Unpacked message '" + netMsg + "'");
        return netMsg;
    }
    /**
     * Submit an ObjectMessage to the destination channel.
     *
     * @param nMsg the NetarkivetMessage to be wrapped and send as an
     *             ObjectMessage
     * @param to   the destination channel
     *
     * @throws IOFailure if message failed to be sent.
     */
    protected void sendMessage(NetarkivetMessage nMsg, ChannelID to)
            throws IOFailure {
        Exception lastException = null;
        boolean operationSuccessful = false;
        int tries = 0;
        while (!operationSuccessful && tries < JMS_MAXTRIES) {
            tries++;
            try {
                doSend(nMsg, to);
                operationSuccessful = true;
            } catch (JMSException e) {
                log.debug("Send failed (try " + tries + ")", e);
                lastException = e;
                if (tries < JMS_MAXTRIES) {
                    onException(e);
                    log.debug("Will sleep a while before trying to send again");
                    TimeUtils.exponentialBackoffSleep(tries,
                                                      Calendar.MINUTE);
                }
            } catch (Exception e) {
                log.debug("Send failed (try " + tries + ")", e);
                lastException = e;
                if (tries < JMS_MAXTRIES) {
                    reconnect();
                    log.debug("Will sleep a while before trying to send again");
                    TimeUtils.exponentialBackoffSleep(tries,
                                                      Calendar.MINUTE);
                }
            }
        }
        if (!operationSuccessful) {
            log.warn("Send failed", lastException);
            throw new IOFailure("Send failed.", lastException);
        }
    }
    /**
     * Do a reconnect to the JMSbroker. Does absolutely nothing, if already in
     * the process of reconnecting.
     */
    protected void reconnect() {
        if (!connectionLock.writeLock().tryLock()) {
            log.debug("Reconnection already in progress. Do nothing");
            return;
        }
        try {
            log.info("Trying to reconnect to jmsbroker");
            boolean operationSuccessful = false;
            Exception lastException = null;
            int tries = 0;
            while (!operationSuccessful && tries < JMS_MAXTRIES) {
                tries++;
                try {
                    doReconnect();
                    operationSuccessful = true;
                } catch (Exception e) {
                    lastException = e;
                    log.debug("Reconnect failed (try " + tries + ")", e);
                    if (tries < JMS_MAXTRIES) {
                        log.debug("Will sleep a while before trying to"
                                  + " reconnect again");
                        TimeUtils.exponentialBackoffSleep(tries,
                                                          Calendar.MINUTE);
                    }
                }
            }
            if (!operationSuccessful) {
                log.warn("Reconnect to JMS broker failed",
                         lastException);
                closeConnection();
            }
        } finally {
            // Tell everybody, that we are not trying to reconnect any longer
            connectionLock.writeLock().unlock();
        }
    }
    /**
     * Helper method for getting the right producer for a queue or topic.
     *
     * @param queueName The name of the channel
     *
     * @return The producer for that channel. A new one is created, if none
     *         exists.
     *
     * @throws JMSException If a new producer cannot be created.
     */
    private MessageProducer getProducer(String queueName) throws JMSException {
        // Check if producer is in cache
        // If it is not, it is created and stored in cache:
        MessageProducer producer = producers.get(queueName);
        if (producer == null) {
            producer = getSession().createProducer(getDestination(queueName));
            producers.put(queueName, producer);
        }
        return producer;
    }
    /**
     * Get the session. Will try reconnecting if session is null.
     *
     * @return The session.
     *
     * @throws IOFailure if no session is available, and reconnect does not
     *                   help.
     */
    private Session getSession() {
        if (session == null) {
            reconnect();
        }
        if (session == null) {
            throw new IOFailure("Session not available");
        }
        return session;
    }
    /**
     * Helper method for getting the right consumer for a queue or topic, and
     * message listener.
     *
     * @param channelName The name of the channel
     * @param ml          The message listener to add as listener to the
     *                    channel
     *
     * @return The producer for that channel. A new one is created, if none
     *         exists.
     *
     * @throws JMSException If a new producer cannot be created.
     */
    private MessageConsumer getConsumer(String channelName, MessageListener ml)
            throws JMSException {
        String key = getConsumerKey(channelName, ml);
        MessageConsumer consumer = consumers.get(key);
        if (consumer == null) {
            consumer = getSession().createConsumer(getDestination(channelName));
            consumers.put(key, consumer);
            listeners.put(key, ml);
        }
        return consumer;
    }
    /**
     * Generate a consumerkey based on the given channel name and
     * messageListener.
     *
     * @param channel         Channel name
     * @param messageListener a messageListener
     *
     * @return the generated consumerkey.
     */
    protected static String getConsumerKey(
            String channel, MessageListener messageListener) {
        return channel + CONSUMER_KEY_SEPARATOR + messageListener;
    }
    /**
     * Get the channelName embedded in a consumerKey.
     *
     * @param consumerKey a consumerKey
     *
     * @return name of channel embedded in a consumerKey
     */
    private static String getChannelName(String consumerKey) {
        //assumes argument consumerKey was created using metod getConsumerKey()
        return consumerKey.split(CONSUMER_KEY_SEPARATOR)[0];
    }
    /**
     * Helper method to establish one Connection and associated Session,
     *
     * @throws JMSException If some JMS error occurred during the creation of
     *                      the required JMS connection and session
     */
    private void establishConnectionAndSession() throws JMSException {
        // Establish a queue connection and a session
        connection = getConnectionFactory().createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.setExceptionListener(this);
        connection.start();
    }
    /**
     * Sends an ObjectMessage on a queue destination.
     *
     * @param msg the NetarkivetMessage to be wrapped and send as an
     *            ObjectMessage.
     * @param to  the destination topic.
     *
     * @throws JMSException if message failed to be sent.
     */
    private void doSend(NetarkivetMessage msg, ChannelID to)
            throws JMSException {
        connectionLock.readLock().lock();
        try {
            ObjectMessage message = getSession().createObjectMessage(msg);
            synchronized (msg) {
                getProducer(to.getName()).send(message);
                // Note: Id is only updated if the message does not already have
                // an id. This ensures that resent messages keep the same ID
                msg.updateId(message.getJMSMessageID());
            }
        } finally {
            connectionLock.readLock().unlock();
        }
        log.trace("Sent message '" + msg.toString() + "'");
    }
    /**
     * Method adds a listener to the given queue or topic.
     *
     * @param channelName the messagequeue to listen to
     * @param ml          the messagelistener
     *
     * @throws IOFailure if the operation failed.
     */
    private void setListener(String channelName, MessageListener ml) {
        log.debug("Adding " + ml.toString() + " as listener to "
                  + channelName);
        String errMsg = "JMS-error - could not add Listener to queue/topic: "
                        + channelName;
        int tries = 0;
        boolean operationSuccessful = false;
        Exception lastException = null;
        while (!operationSuccessful && tries < JMS_MAXTRIES) {
            tries++;
            try {
                connectionLock.readLock().lock();
                try {
                    getConsumer(channelName, ml).setMessageListener(ml);
                } finally {
                    connectionLock.readLock().unlock();
                }
                operationSuccessful = true;
            } catch (JMSException e) {
                lastException = e;
                log.debug("Set listener failed (try " + tries + ")", e);
                if (tries < JMS_MAXTRIES) {
                    onException(e);
                    log.debug("Will sleep a while before trying to set listener"
                              + " again");
                    TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
                }
            } catch (Exception e) {
                lastException = e;
                log.debug("Set listener failed (try " + tries + ")", e);
                if (tries < JMS_MAXTRIES) {
                    reconnect();
                    log.debug("Will sleep a while before trying to set listener"
                              + " again");
                    TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
                }
            }
        }
        if (!operationSuccessful) {
            log.warn(errMsg, lastException);
            throw new IOFailure(errMsg, lastException);
        }
    }
    /**
     * Remove a messagelistener from a channel (a queue or a topic).
     *
     * @param ml          A specific MessageListener
     * @param channelName a channelname
     */
    private void removeListener(MessageListener ml, String channelName) {
        String errMsg = "JMS-error - could not remove Listener from "
                        + "queue/topic: " + channelName;
        int tries = 0;
        Exception lastException = null;
        boolean operationSuccessful = false;
        log.info("Removing listener from channel '" + channelName + "'");
        while (!operationSuccessful && tries < JMS_MAXTRIES) {
            try {
                tries++;
                connectionLock.readLock().lock();
                try {
                    MessageConsumer messageConsumer = getConsumer(channelName,
                                                                  ml);
                    messageConsumer.close();
                    consumers.remove(getConsumerKey(channelName, ml));
                    listeners.remove(getConsumerKey(channelName, ml));
                } finally {
                    connectionLock.readLock().unlock();
                }
                operationSuccessful = true;
            } catch (JMSException e) {
                lastException = e;
                log.debug("Remove  listener failed (try " + tries + ")", e);
                onException(e);
                log.debug("Will and sleep a while before trying to remove"
                          + " listener again");
                TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
            } catch (Exception e) {
                lastException = e;
                log.debug("Remove  listener failed (try " + tries + ")", e);
                reconnect();
                log.debug("Will and sleep a while before trying to remove"
                          + " listener again");
                TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
            }
        }
        if (!operationSuccessful) {
            log.warn(errMsg, lastException);
            throw new IOFailure(errMsg, lastException);
        }
    }
    /**
     * Reconnect to JMSBroker and reestablish session. Resets senders and
     * publishers.
     *
     * @throws JMSException If unable to reconnect to JMSBroker and/or
     *                      reestablish sesssions
     */
    private void doReconnect()
            throws JMSException {
        closeConnection();
        establishConnectionAndSession();
        // Add listeners already stored in the consumers map
        log.debug("Re-add listeners");
        for (Map.Entry<String, MessageListener> listener
                : listeners.entrySet()) {
            setListener(getChannelName(listener.getKey()),
                        listener.getValue());
        }
        log.info("Reconnect successful");
    }
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/common/distribute/JMSConnection.java?root=netarchivesuite (requires access to our code repository).

ArcRepositoryClient

The ArcRepositoryClient handles access to the Archive module, both upload and low-level access. There are two implementations in the default distribution:

  • JMSArcRepositoryClient - this is a full-fledged distributed implementation using JMS for communication, allowing multiple locations with multiple machines each.
  • LocalArcRepositoryClient - An ARC repository implementation that stores all files in a local directories.

The ArcRepositoryClient interface is defined by the Java interface dk.netarkivet.common.distribute.arcrepository.ArcRepositoryClient:

/**
 * Generic interface defining all methods that an ArcRepository provides.
 * Typically, an application using this will only see one of the restricted
 * superinterfaces.
 *
 */
public interface ArcRepositoryClient extends
        HarvesterArcRepositoryClient, ViewerArcRepositoryClient,
                PreservationArcRepositoryClient {
    /** Call on shutdown to release external resources. */
    void close();
    /**
     * Gets a single ARC record out of the ArcRepository.
     *
     * @param arcfile The name of a file containing the desired record.
     * @param index   The offset of the desired record in the file
     * @return a BitarchiveRecord-object, or null if request times out or object
     * is not found.
     * @throws IOFailure If the get operation failed.
     * @throws ArgumentNotValid if the given arcfile is null or empty string,
     * or the given index is negative.
     */
    BitarchiveRecord get(String arcfile, long index) throws ArgumentNotValid;
    /**
     * Retrieves a file from an ArcRepository and places it in a local file.
     * @param arcfilename Name of the arcfile to retrieve.
     * @param replica The bitarchive to retrieve the data from. On
     * implementations with only one replica, null may be used.
     * @param toFile Filename of a place where the file fetched can be put.
     * @throws IOFailure if there are problems getting a reply or the file
     * could not be found.
     */
    void getFile(String arcfilename, Replica replica, File toFile);
    /**
     * Store the given file in the ArcRepository.  After storing, the file is
     * deleted.
     *
     * @param file A file to be stored. Must exist.
     * @throws IOFailure thrown if store is unsuccessful, or failed to clean
     * up files after the store operation.
     * @throws ArgumentNotValid if file parameter is null or file is not an
     *                          existing file.
     */
    void store(File file) throws IOFailure, ArgumentNotValid;
    /**
     * Runs a batch batch job on each file in the ArcRepository.
     *
     * @param job An object that implements the FileBatchJob interface. The
     *  initialize() method will be called before processing and the finish()
     *  method will be called afterwards. The process() method will be called
     *  with each File entry.
     *
     * @param replicaId The archive to execute the job on.
     * @return The status of the batch job after it ended.
     */
    BatchStatus batch(FileBatchJob job, String replicaId);
    /** Updates the administrative data in the ArcRepository for a given
     * file and replica.
     *
     * @param fileName The name of a file stored in the ArcRepository.
     * @param bitarchiveId The id of the replica that the administrative
     * data for fileName is wrong for.
     * @param newval What the administrative data will be updated to.
     */
    void updateAdminData(String fileName, String bitarchiveId,
                         ReplicaStoreState newval);
    /** Updates the checksum kept in the ArcRepository for a given
     * file.  It is the responsibility of the ArcRepository implementation to
     * ensure that this checksum matches that of the underlying files.
     *
     * @param filename The name of a file stored in the ArcRepository.
     * @param checksum The new checksum.
     */
    void updateAdminChecksum(String filename, String checksum);
    /** Remove a file from one part of the ArcRepository, retrieving a copy
     * for security purposes.  This is typically used when repairing a file
     * that has been corrupted.
     *
     * @param fileName The name of the file to remove.
     * @param bitarchiveId The id of the replica from which to remove the file.
     * @param checksum The checksum of the file to be removed.
     * @param credentials A string that shows that the user is allowed to
     * perform this operation.
     * @return A local copy of the file removed.
     */
    File removeAndGetFile(String fileName, String bitarchiveId,
                          String checksum, String credentials);
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/common/distribute/arcrepository/ArcRepositoryClient.java?root=netarchivesuite(requires access to our code repository).

IndexClient

The IndexClient provides the Lucene indices that are used for deduplication and for viewerproxy access. It makes use of the ArcRepositoryClient to fetch data from the archive and implements several layers of caching of these data and of Lucene-indices created from the data. It is advisable to perform regular clean-up of the cache directories.

The IndexClient interface is defined by the Java interface dk.netarkivet.common.distribute.indexserver.JobIndexCache:

/** An interface to a cache of data for jobs. */
public interface JobIndexCache {
    /** Get an index for the given list of job IDs.
     * The resulting file contains a suitably sorted list.
     * This method should always be safe for asynchronous calling.
     * This method may use a cached version of the file.
     *
     * @param jobIDs Set of job IDs to generate index for.
     * @return An index, consisting of a file and the set this is an index for.
     * This file must not be modified or deleted, since it is part of the cache
     * of data.
     */
    Index<Set<Long>> getIndex(Set<Long> jobIDs);

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/common/distribute/indexserver/JobIndexCache.java?root=netarchivesuite (requires access to our code repository).

Archive Admin DBSpecifics

Defines functionality specific to the type of database for the Archive Admin databse, see Javadoc for details.

Harvester DBSpecifics

Defines functionality specific to the type of database used for the Harvester module, see Javadoc for details.

Notifications

The Notifications interface lets you choose how you want important error notifications to be handled in your system. Two implementations exist, one to send emails, and one to print the messages to System.err. Adding more specialised plugins should be easy.

The Notifications interface is defined by the abstract class dk.netarkivet.common.utils.Notifications:

/**
 * This class encapsulates reacting to a serious error message.
 *
 */
public abstract class Notifications {
    /**
     * Notify about an error event. This is the same as calling
     * {@link #errorEvent(String, Throwable)} with null as the second parameter.
     *
     * @param message The error message to notify about.
     */
    public void errorEvent(String message) {
        errorEvent(message, null);
    }
    /**
     * Notifies about an error event including an exception.
     *
     * @param message The error message to notify about.
     * @param e       The exception to notify about.
     * May be null for no exception.
     */
    public abstract void errorEvent(String message, Throwable e);
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/common/utils/Notifications.java?root=netarchivesuite (requires access to our code repository).

HeritrixController

The HeritrixController interface defines our interface for initialize a running Heritrix instance and communicate with this instance. We have an implementation that starts heritrix as its own process and then communicates with it using JMX (JMXHeritrixController), and a deprecated implementation with heritrix embedded inside NetarchiveSuite (DirectHeritrixController), which controls Heritrix using a CrawlController instance.

The HeritrixController interface is defined by the Java interface dk.netarkivet.harvester.harvesting.HeritrixController:

/**
 * This interface encapsulates the direct access to Heritrix, allowing
 * for accessing in various ways (direct class access or JMX).  Heritrix is
 * expected to perform one crawl for each instance of an implementing class.
 *
 */
public interface HeritrixController {
    /** Initialize a new CrawlController for executing a Heritrix crawl.
     * This does not start the crawl.
     *
     */
    void initialize();
    /** Request that Heritrix start crawling.  When this method returns,
     * either Heritrix has failed in the early stages, or the crawljob has
     * been successfully created.  Actual crawling will commence at some
     * point hereafter.
     * @throws IOFailure If something goes wrong during startup.
     */
    void requestCrawlStart() throws IOFailure;
    /** Tell Heritrix to stop crawling.  Heritrix may take a while to actually
     * stop, so you cannot assume that crawling is stopped when this method
     * returns.
     */
    void beginCrawlStop();
    /** Request that crawling stops.
     * This makes a call to beginCrawlStop(), unless the crawler
     * is already shutting down. In that case it does nothing.
     *
     * @param reason A human-readable reason the crawl is being stopped.
     */
    void requestCrawlStop(String reason);
    /** Query whether Heritrix is in a state where it can finish crawling.
     *  Returns true if no uris remain to be harvested, or it has met
     *  either the maxbytes limit, the document limit,
     *  or the time-limit for the current harvest.
     *
     * @return True if Heritrix thinks it is time to stop crawling.
     */
    boolean atFinish();
    /** Returns true if the crawl has ended, either because Heritrix finished
     * or because we terminated it.
     *
     * @return True if the CrawlEnded event has happened in Heritrix,
     * indicating that all crawls have stopped.
     */
    boolean crawlIsEnded();
    /**
     * Get the number of currently active ToeThreads (crawler threads).
     * @return Number of ToeThreads currently active within Heritrix.
     */
    int getActiveToeCount();
    /** Get the number of URIs currently on the queue to be processed.  This
     * number may not be exact and should only be used in informal texts.
     *
     * @return How many URIs Heritrix have lined up for processing.
     */
    long getQueuedUriCount();
    /**
     * Get an estimate of the rate, in kb, at which documents
     * are currently being processed by the crawler.
     * @see org.archive.crawler.framework.StatisticsTracking#currentProcessedKBPerSec()
     * @return Number of KB data downloaded by Heritrix over an undefined
     * interval up to now.
     */
    int getCurrentProcessedKBPerSec();
    /** Get a human-readable set of statistics on the progress of the crawl.
     *  The statistics is
     *  discovered uris, queued uris, downloaded uris, doc/s(avg), KB/s(avg),
     *  dl-failures, busy-thread, mem-use-KB, heap-size-KB, congestion,
     *  max-depth, avg-depth.
     *  If no statistics are available, the string "No statistics available"
     *  is returned.
     *  Note: this method may disappear in the future.
     *
     * @return Some ascii-formatted statistics on the progress of the crawl.
     */
    String getProgressStats();
    /** Returns true if the crawler has been paused, and thus not
     * supposed to fetch anything.  Heritrix may still be fetching stuff, as
     * it takes some time for it to go into full pause mode.  This method can
     * be used as an indicator that we should not be worried if Heritrix
     * appears to be idle.
     *
     * @return True if the crawler has been paused, e.g. by using the
     * Heritrix GUI.
     */
    boolean isPaused();
    /** Release any resources kept by the class.
     */
    void cleanup();
    /**
     * Get harvest information. An example of this can be an URL pointing
     * to the GUI of a running Heritrix process.
     * @return information about the harvest process.
     */
    String getHarvestInformation();
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/harvester/harvesting/HeritrixController.java?root=netarchivesuite (requires access to our code repository).

ActiveBitPreservation

The ActiveBitpreservaton interface defines our interface for initializing bitpreservation actions from our GUI. We have a filebased and a database based implementations. Both these implementations communicate with the archive through the ArcRepository interface.

The ActiveBitPreservation interface is defined by the Java interface dk.netarkivet.archive.arcrepository.bitpreservation.ActiveBitPreservation:

/**
 * All bitpreservation implementations are assumed to have access to admin data
 * and bitarchives. Operations may request information from the bitarchive by
 * sending batch jobs, reading admin data directly, or reading from cached
 * information from either.
 */
public interface ActiveBitPreservation {
    // General state
    /**
     * Get details of the state of one or more files in the bitarchives
     * and admin data.
     *
     * @param filenames the list of filenames to investigate
     * @return a map ([filename]-> [FilePreservationState]) with the
     *  preservationstate of all files in the list.
     *  The preservationstates in the map will be null for all filenames,
     *  that are not found in admin data.
     */
    Map<String, PreservationState> getPreservationStateMap(
            String... filenames);
    /**
     * Get the details of the state of the given file in the bitarchives
     * and admin data.
     *
     * @param filename A given file
     * @return the FilePreservationState for the given file. This will be null,
     * if the filename is not found in admin data.
     */
    PreservationState getPreservationState(String filename);

    // Check state for bitarchives
    /**
     * Return a list of files marked as missing on this replica.
     * A file is considered missing if it exists in admin data, but is not known
     * in the bit archives. Guaranteed not to recheck the archive, simply
     * returns the list generated by the last test.
     *
     * @param replica The replica to get missing files from.
     * @return A list of missing files.
     */
    Iterable<String> getMissingFiles(Replica replica);
    /**
     * Return a list of files with changed checksums on this replica.
     * A file is considered changed if checksum does not compare to
     * admin data. Guaranteed not to recheck the archive, simply returns the
     * list generated by the last test.
     *
     * @param replica The replica to get a list of changed files from.
     * @return A list of files with changed checksums.
     */
    Iterable<String> getChangedFiles(Replica replica);
    /** Update the list of files in a given bitarchive. This will be used for
     * the next call to getMissingFiles.
     *
     * @param replica The replica to update list of files for.
     */
    void findMissingFiles(Replica replica);
    /** Update the list of checksums in a given replica. This will be used
     * for the next call to getChangedFiles.
     *
     * @param replica The replica to update list of files for.
     */
    void findChangedFiles(Replica replica);
    /**
     * Return the number of missing files for replica. Guaranteed not to
     * recheck the archive, simply returns the number generated by the last
     * test.
     *
     * @param replica The replica to get the number of missing files from.
     * @return The number of missing files.
     */
    long getNumberOfMissingFiles(Replica replica);
    /**
     * Return the number of changed files for replica. Guaranteed not to
     * recheck the archive, simply returns the number generated by the last
     * test.
     *
     * @param replica The replica to get the number of changed files from.
     * @return The number of changed files.
     */
    long getNumberOfChangedFiles(Replica replica);
    /**
     * Return the total number of files for replica. Guaranteed not to
     * recheck the archive, simply returns the number generated by the last
     * update.
     *
     * @param replica The replica to get the number of files from.
     * @return The number of files.
     */
    long getNumberOfFiles(Replica replica);
    /**
     * Return the date for last check of missing files for replica. Guaranteed
     * not to recheck the archive, simply returns the date for the
     * last test.
     *
     * @param replica The replica to get date for changed files from.
     * @return The date for last check of missing files.
     */
    Date getDateForMissingFiles(Replica replica);
    /**
     * Return the date for last check of changed files for replica. Guaranteed
     * not to recheck the archive, simply returns the date for the
     * last test.
     *
     * @param replica The replica to get date for changed files from.
     * @return The date for last check of changed files.
     */
    Date getDateForChangedFiles(Replica replica);
    // Update files in bitarchives
    /**
     * Check that files are indeed missing on the given replica, and present
     * in admin data and reference replica. If so, upload missing files from
     * reference replica to this replica.
     *
     * @param replica The replica to restore files to
     * @param filenames The names of the files.
     */
    void uploadMissingFiles(Replica replica, String... filenames);
    /**
     * Check that the checksum of the file is indeed different to the value in
     * admin data and reference replica. If so, remove missing file and upload
     * it from reference replica to this replica.
     *
     * @param replica The replica to restore file to
     * @param filename The name of the file
     * @param credentials The credentials used to perform this replace operation
     * @param checksum  The known bad checksum. Only a file with this bad
     * checksum is attempted repaired.
     */
    void replaceChangedFile(Replica replica, String filename,
                            String credentials, String checksum);
    // Check state for admin data
    /**
     * Return a list of files represented in replica but missing in AdminData.
     *
     * @return A list of missing files.
     */
    Iterable<String> getMissingFilesForAdminData();
    /**
     * Return a list of files with wrong checksum or state in admin data.
     *
     * @return A list of files with wrong checksum or state.
     */
    Iterable<String> getChangedFilesForAdminData();
    // Update admin data
    /**
     * Add files unknown in admin.data to admin.data.
     *
     * @param filenames The files to add.
     */
    void addMissingFilesToAdminData(String... filenames);
    /**
     * Reestablish admin data to match bitarchive states for file.
     *
     * @param filename The file to reestablish state for.
     */
    void changeStateForAdminData(String filename);
}

The above code may differ from the latest version in our repository: https://gforge.statsbiblioteket.dk/plugins/scmsvn/viewcvs.php/*checkout*/trunk/src/dk/netarkivet/archive/arcrepository/bitpreservation/ActiveBitPreservation.java?root=netarchivesuite (requires access to our code repository).

XML handling by Deploy

edit

Deploy needs to create a settings file in the xml fileformat for each application. The creation of these files involves the ability to manipulate the xml datastructure, create new xml instances based on previous ones and save the result to a file.

The existing XMLTree class (under dk.netarkivet.common.utils) did not support these abilities, and it would require a larger structural change of the class to meet these demands.

A new class (dk.netarkivet.deploy.XmlStructure) has therefore been implemented to meet the requests for handling the xml datastructure. This class uses the com.dom4j structure for handling the xml datastructure.

The dk.netarkivet.deploy.XmlStructure class has the ability to inherit and overwrite, which is used in the deploy configuration structure. The abilty to inherit is implemented as creating a new instance identical to a current instance, thus inheritance can only occour during creation of a new instance of this class.

The overwrite function merges the current XmlStructure with a new tree. This means that the leafs which are present in both new tree and the current one, the value in the current leaf will be overwritten by the leaf on the new tree. Branches which only exists in the new tree will be appended to the current tree. The branches in both trees are recursively overwritten

System Design 3.16/Coding Guidelines - Design Related (last edited 2011-04-27 12:29:31 by MikisSethSorensen)