diff --git a/src/main/java/gov/usgs/earthquake/aws/AwsBatchIndexer.java b/src/main/java/gov/usgs/earthquake/aws/AwsBatchIndexer.java index 5e940d1a..28e8f679 100644 --- a/src/main/java/gov/usgs/earthquake/aws/AwsBatchIndexer.java +++ b/src/main/java/gov/usgs/earthquake/aws/AwsBatchIndexer.java @@ -37,15 +37,22 @@ * and call indexer.onProduct. */ public class AwsBatchIndexer implements Bootstrappable { - + /** Force reindex argument */ public static final String FORCE_REINDEX_ARGUMENT = "--force"; + /** Get product URL argument */ public static final String GET_PRODUCT_URL_ARGUMENT = "--getProductUrl="; + /** Argument for indexer configuration name */ public static final String INDEXER_CONFIG_NAME_ARGUMENT="--indexerConfigName="; + /** Default indexer configuration name */ public static final String INDEXER_CONFIG_NAME_DEFAULT = "indexer"; + /** Argument for database driver */ public static final String DATABASE_DRIVER_ARGUMENT = "--databaseDriver="; + /** Argument for database URL */ public static final String DATABASE_URL_ARGUMENT = "--databaseUrl="; + /** Argument for indexer database */ public static final String INDEXER_DATABASE_ARGUMENT = "--indexerDatabase="; + /** Default database for indexer */ public static final String INDEXER_DATABASE_DEFAULT = "indexer"; /** Logging object. */ @@ -110,7 +117,7 @@ public void run(String[] args) throws Exception { * @param id * which product. * @return URL with placeholders replaced. - * @throws Exception + * @throws Exception Exception */ public URL getProductUrl(final ProductId id) throws Exception { String url = getProductUrlTemplate; @@ -127,7 +134,7 @@ public URL getProductUrl(final ProductId id) throws Exception { * @param id * which product. * @return Product object. - * @throws Exception + * @throws Exception Exception */ public Product getProduct(final ProductId id) throws Exception { final URL url = getProductUrl(id); @@ -171,6 +178,14 @@ public void processProductId(final ProductId id) { } } + /** + * Read product ids (as urns) from database and submit to executor for processing. + * + * @param driver database driver + * @param url database url + * + * @throws Exception exception + */ public void readProductIdsFromDatabase( final String driver, final String url) throws Exception { @@ -232,7 +247,7 @@ public void readProductIdsFromDatabase( /** * Read product ids (as urns) from stdin and submit to executor for processing. * - * @throws Exception + * @throws Exception Exception */ public void readProductIdsFromStdin() throws Exception { // read product ids from stdin @@ -261,7 +276,7 @@ public void readProductIdsFromStdin() throws Exception { * * @param id * which product - * @throws InterruptedException + * @throws InterruptedException InterruptedException */ public void submitProductId(final ProductId id) throws InterruptedException { // queue for processing diff --git a/src/main/java/gov/usgs/earthquake/aws/AwsProductReceiver.java b/src/main/java/gov/usgs/earthquake/aws/AwsProductReceiver.java index 4bbc3ef0..ae5fe964 100644 --- a/src/main/java/gov/usgs/earthquake/aws/AwsProductReceiver.java +++ b/src/main/java/gov/usgs/earthquake/aws/AwsProductReceiver.java @@ -31,20 +31,31 @@ */ public class AwsProductReceiver extends DefaultNotificationReceiver implements Runnable, WebSocketListener { + /** Initialzation of logger. For us later in file. */ public static final Logger LOGGER = Logger .getLogger(AwsProductReceiver.class.getName()); - + /** Variable for URI string */ public static final String URI_PROPERTY = "url"; + /** Variable for createdAfter string */ public static final String CREATED_AFTER_PROPERTY = "createdAfter"; + /** Variable for trackingIndex string */ public static final String TRACKING_INDEX_PROPERTY = "trackingIndex"; + /** Variable for trackingFileName string */ public static final String TRACKING_FILE_NAME_PROPERTY = "trackingFileName"; + /** Variable for connectAttempts string */ public static final String CONNECT_ATTEMPTS_PROPERTY = "connectAttempts"; + /** Variable for connectTimeout string */ public static final String CONNECT_TIMEOUT_PROPERTY = "connectTimeout"; + /** Variable for initialCatchUpAge string */ public static final String INITIAL_CATCHUP_AGE_PROPERTY = "initialCatchUpAge"; + /** Variable for tracking file. Links to data/AwsReceiver.json */ public static final String DEFAULT_TRACKING_FILE_NAME = "data/AwsReceiver.json"; + /** Variable for connect attempts. Set to 5 */ public static final String DEFAULT_CONNECT_ATTEMPTS = "5"; + /** Variable for timout. Set to 1000 */ public static final String DEFAULT_CONNECT_TIMEOUT = "1000"; + /** Variable for catchup age. Set to 7.0 */ public static final String DEFAULT_INITIAL_CATCHUP_AGE = "7.0"; private URI uri; @@ -55,30 +66,31 @@ public class AwsProductReceiver extends DefaultNotificationReceiver implements R private TrackingIndex trackingIndex; private WebSocketClient client; - /* Websocket session */ + /** Websocket session */ private Session session; - /* µs timestamp of last message that has been processed */ + /** µs timestamp of last message that has been processed */ protected Instant createdAfter = null; /** How far back to check when first connecting. */ protected double initialCatchUpAge = Double.valueOf(DEFAULT_INITIAL_CATCHUP_AGE); - /* last broadcast message that has been processed (used for catch up) */ + /** last broadcast message that has been processed (used for catch up) */ protected JsonNotification lastBroadcast = null; + /** ID of the previously mentioned last broadcast */ protected Long lastBroadcastId = null; - /* whether to process broadcast messages (after catching up). */ + /** whether to process broadcast messages (after catching up). */ protected boolean processBroadcast = false; - /* whether currenting catching up. */ + /** whether currenting catching up. */ protected boolean catchUpRunning = false; - /* sync object for catchUp state. */ + /** sync object for catchUp state. */ protected final Object catchUpSync = new Object(); - /* thread where catch up process runs. */ + /** thread where catch up process runs. */ protected Thread catchUpThread = null; - /* whether thread should continue running (shutdown flag) */ + /** whether thread should continue running (shutdown flag) */ protected boolean catchUpThreadRunning = false; - /* last catch up message sent (for response timeouts) */ + /** last catch up message sent (for response timeouts) */ protected Instant lastCatchUpSent = null; @Override @@ -160,7 +172,7 @@ public void onClose(Session session, CloseReason closeReason) { * compares state of latest product to determine whether caught up and if * broadcasts should be processed. * - * @param message + * @param message Message notification - string */ @Override synchronized public void onMessage(String message) throws IOException { @@ -191,8 +203,8 @@ synchronized public void onMessage(String message) throws IOException { * If caught up process notification as usual, otherwise save notification * to help detect when caught up. * - * @param json - * @throws Exception + * @param json JSON Message + * @throws Exception Exception */ protected void onBroadcast(final JsonObject json) throws Exception { final JsonNotification notification = new JsonNotification( @@ -230,8 +242,8 @@ protected void onBroadcast(final JsonObject json) throws Exception { /** * Process a received notification and update current "created" timestamp. * - * @param notification - * @throws Exception + * @param notification JSON Notification + * @throws Exception Exception */ protected void onJsonNotification(final JsonNotification notification) throws Exception { // receive and notify listeners @@ -246,8 +258,8 @@ protected void onJsonNotification(final JsonNotification notification) throws Ex /** * Handle a message with "action"="product", which is received during catch up. * - * @param json - * @throws Exception + * @param json JSON Message + * @throws Exception Exception */ protected void onProduct(final JsonObject json) throws Exception { final JsonNotification notification = new JsonNotification( @@ -264,8 +276,8 @@ protected void onProduct(final JsonObject json) throws Exception { * Check whether caught up, and either switch to broadcast mode or continue * catch up process. * - * @param json - * @throws Exception + * @param json JSON Message + * @throws Exception Exception */ protected void onProductsCreatedAfter(final JsonObject json) throws Exception { final String after = json.getString("created_after"); @@ -362,6 +374,8 @@ public void run() { * The server will reply with zero or more "action"="product" messages, and * then one "action"="products_created_after" message to indicate the request * is complete. + * + * @throws IOException IOException */ protected void sendProductsCreatedAfter() throws IOException { // set default for created after @@ -460,7 +474,7 @@ public void onReconnectFail() { * Reads createdAfter from a tracking file if it exists, * then connects to web socket. * - * @throws Exception + * @throws Exception Exception */ @Override public void startup() throws Exception{ @@ -485,7 +499,7 @@ public void startup() throws Exception{ /** * Closes web socket - * @throws Exception + * @throws Exception Exception */ @Override public void shutdown() throws Exception { @@ -502,7 +516,7 @@ public void shutdown() throws Exception { * Reads tracking file. * * @return JsonObject tracking file - * @throws Exception + * @throws Exception Exception */ public JsonObject readTrackingData() throws Exception { // use name as key @@ -512,7 +526,7 @@ public JsonObject readTrackingData() throws Exception { /** * Writes tracking file. * - * @throws Exception + * @throws Exception Exception */ public void writeTrackingData() throws Exception { JsonObject json = Json.createObjectBuilder() @@ -523,42 +537,82 @@ public void writeTrackingData() throws Exception { trackingIndex.setTrackingData(getName(), json); } + /** + * Getter for URI + * @return URI + */ public URI getURI() { return uri; } + /** + * Setter for URI + * @param uri URI + */ public void setURI(final URI uri) { this.uri = uri; } + /** + * Getter for trackingFileName + * @return name of tracking file + */ public String getTrackingFileName() { return trackingFileName; } + /** + * Setter for trackingFileName + * @param trackingFileName trackingFileName + */ public void setTrackingFileName(final String trackingFileName) { this.trackingFileName = trackingFileName; } + /** + * Getter for createdAfter + * @return createdAfter + */ public Instant getCreatedAfter() { return createdAfter; } + /** + * Setter for createdAfter + * @param createdAfter createdAfter + */ public void setCreatedAfter(final Instant createdAfter) { this.createdAfter = createdAfter; } + /** + * Getter for attempts + * @return attempts + */ public int getAttempts() { return attempts; } + /** + * Setter for attempts + * @param attempts attempts + */ public void setAttempts(final int attempts) { this.attempts = attempts; } + /** + * Getter for timeout + * @return timeout + */ public long getTimeout() { return timeout; } + /** + * Setter for timeout + * @param timeout long timeout + */ public void setTimeout(final long timeout) { this.timeout = timeout; } diff --git a/src/main/java/gov/usgs/earthquake/aws/AwsProductSender.java b/src/main/java/gov/usgs/earthquake/aws/AwsProductSender.java index 61f03066..bba8bbfe 100644 --- a/src/main/java/gov/usgs/earthquake/aws/AwsProductSender.java +++ b/src/main/java/gov/usgs/earthquake/aws/AwsProductSender.java @@ -31,6 +31,7 @@ /** Send using AWS Hub API. */ public class AwsProductSender extends DefaultConfigurable implements ProductSender { + /** Initialzation of logger. For us later in file. */ public static final Logger LOGGER = Logger.getLogger(AwsProductSender.class.getName()); /** Base URL for Hub API. */ @@ -40,19 +41,19 @@ public class AwsProductSender extends DefaultConfigurable implements ProductSend /** Whether to sign products using private key. */ public static final String SIGN_PRODUCTS_PROPERTY = "signProducts"; - // url where products are sent + /**url where products are sent */ protected URL hubUrl; - // signing key + /** signing key */ protected PrivateKey privateKey; - // whether to sign products + /** wheter to sign products */ protected boolean signProducts = false; - // 5s seems excessive, but be cautious for now + /** Connection timeout. 5s seems excessive, but be cautious for now */ protected int connectTimeout = 5000; - // this corresponds to server-side timeout - // read timeout applies once getInputStream().read() is called + /** Server-side timeout. Called at getInputStream().read() */ protected int readTimeout = 30000; + /** Empty class constructor */ public AwsProductSender() {} public AwsProductSender(URL url) { @@ -208,7 +209,7 @@ public void sendProduct(final Product product) throws Exception { * * @param json product in json format. * @return product with content urls set to upload URLs. - * @throws Exception + * @throws Exception Exception */ protected Product getUploadUrls(final JsonObject json) throws Exception { final URL url = new URL(hubUrl, "get_upload_urls"); @@ -238,10 +239,10 @@ protected Product getUploadUrls(final JsonObject json) throws Exception { * This is a HTTP POST method, * with a JSON content body with a "product" property with the product. * - * @param url - * @param product - * @return - * @throws Exception + * @param url url of connection + * @param product product in json format + * @return new HTTP POST response + * @throws Exception Exception */ protected HttpResponse postProductJson(final URL url, final JsonObject product) throws Exception { // send as attribute, for extensibility @@ -263,7 +264,7 @@ protected HttpResponse postProductJson(final URL url, final JsonObject product) * * @param json product in json format. * @return product with content urls pointing to hub. - * @throws Exception + * @throws Exception Exception */ protected Product sendProduct(final JsonObject json) throws Exception { // send request @@ -304,8 +305,8 @@ protected Product sendProduct(final JsonObject json) throws Exception { * @param path content path. * @param content content to upload. * @param signedUrl url where content should be uploaded. - * @return - * @throws Exception + * @return HTTP result + * @throws Exception Exception */ protected HttpResponse uploadContent(final String path, final Content content, final URL signedUrl) throws Exception { @@ -399,19 +400,30 @@ protected Map uploadContents( } return uploadResults; } - + /** Getter for signProducts + * @return boolean + */ public boolean getSignProducts() { return signProducts; } + /** Setter for signProducts + * @param sign boolean + */ public void setSignProducts(final boolean sign) { this.signProducts = sign; } + /** getter for privateKey + * @return privateKey + */ public PrivateKey getPrivateKey() { return privateKey; } + /** setting for privateKey + * @param key PrivateKey + */ public void setPrivateKey(final PrivateKey key) { this.privateKey = key; } diff --git a/src/main/java/gov/usgs/earthquake/aws/FileTrackingListener.java b/src/main/java/gov/usgs/earthquake/aws/FileTrackingListener.java index 9b5b947d..a9babb36 100644 --- a/src/main/java/gov/usgs/earthquake/aws/FileTrackingListener.java +++ b/src/main/java/gov/usgs/earthquake/aws/FileTrackingListener.java @@ -28,13 +28,15 @@ */ public class FileTrackingListener extends DefaultConfigurable implements NotificationListener { + /** Initialzation of logger. For us later in file. */ private static final Logger LOGGER = Logger.getLogger(FileTrackingListener.class.getName()); - // tracking index properties + /** Tracking index property */ public static final String TRACKING_INDEX_PROPERTY = "trackingIndex"; + /** Tracking index file property */ public static final String TRACKING_INDEX_FILE_PROPERTY = "trackingIndexFile"; - // tracking file properties + /** Tracking file property */ public static final String TRACKING_FILE_PROEPRTY = "trackingFile"; /** File being tracked. */ @@ -42,20 +44,39 @@ public class FileTrackingListener extends DefaultConfigurable implements Notific /** Tracking Index where contents are stored */ private TrackingIndex trackingIndex; + /** FileTrackingListener constructor */ public FileTrackingListener() { } + /** Initializable FileTrackingListener + * @param trackingFile file to be traacked + * @param trackingIndex Index where contents are stored + */ public FileTrackingListener(final File trackingFile, final TrackingIndex trackingIndex) { this.trackingFile = trackingFile; this.trackingIndex = trackingIndex; } + /** Getter for trackingFile + * @return trackingFile + */ public File getTrackingFile() { return this.trackingFile; } + + /** Setter for trackingFile + * @param trackingFile File to be tracked + */ public void setTrackingFile(final File trackingFile) { this.trackingFile = trackingFile; } + /** Getter for trackingIndex + * @return trackingIndex + */ public TrackingIndex getTrackingIndex() { return this.trackingIndex; } + + /** Setter for trackingIndex + * @param trackingIndex Index where contents are stored + */ public void setTrackingIndex(final TrackingIndex trackingIndex) { this.trackingIndex = trackingIndex; } @@ -121,7 +142,7 @@ public void shutdown() throws Exception { /** * Read trackingIndex and write trackingFile. * - * @throws Exception + * @throws Exception Exception */ public void loadTrackingFile() throws Exception { final String name = trackingFile.getAbsolutePath(); @@ -137,7 +158,7 @@ public void loadTrackingFile() throws Exception { /** * Read trackingFile and write into trackingIndex. * - * @throws Exception + * @throws Exception Exception */ public void storeTrackingFile() throws Exception { try { diff --git a/src/main/java/gov/usgs/earthquake/aws/HttpResponse.java b/src/main/java/gov/usgs/earthquake/aws/HttpResponse.java index 9f8d5030..4d781f00 100644 --- a/src/main/java/gov/usgs/earthquake/aws/HttpResponse.java +++ b/src/main/java/gov/usgs/earthquake/aws/HttpResponse.java @@ -14,12 +14,17 @@ * Utility class to hold HttpURLConnection and parse JSON response data. */ public class HttpResponse { + /** Variable to hold HttpURLConnection */ public final HttpURLConnection connection; + /** Variable for holding IOExceptions */ public final IOException readException; + /** Varialbe to hold URL response */ public final byte[] response; /** * Reads response from HttpUrlConnection. + * @param connection HttpURLConnection to read + * @throws Exception exception if errors */ public HttpResponse(final HttpURLConnection connection) throws Exception { this.connection = connection; diff --git a/src/main/java/gov/usgs/earthquake/aws/JsonNotificationIndex.java b/src/main/java/gov/usgs/earthquake/aws/JsonNotificationIndex.java index 2d6668c3..1ab76cea 100644 --- a/src/main/java/gov/usgs/earthquake/aws/JsonNotificationIndex.java +++ b/src/main/java/gov/usgs/earthquake/aws/JsonNotificationIndex.java @@ -61,8 +61,11 @@ public class JsonNotificationIndex private static final Logger LOGGER = Logger.getLogger( JsonNotificationIndex.class.getName()); + /** Variable for the default driver */ public static final String DEFAULT_DRIVER = "org.sqlite.JDBC"; + /** Variable for the default table */ public static final String DEFAULT_TABLE = "notification"; + /** Variable for the default URL */ public static final String DEFAULT_URL = "jdbc:sqlite:json_notification_index.db"; @@ -78,6 +81,8 @@ public JsonNotificationIndex() { /** * Construct a JsonNotificationIndex with the default table. + * @param driver Driver to use + * @param url URL to use */ public JsonNotificationIndex(final String driver, final String url) { this(driver, url, DEFAULT_TABLE); @@ -85,6 +90,9 @@ public JsonNotificationIndex(final String driver, final String url) { /** * Construct a JsonNotificationIndex with custom driver, url, and table. + * @param driver Driver to use + * @param url URL to use + * @param table Table to use */ public JsonNotificationIndex( final String driver, final String url, final String table) { @@ -92,7 +100,9 @@ public JsonNotificationIndex( this.table = table; } + /** @return table */ public String getTable() { return this.table; } + /** @param table Table to set */ public void setTable(final String table) { this.table = table; } @Override @@ -109,6 +119,7 @@ public void configure(final Config config) throws Exception { /** * After normal startup, check whether schema exists and attempt to create. + * @throws Exception if error occurs */ @Override public void startup() throws Exception { @@ -123,8 +134,8 @@ public void startup() throws Exception { /** * Check whether schema exists. * - * @return - * @throws Exception + * @return boolean + * @throws Exception if error occurs */ public boolean schemaExists() throws Exception { final String sql = "select * from " + this.table + " limit 1"; @@ -150,7 +161,7 @@ public boolean schemaExists() throws Exception { * Only supports sqlite or mysql. When not using sqlite, relying on this * method is only recommended for local development. * - * @throws Exception + * @throws Exception if error occurs */ public void createSchema() throws Exception { // create schema @@ -193,6 +204,8 @@ public void createSchema() throws Exception { * Add a notification to the index. * * TrackerURLs are ignored. + * @param notification To be added to index + * @throws Exception if error occurs */ @Override public synchronized void addNotification(Notification notification) @@ -255,6 +268,8 @@ public synchronized void addNotification(Notification notification) * Remove notification from index. * * Tracker URLs are ignored. + * @param notification to be removed from index + * @throws Exception if error occurs */ @Override public synchronized void removeNotification(Notification notification) throws Exception { @@ -319,6 +334,7 @@ public synchronized void removeNotification(Notification notification) throws Ex * @param code * code, or null for all codes. * @return list with matching notifications, empty if not found. + * @throws Exception if error occurs */ @Override public synchronized List findNotifications( @@ -379,6 +395,7 @@ public synchronized List findNotifications( * @param codes * codes, or null for all codes. * @return list with matching notifications, empty if not found. + * @throws Exception if error occurs */ @Override public synchronized List findNotifications( @@ -457,6 +474,7 @@ public synchronized List findNotifications( * Find notifications with expires time before or equal to current time. * * @return list with matching notifications, empty if not found. + * @throws Exception if error occurs */ @Override public synchronized List findExpiredNotifications() throws Exception { @@ -494,6 +512,7 @@ public synchronized List findExpiredNotifications() throws Excepti * @param id * the product id to search. * @return list with matching notifications, empty if not found. + * @throws Exception if error occurs */ @Override public synchronized List findNotifications(ProductId id) throws Exception { @@ -541,7 +560,7 @@ public synchronized List findNotifications(ProductId id) throws Ex * @return * list of notifications found in this indexes table, but not found in the * other table. - * @throws Exception + * @throws Exception if error occurs */ public synchronized List getMissingNotifications( final String otherTable) throws Exception { @@ -582,6 +601,9 @@ public synchronized List getMissingNotifications( /** * Parse notifications from a statement ready to be executed. + * @param ps PreparedStatement to be parsed + * @return List of notifications + * @throws Exception if error occurs */ protected synchronized List getNotifications(PreparedStatement ps) throws Exception { @@ -611,6 +633,16 @@ protected synchronized List getNotifications(PreparedStatement ps) *
  • Return a URLNotification if url is set *
  • Otherwise, return a DefaultNotification * + * @param created When created + * @param expires When notification expires + * @param source sources + * @param type types + * @param code codes + * @param updateTime updateTime + * @param url URL + * @param data data + * @return Notification, JSONNotification, URLNotification, or DefaultNotification + * @throws Exception if error occurs */ protected Notification parseNotification( final String created, diff --git a/src/main/java/gov/usgs/earthquake/aws/JsonProductStorage.java b/src/main/java/gov/usgs/earthquake/aws/JsonProductStorage.java index 1a41ec5a..4650c490 100644 --- a/src/main/java/gov/usgs/earthquake/aws/JsonProductStorage.java +++ b/src/main/java/gov/usgs/earthquake/aws/JsonProductStorage.java @@ -50,8 +50,11 @@ public class JsonProductStorage extends JDBCConnection implements ProductStorage private static final Logger LOGGER = Logger.getLogger( JsonProductStorage.class.getName()); + /** Variable for the default driver */ public static final String DEFAULT_DRIVER = "org.sqlite.JDBC"; + /** Variable for the default table */ public static final String DEFAULT_TABLE = "product"; + /** Variable for the default URL */ public static final String DEFAULT_URL = "jdbc:sqlite:json_product_index.db"; /** Database table name. */ @@ -66,6 +69,8 @@ public JsonProductStorage() { /** * Create a JsonProductStorage with a default table. + * @param driver Driver to use + * @param url URL to use */ public JsonProductStorage(final String driver, final String url) { this(driver, url, DEFAULT_TABLE); @@ -73,6 +78,9 @@ public JsonProductStorage(final String driver, final String url) { /** * Create a JsonProductStorage with a custom driver, url, and table. + * @param driver Driver to use + * @param url URL to use + * @param table Table to use */ public JsonProductStorage( final String driver, final String url, final String table) { @@ -80,7 +88,9 @@ public JsonProductStorage( this.table = table; } + /** @return table */ public String getTable() { return this.table; } + /** @param table Table to set */ public void setTable(final String table) { this.table = table; } @Override @@ -97,6 +107,7 @@ public void configure(final Config config) throws Exception { /** * After normal startup, check whether schema exists and attempt to create. + * @throws Exception if error occurs */ @Override public void startup() throws Exception { @@ -111,8 +122,8 @@ public void startup() throws Exception { /** * Check whether schema exists. * - * @return - * @throws Exception + * @return boolean + * @throws Exception if error occurs */ public boolean schemaExists() throws Exception { final String sql = "select * from " + this.table + " limit 1"; @@ -138,7 +149,7 @@ public boolean schemaExists() throws Exception { * Only supports sqlite or mysql. When not using sqlite, relying on this * method is only recommended for local development. * - * @throws Exception + * @throws Exception if error occurs */ public void createSchema() throws Exception { // create schema diff --git a/src/main/java/gov/usgs/earthquake/aws/TrackingIndex.java b/src/main/java/gov/usgs/earthquake/aws/TrackingIndex.java index f3e7c40c..081b98e0 100644 --- a/src/main/java/gov/usgs/earthquake/aws/TrackingIndex.java +++ b/src/main/java/gov/usgs/earthquake/aws/TrackingIndex.java @@ -34,8 +34,11 @@ public class TrackingIndex extends JDBCConnection { private static final Logger LOGGER = Logger.getLogger( TrackingIndex.class.getName()); + /** Variable for the default driver */ public static final String DEFAULT_DRIVER = "org.sqlite.JDBC"; + /** Variable for the default table */ public static final String DEFAULT_TABLE = "tracking"; + /** Variable for the default URL */ public static final String DEFAULT_URL = "jdbc:sqlite:json_tracking_index.db"; /** Database table name. */ @@ -50,6 +53,8 @@ public TrackingIndex() { /** * Construct a TrackingIndex with the default table. + * @param driver Driver to use + * @param url URL to use */ public TrackingIndex(final String driver, final String url) { this(driver, url, DEFAULT_TABLE); @@ -57,6 +62,9 @@ public TrackingIndex(final String driver, final String url) { /** * Construct a TrackingIndex with custom driver, url, and table. + * @param driver Driver to use + * @param url URL to use + * @param table Table to use */ public TrackingIndex( final String driver, final String url, final String table) { @@ -64,7 +72,9 @@ public TrackingIndex( this.table = table; } + /** @return table */ public String getTable() { return this.table; } + /** @param table Table to set */ public void setTable(final String table) { this.table = table; } @Override @@ -95,8 +105,8 @@ public void startup() throws Exception { /** * Check whether schema exists. * - * @return - * @throws Exception + * @return boolean + * @throws Exception if error occurs */ public boolean schemaExists() throws Exception { final String sql = "select * from " + this.table + " limit 1"; @@ -122,7 +132,7 @@ public boolean schemaExists() throws Exception { * Only supports sqlite or mysql. When not using sqlite, relying on this * method is only recommended for local development. * - * @throws Exception + * @throws Exception if error occurs */ public void createSchema() throws Exception { // create schema @@ -154,6 +164,7 @@ public void createSchema() throws Exception { * @param name * name of tracking data. * @return null if data not found. + * @throws Exception if error occurs */ public synchronized JsonObject getTrackingData(final String name) throws Exception { JsonObject data = null; @@ -189,7 +200,7 @@ public synchronized JsonObject getTrackingData(final String name) throws Excepti * * @param name * name of tracking data. - * @throws Exception + * @throws Exception if error occurs */ public synchronized void removeTrackingData(final String name) throws Exception { final String sql = "DELETE FROM " + this.table + " WHERE name=?"; @@ -214,7 +225,7 @@ public synchronized void removeTrackingData(final String name) throws Exception * name of tracking data. * @param data * data to store. - * @throws Exception + * @throws Exception if error occurs */ public synchronized void setTrackingData(final String name, final JsonObject data) throws Exception { final String update = "UPDATE " + this.table + " SET data=? WHERE name=?"; diff --git a/src/main/java/gov/usgs/earthquake/distribution/AdminSocketServer.java b/src/main/java/gov/usgs/earthquake/distribution/AdminSocketServer.java index 40eda448..14be8c2d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/AdminSocketServer.java +++ b/src/main/java/gov/usgs/earthquake/distribution/AdminSocketServer.java @@ -19,7 +19,7 @@ /** * Telnet to this socket to get a "command prompt". - * + * * @author jmfee */ public class AdminSocketServer extends DefaultConfigurable implements @@ -28,7 +28,9 @@ public class AdminSocketServer extends DefaultConfigurable implements private static final Logger LOGGER = Logger .getLogger(AdminSocketServer.class.getName()); + /** Variable for default thread pool size */ private static final int DEFAULT_THREAD_POOL_SIZE = 10; + /** Variable for default admin port */ private static final int DEFAULT_ADMIN_PORT = 11111; private int port = -1; @@ -38,10 +40,16 @@ public class AdminSocketServer extends DefaultConfigurable implements /** the client this server is providing stats for. */ private ProductClient client = null; + /** Initializes socket with default thread pool size and port */ public AdminSocketServer() { this(DEFAULT_ADMIN_PORT, DEFAULT_THREAD_POOL_SIZE, null); } + /** Initializes socket with custom port, threads, and client + * @param port Admind port + * @param threads Thread pool size + * @param client Product Client + */ public AdminSocketServer(final int port, final int threads, final ProductClient client) { this.port = port; @@ -74,7 +82,7 @@ public void shutdown() throws Exception { /** * Process a line of input. - * + * * @param line * input * @param out @@ -186,26 +194,32 @@ public void onSocket(Socket socket) { + socket.toString()); } + /** @return port */ public int getPort() { return port; } + /** @param port port number */ public void setPort(int port) { this.port = port; } + /** @return threads */ public int getThreads() { return threads; } + /** @param threads set number of threads */ public void setThreads(int threads) { this.threads = threads; } + /** @return product client */ public ProductClient getClient() { return client; } + /** @param client set product client */ public void setClient(ProductClient client) { this.client = client; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/Bootstrap.java b/src/main/java/gov/usgs/earthquake/distribution/Bootstrap.java index 12303875..b9c15688 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/Bootstrap.java +++ b/src/main/java/gov/usgs/earthquake/distribution/Bootstrap.java @@ -93,7 +93,7 @@ public class Bootstrap { public static final String MAINCLASS_PROPERTY_NAME = "mainclass"; /** Default mainclass is "gov.usgs.earthquake.distribution.ProductClient. */ public static final String DEFAULT_MAINCLASS = "gov.usgs.earthquake.distribution.ProductClient"; - + /** Argument for version */ public static final String VERSION_ARGUMENT = "--version"; // private static @@ -106,8 +106,7 @@ public class Bootstrap { /** List of logger objects that have level overrides configured. */ private final ArrayList loggers = new ArrayList(); - // constructors - + /** Constructor */ public Bootstrap() { } @@ -118,7 +117,10 @@ public Bootstrap() { * * @param configFile * config file to load. + * @return + * config * @throws IOException + * if IO error occurs */ public Config loadConfig(final File configFile) throws IOException { Config config = new Config(); @@ -153,6 +155,10 @@ public Config loadConfig(final File configFile) throws IOException { return config; } + /** + * Sets up LogManager + * @param config Config file + */ public void setupLogging(final Config config) { final LogManager logManager = LogManager.getLogManager(); logManager.reset(); diff --git a/src/main/java/gov/usgs/earthquake/distribution/Bootstrappable.java b/src/main/java/gov/usgs/earthquake/distribution/Bootstrappable.java index 39560119..58806dca 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/Bootstrappable.java +++ b/src/main/java/gov/usgs/earthquake/distribution/Bootstrappable.java @@ -10,9 +10,10 @@ public interface Bootstrappable { /** * Called by Bootstrap after processing the Configurable interface. - * + * * @param args * array of command line arguments. + * @throws Exception Exception */ public void run(final String[] args) throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/distribution/CLIProductBuilder.java b/src/main/java/gov/usgs/earthquake/distribution/CLIProductBuilder.java index b83dee1d..ad228211 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/CLIProductBuilder.java +++ b/src/main/java/gov/usgs/earthquake/distribution/CLIProductBuilder.java @@ -66,43 +66,61 @@ public class CLIProductBuilder extends DefaultConfigurable { /** Exit code when errors occur while sending, but not to all senders. */ public static final int EXIT_PARTIALLY_SENT = 4; - // product id arguments + /** product id type argument */ public static final String TYPE_ARGUMENT = "--type="; + /** product id code argument */ public static final String CODE_ARGUMENT = "--code="; + /** product id source argument */ public static final String SOURCE_ARGUMENT = "--source="; + /** product id updateTime argument */ public static final String UPDATE_TIME_ARGUMENT = "--updateTime="; - // product status arguments + /** product status argument */ public static final String STATUS_ARGUMENT = "--status="; + /** product delete argument */ public static final String DELETE_ARGUMENT = "--delete"; - // tracking url + /** tracker url argument */ public static final String TRACKER_URL_ARGUMENT = "--trackerURL="; - // product properties + /** property argument */ public static final String PROPERTY_ARGUMENT = "--property-"; + /** eventID argument */ public static final String EVENTID_ARGUMENT = "--eventid="; + /** eventsource argument */ public static final String EVENTSOURCE_ARGUMENT = "--eventsource="; + /** eventsourcecode argument */ public static final String EVENTSOURCECODE_ARGUMENT = "--eventsourcecode="; + /** eventCode argument */ public static final String EVENTCODE_ARGUMENT = "--eventcode="; + /** eventtime argument */ public static final String EVENTTIME_ARGUMENT = "--eventtime="; + /** latitude argument */ public static final String LATITUDE_ARGUMENT = "--latitude="; + /** longitude argument */ public static final String LONGITUDE_ARGUMENT = "--longitude="; + /** depth argument */ public static final String DEPTH_ARGUMENT = "--depth="; + /** magnitude argument */ public static final String MAGNITUDE_ARGUMENT = "--magnitude="; + /** version argument */ public static final String VERSION_ARGUMENT = "--version="; - // product links + /** product link argument */ public static final String LINK_ARGUMENT = "--link-"; - // product content arguments + /** product content argument */ public static final String CONTENT_ARGUMENT = "--content"; + /** product content type argument */ public static final String CONTENT_TYPE_ARGUMENT = "--contentType="; + /** product directory argument */ public static final String DIRECTORY_ARGUMENT = "--directory="; + /** product file argument */ public static final String FILE_ARGUMENT = "--file="; - // private key used for signature + /** private key argument */ public static final String PRIVATE_KEY_ARGUMENT = "--privateKey="; + /** signature version argument */ public static final String SIGNATURE_VERSION_ARGUMENT = "--signatureVersion="; /** Property name used for configuring a tracker url. */ @@ -113,11 +131,17 @@ public class CLIProductBuilder extends DefaultConfigurable { /** Arguments for configuring servers and connectTimeouts. */ public static final String SERVERS_ARGUMENT = "--servers="; + /** connectionTimeout argument */ public static final String CONNECT_TIMEOUT_ARGUMENT = "--connectTimeout="; + /** Default connectionTimeout argument. 15s */ public static final Integer DEFAULT_CONNECT_TIMEOUT = 15000; + /** binaryFormat argument */ public static final String BINARY_FORMAT_ARGUMENT = "--binaryFormat"; + /** disableDeflate argument */ public static final String DISABLE_DEFLATE = "--disableDeflate"; + /** disableParallelSend argument */ public static final String DISABLE_PARALLEL_SEND = "--disableParallelSend"; + /** parallelSendTimeout argument */ public static final String PARALLEL_SEND_TIMEOUT_ARGUMENT = "--parallelSendTimeout="; /** Tracker URL that is used when not overriden by an argument. */ @@ -134,7 +158,8 @@ public class CLIProductBuilder extends DefaultConfigurable { private long parallelSendTimeout = Long.valueOf(ProductBuilder.DEFAULT_PARALLEL_SEND_TIMEOUT); /** - * This class is not intended to be instantiated directly. f + * This class is not intended to be instantiated directly. + * @param args arguments */ protected CLIProductBuilder(final String[] args) { this.args = args; @@ -258,7 +283,8 @@ public Map sendProduct(final Product product) { /** * Build a product using command line arguments. * - * @throws Exception + * @return Product + * @throws Exception if error occurs */ public Product buildProduct() throws Exception { // start product id with null values, and verify they are all set after @@ -426,6 +452,14 @@ public Product buildProduct() throws Exception { return product; } + /** + * Parse servers for list of product senders + * @param servers CSV string of servers + * @param connectTimeout timeout + * @param binaryFormat if binaryFormat + * @param enableDeflate if enableDeflate + * @return List of product senders + * */ public static List parseServers(final String servers, final Integer connectTimeout, final boolean binaryFormat, final boolean enableDeflate) throws Exception { @@ -455,8 +489,8 @@ public static List parseServers(final String servers, * * Called by Main if the --build argument is present. * - * @param args - * @throws Exception + * @param args arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { CLIProductBuilder builder = new CLIProductBuilder(args); @@ -536,7 +570,10 @@ public static void main(final String[] args) throws Exception { builder.shutdown(); System.exit(0); } - + /** + * Function on how to use command + * @return string + */ public static String getUsage() { StringBuffer buf = new StringBuffer(); diff --git a/src/main/java/gov/usgs/earthquake/distribution/Command.java b/src/main/java/gov/usgs/earthquake/distribution/Command.java index 72c52491..67c44973 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/Command.java +++ b/src/main/java/gov/usgs/earthquake/distribution/Command.java @@ -26,9 +26,15 @@ public class Command { private long timeout = 0; private int exitCode = -1; + /** Empty command constructor */ public Command() { } + /** + * @throws CommandTimeout CommandTimeout + * @throws IOException IOException + * @throws InterruptedException InterruptedException + */ public void execute() throws CommandTimeout, IOException, InterruptedException { StreamTransferThread outputTransfer = null; @@ -89,54 +95,67 @@ public void run() { } } + /** @return string[] */ public String[] getCommand() { return commandArray; } + /** @param command single command */ public void setCommand(final String command) { setCommand(splitCommand(command)); } + /** @param commandArray string[] */ public void setCommand(final String[] commandArray) { this.commandArray = commandArray; } + /** @return envp */ public String[] getEnvp() { return envp; } + /** @param envp String[] */ public void setEnvp(final String[] envp) { this.envp = envp; } + /** @return dir */ public File getDir() { return dir; } + /** @param dir File */ public void setDir(final File dir) { this.dir = dir; } + /** @return timeout */ public long getTimeout() { return timeout; } + /** @param timeout long */ public void setTimeout(final long timeout) { this.timeout = timeout; } + /** @return exitCode */ public int getExitCode() { return exitCode; } + /** @param stdin InputStream */ public void setStdin(final InputStream stdin) { this.stdin = stdin; } + /** @return stdout byte[] */ public byte[] getStdout() { return stdout.toByteArray(); } + /** @return stderr byte[] */ public byte[] getStderr() { return stderr.toByteArray(); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/ConfigurationException.java b/src/main/java/gov/usgs/earthquake/distribution/ConfigurationException.java index 5e34edca..da1e06cc 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ConfigurationException.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ConfigurationException.java @@ -11,7 +11,7 @@ public class ConfigurationException extends Exception { /** * Construct a configuration exception with only a string describing the * error. - * + * * @param message * description of the error (and possibly, solution). */ @@ -22,9 +22,11 @@ public ConfigurationException(final String message) { /** * Construct a configuration exception with a string describing the error, * and an exception that was caught that led to the problem. - * + * * @param message + * description of the error (and possibly, solution). * @param cause + * exception that led to problem */ public ConfigurationException(final String message, final Exception cause) { super(message, cause); diff --git a/src/main/java/gov/usgs/earthquake/distribution/ContentListener.java b/src/main/java/gov/usgs/earthquake/distribution/ContentListener.java index 230a6ab2..4177c828 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ContentListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ContentListener.java @@ -15,7 +15,7 @@ /** * A listener that listens for a specific content path. - * + * * This is intended for users who wish to output specific pieces of product * content, such as "quakeml.xml", for products that otherwise meet their * configured NotificationListener criteria. @@ -25,11 +25,14 @@ public class ContentListener extends DefaultNotificationListener { private static final Logger LOGGER = Logger.getLogger(ContentListener.class .getName()); - /** configuration property for includePaths. */ + /** configuration property for includePaths - output directory. */ public static final String OUTPUT_DIRECTORY_PROPERTY = "outputDirectory"; + /** property for temporary directory */ public static final String TEMP_DIRECTORY_PROPERTY = "tempDirectory"; + /** property for output format */ public static final String OUTPUT_FORMAT_PROPERTY = "outputFormat"; + /** property for default output format */ public static final String DEFAULT_OUTPUT_FORMAT = "SOURCE_TYPE_CODE_UPDATETIME_PATH"; /** Directory where content is output. */ @@ -44,6 +47,7 @@ public class ContentListener extends DefaultNotificationListener { /** Output format for files inside outputDirectory. */ private String outputFormat = DEFAULT_OUTPUT_FORMAT; + /** empty constructor for ContentListener */ public ContentListener() { } @@ -89,7 +93,7 @@ public void onProduct(final Product product) throws Exception { /** * Generate an output path based on product id and content path. - * + * * @param id * the product id. * @param path @@ -108,7 +112,7 @@ protected String getOutputPath(final ProductId id, final String path) { /** * Output a product content that was in includePaths. - * + * * @param id * the product id. * @param path diff --git a/src/main/java/gov/usgs/earthquake/distribution/ContinuableListenerException.java b/src/main/java/gov/usgs/earthquake/distribution/ContinuableListenerException.java index a4d29ef5..51dc85bb 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ContinuableListenerException.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ContinuableListenerException.java @@ -5,22 +5,35 @@ * onNotification method. This exception exists only so we can * identify the type of exception and attempt to resubmit a failed notification * for indexing. - * + * * @author emartinez - * + * */ public class ContinuableListenerException extends Exception { private static final long serialVersionUID = 0x256D2BEL; + /** + * Wrapper for exception. Takes message + * @param message string + */ public ContinuableListenerException(String message) { super(message); } + /** + * Wrapper for exception. Takes cause + * @param cause throwable + */ public ContinuableListenerException(Throwable cause) { super(cause); } + /** + * Wrapper for exception. Takes message and cause + * @param message string + * @param cause throwable + */ public ContinuableListenerException(String message, Throwable cause) { super(message, cause); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationListener.java b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationListener.java index 4b77c9bb..1ddc08e7 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationListener.java @@ -41,22 +41,27 @@ public class DefaultNotificationListener extends AbstractListener implements /** Property referencing a notification index config section. */ public static final String NOTIFICATION_INDEX_PROPERTY = "listenerIndex"; + /** Property for listener index file */ public static final String INDEX_FILE_PROPERTY = "listenerIndexFile"; /** How long to wait until checking for expired notifications/products. */ public static final String CLEANUP_INTERVAL_PROPERTY = "cleanupInterval"; + /** Default time to wait for cleanup. 1h */ public static final String DEFAULT_CLEANUP_INTERVAL = "3600000"; - /** How many products to process at a time. */ + /** Property for concurrentProducts */ public static final String CONCURRENT_PRODUCTS_PROPERTY = "concurrentProducts"; + /** How many products to process at a time. */ public static final String DEFAULT_CONCURRENT_PRODUCTS = "1"; /** Whether or not to process products more than once. */ public static final String PROCESS_DUPLICATES = "processDuplicates"; + /** Default for process duplicates. False */ public static final String DEFAULT_PROCESS_DUPLICATES = "false"; /** Filter products based on content paths they contain. */ public static final String INCLUDE_PATHS_PROPERTY = "includePaths"; + /** Property for exludePaths */ public static final String EXCLUDE_PATHS_PROPERTY = "excludePaths"; /** Optional notification index. */ @@ -141,7 +146,7 @@ public void onNotification(final NotificationEvent event) throws Exception { * * @param product * a product whose notification was accepted. - * @throws Exception + * @throws Exception if error occurs */ public void onProduct(final Product product) throws Exception { // subclasses do stuff here @@ -169,7 +174,7 @@ public void onProduct(final Product product) throws Exception { * @param notification * notification about to be processed. * @return true to process the notification, false to skip - * @throws Exception + * @throws Exception if error occurs */ protected boolean onBeforeProcessNotification( final Notification notification) throws Exception { @@ -199,7 +204,7 @@ protected boolean onBeforeProcessNotification( * @param product * product about to be processed. * @return true to process the product, false to skip - * @throws Exception + * @throws Exception if error occurs */ protected boolean onBeforeProcessProduct(final Product product) throws Exception { @@ -246,7 +251,7 @@ protected boolean onBeforeProcessProduct(final Product product) * * @param notification * notification that was processed. - * @throws Exception + * @throws Exception if error occurs */ protected void onAfterProcessNotification(final Notification notification) throws Exception { @@ -258,8 +263,8 @@ protected void onAfterProcessNotification(final Notification notification) /** * Called when an expired notification is being removed from the index. * - * @param notification - * @throws Exception + * @param notification to be removed + * @throws Exception if error occurs */ protected void onExpiredNotification(final Notification notification) throws Exception { @@ -384,34 +389,42 @@ public void configure(final Config config) throws Exception { LOGGER.config("[" + getName() + "] exclude paths = " + excludePaths); } + /** @return notificationIndex */ public NotificationIndex getNotificationIndex() { return notificationIndex; } + /** @param notificationIndex to set */ public void setNotificationIndex(NotificationIndex notificationIndex) { this.notificationIndex = notificationIndex; } + /** @return cleanupInterval */ public Long getCleanupInterval() { return cleanupInterval; } + /** @param cleanupInterval long to set */ public void setCleanupInterval(Long cleanupInterval) { this.cleanupInterval = cleanupInterval; } + /** @return concurrentProducts */ public int getConcurrentProducts() { return concurrentProducts; } + /** @param concurrentProducts int to set */ public void setConcurrentProducts(int concurrentProducts) { this.concurrentProducts = concurrentProducts; } + /** @return processDuplicates */ public boolean isProcessDuplicates() { return processDuplicates; } + /** @param processDuplicates boolean to set */ public void setProcessDuplicates(boolean processDuplicates) { this.processDuplicates = processDuplicates; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationReceiver.java b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationReceiver.java index 55bb2457..743a8d4e 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationReceiver.java +++ b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationReceiver.java @@ -86,14 +86,22 @@ public class DefaultNotificationReceiver extends DefaultConfigurable implements */ public static final String DEFAULT_RECEIVER_CLEANUP = "900000"; + /** Property for connection Timeout */ public static final String CONNECT_TIMEOUT_PROPERTY = "connectTimeout"; + /** Default connection timeout. 15 seconds */ public static final String DEFAULT_CONNECT_TIMEOUT = "15000"; + /** Property for read timeout */ public static final String READ_TIMEOUT_PROPERTY = "readTimeout"; + /** default read timeout. 15 seconds */ public static final String DEFAULT_READ_TIMEOUT = "15000"; + /** Property for listener notifier */ public static final String LISTENER_NOTIFIER_PROPERTY = "listenerNotifier"; + /** Property for listener notifier to set to executor*/ public static final String EXECUTOR_LISTENER_NOTIFIER = "executor"; + /** Property to listener notifier to set to future */ public static final String FUTURE_LISTENER_NOTIFIER = "future"; + /** Property to listener notifier to set to roundrobin */ public static final String ROUNDROBIN_LISTENER_NOTIFIER = "roundrobin"; /** The notification index where received notifications are stored. */ @@ -119,6 +127,7 @@ public class DefaultNotificationReceiver extends DefaultConfigurable implements /** A lock that is acquired when a product is being retrieved. */ private ObjectLock retrieveLocks = new ObjectLock(); + /** Creates new ExecutorListenerNotifier to var notifier */ public DefaultNotificationReceiver() { notifier = new ExecutorListenerNotifier(this); } @@ -129,6 +138,7 @@ public DefaultNotificationReceiver() { * @param listener * the listener to add. When notifications are received, this * listener will be notified. + * @throws Exception exception */ public void addNotificationListener(NotificationListener listener) throws Exception { @@ -143,6 +153,7 @@ public void addNotificationListener(NotificationListener listener) * @param listener * the listener to remove. When notifications are receive, this * listener will no longer be notified. + * @throws Exception exception */ public void removeNotificationListener(NotificationListener listener) throws Exception { @@ -200,7 +211,7 @@ public void receiveNotification(Notification notification) throws Exception { * * @param notification * the notification being sent to listeners. - * @throws Exception + * @throws Exception exception */ protected void notifyListeners(final Notification notification) throws Exception { @@ -212,7 +223,7 @@ protected void notifyListeners(final Notification notification) NotificationEvent event = new NotificationEvent(this, notification); notifier.notifyListeners(event); } - + /** @return "Using notifier" */ public String getListenerQueueStatus() { return "Using notifier"; } @@ -262,6 +273,7 @@ public void removeExpiredNotifications() throws Exception { * @param id * the product to retrieve * @return the retrieved product, or null if not available. + * @throws Exception exception */ public Product retrieveProduct(ProductId id) throws Exception { Product product = null; @@ -432,7 +444,7 @@ public Product retrieveProduct(ProductId id) throws Exception { * The ProductSource to store. * @return The ProductId of the product referenced by the given * ProductSource. - * @throws Exception + * @throws Exception exception * @see gov.usgs.earthquake.distribution.ProductStorage */ protected Notification storeProductSource(ProductSource source) @@ -678,6 +690,9 @@ public void setProductStorageMaxAge(Long productStorageMaxAge) { this.productStorageMaxAge = productStorageMaxAge; } + /** + * @return the QueueStatus or null if ExecutorListenerNotifier doesn't exist + */ public Map getQueueStatus() { if (notifier instanceof ExecutorListenerNotifier) { return ((ExecutorListenerNotifier) notifier).getStatus(); @@ -685,40 +700,68 @@ public Map getQueueStatus() { return null; } + /** + * Throttle notifier queues + * @throws InterruptedException InterruptedException + */ public void throttleQueues() throws InterruptedException { if (notifier instanceof ExecutorListenerNotifier) { ((ExecutorListenerNotifier) notifier).throttleQueues(); } } + /** + * @return receiverCleanupInterval + */ public Long getReceiverCleanupInterval() { return receiverCleanupInterval; } + /** + * @param receiverCleanupInterval the receiverCleanupInterval to set + */ public void setReceiverCleanupInterval(Long receiverCleanupInterval) { this.receiverCleanupInterval = receiverCleanupInterval; } + /** + * @return connectionTimeout + */ public int getConnectTimeout() { return connectTimeout; } + /** + * @param connectTimeout int connectionTimeout to set + */ public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } + /** + * @return ListenerNotifier + */ public ListenerNotifier getNotifier() { return this.notifier; } + /** + * @param notifier ListenerNotifier to set + */ public void setNotifier(final ListenerNotifier notifier) { this.notifier = notifier; } + /** + * @return readTimeout + */ public int getReadTimeout() { return readTimeout; } + /** + * @param readTimeout int readTimeout to set + */ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationSender.java b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationSender.java index f50e0bba..9af3a0a2 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationSender.java +++ b/src/main/java/gov/usgs/earthquake/distribution/DefaultNotificationSender.java @@ -31,11 +31,16 @@ public class DefaultNotificationSender extends DefaultNotificationListener { /** Property referencing the length of time products should be held in storage*/ public static final String PRODUCT_STORAGE_MAX_AGE_PROPERTY = "storageage"; + /** property for max age of product in storage. 7000 days? */ public static final String DEFAULT_PRODUCT_STORAGE_MAX_AGE = "604800000"; + /** Variable for String serverHost */ protected String serverHost; + /** Variable for String serverPort */ protected String serverPort; + /** Variable for URL productStorage */ protected URLProductStorage productStorage; + /** Variable for long productStorageMaxAge */ protected long productStorageMaxAge; @@ -44,7 +49,7 @@ public class DefaultNotificationSender extends DefaultNotificationListener { * * @param config * The config - * @throws Exception + * @throws Exception if something goes wrong */ public void configure(Config config) throws Exception { // let default notification listener configure itself @@ -81,7 +86,7 @@ public void configure(Config config) throws Exception { * * @param product * a product whose notification was accepted. - * @throws Exception + * @throws Exception if something goes wrong */ public void onProduct(final Product product) throws Exception { ProductId id = product.getId(); @@ -132,7 +137,7 @@ public void onProduct(final Product product) throws Exception { * @param notification * notification about to be processed. * @return true to process the notification, false to skip - * @throws Exception + * @throws Exception if something goes wrong */ @Override protected boolean onBeforeProcessNotification( @@ -170,7 +175,7 @@ protected void onAfterProcessNotification(final Notification notification) { * * @param notification * The expired notification - * @throws Exception + * @throws Exception if something goes wrong */ @Override protected void onExpiredNotification(final Notification notification) throws Exception{ @@ -192,7 +197,7 @@ protected void onExpiredNotification(final Notification notification) throws Exc * * @param notification * The notification to send - * @throws Exception + * @throws Exception if something goes wrong */ protected void sendNotification(final Notification notification) throws Exception { LOGGER.info("[" + getName() + "] sent message " + notification.toString()); @@ -223,38 +228,42 @@ public void shutdown() throws Exception{ } - /** - * Getters and Setters - */ - + /** @return serverHost */ public String getServerHost() { return serverHost; } + /** @param serverHost string to set */ public void setServerHost(String serverHost) { this.serverHost = serverHost; } + /** @return serverPort */ public String getServerPort() { return serverPort; } + /** @param serverPort string to set */ public void setServerPort(String serverPort) { this.serverPort = serverPort; } + /** @return productStorage */ public URLProductStorage getProductStorage() { return productStorage; } + /** @param productStorage URLProductStorage to set */ public void setProductStorage(URLProductStorage productStorage) { this.productStorage = productStorage; } + /** @return productStorageMaxAge */ public long getProductStorageMaxAge() { return productStorageMaxAge; } + /** @param productStorageMaxAge long to set */ public void setProductStorageMaxAge(long productStorageMaxAge) { this.productStorageMaxAge = productStorageMaxAge; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/DefaultStorageListener.java b/src/main/java/gov/usgs/earthquake/distribution/DefaultStorageListener.java index 117eab66..f3ae27e1 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/DefaultStorageListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/DefaultStorageListener.java @@ -30,7 +30,7 @@ public void startup() throws Exception { /** * Simple dispatch method for listeners who are only interested in certain * types of StorageEvents. - * + * * @param event * The event that triggered the call */ @@ -51,8 +51,9 @@ public void onStorageEvent(StorageEvent event) { /** * Dispatched method called when the type of event is * StorageEvent.StorageEventType.PRODUCT_STORED. - * - * @param event + * + * @param event The event that triggered the call + * @throws Exception if error occurs */ public void onProductStored(StorageEvent event) throws Exception { LOGGER.info("onProductStored::" + event.getProductId().toString()); @@ -61,8 +62,9 @@ public void onProductStored(StorageEvent event) throws Exception { /** * Dispatched method called when the type of event is * StorageEvent.StorageEventType.PRODUCT_REMOVED. - * - * @param event + * + * @param event The event that triggered the call + * @throws Exception if error occurs */ public void onProductRemoved(StorageEvent event) throws Exception { LOGGER.info("onProductRemoved::" + event.getProductId().toString()); diff --git a/src/main/java/gov/usgs/earthquake/distribution/DeflateComparison.java b/src/main/java/gov/usgs/earthquake/distribution/DeflateComparison.java index daa1244b..1d0b3ece 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/DeflateComparison.java +++ b/src/main/java/gov/usgs/earthquake/distribution/DeflateComparison.java @@ -23,13 +23,13 @@ public class DeflateComparison { /** * Deflate an input stream. - * + * * @param level * deflate level. * @param in * input stream to deflate. * @return output length in bytes. - * @throws IOException + * @throws IOException if IO error occurs */ public long deflateStream(final int level, final InputStream in) throws IOException { @@ -45,11 +45,11 @@ public long deflateStream(final int level, final InputStream in) /** * Transfer an input stream. - * + * * @param in * input stream to transfer. * @return output length in bytes. - * @throws IOException + * @throws IOException if IO error occurs */ public long transferStream(final InputStream in) throws IOException { CountingOutputStream cos = new CountingOutputStream(); @@ -59,13 +59,13 @@ public long transferStream(final InputStream in) throws IOException { /** * Test different compression levels and speeds for a file. - * + * * Reads file into memory to avoid disk io overhead. - * + * * @param file * file to test. - * @throws IllegalArgumentException - * @throws IOException + * @throws IllegalArgumentException if illegal arg + * @throws IOException if IO error occurs */ public void testFile(final File file) throws IllegalArgumentException, IOException { @@ -77,11 +77,13 @@ public void testFile(final File file) throws IllegalArgumentException, /** * Test different compression levels and speeds for a byte array. - * + * + * @param name + * given name * @param content * content to test. - * @throws IllegalArgumentException - * @throws IOException + * @throws IllegalArgumentException if illegal arg + * @throws IOException if IO error occurs */ public void testByteArray(final String name, final byte[] content) throws IOException { @@ -120,6 +122,13 @@ public void testByteArray(final String name, final byte[] content) deflateBestCompressionTime); } + /** + * For calculating for properly formatting the results + * + * @param totalBytes totalBytes + * @param transferredBytes Bytes transferred + * @param elapsedTime total elapsed time + */ protected void formatResult(final long totalBytes, final long transferredBytes, final long elapsedTime) { long savedBytes = totalBytes - transferredBytes; @@ -159,11 +168,11 @@ public void write(int arg0) throws IOException { /** * A main method for accessing tests using custom files. - * + * * @param args * a list of files or directorys to include in compression * comparison. - * @throws Exception + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { if (args.length == 0) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationReceiver.java b/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationReceiver.java index ef13bbe2..36fb2c11 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationReceiver.java +++ b/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationReceiver.java @@ -15,8 +15,8 @@ /** * Receive XML notifications using EIDS. - * - * + * + * * This class implements the Configurable interface, and has the following * options: *
    @@ -64,7 +64,7 @@ public class EIDSNotificationReceiver extends DefaultNotificationReceiver //TODO: Change condition using URLNotificationParser /** * Implement the EIDSListener interface to process messages from EIDS. - * + * * Checks to make sure message has Correct namespace and root element before * parsing. */ @@ -154,10 +154,12 @@ public void startup() throws Exception { client.startup(); } + /** @return EIDSClient */ public EIDSClient getClient() { return client; } + /** @param client set EIDSClient */ public void setClient(EIDSClient client) { this.client = client; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationSender.java b/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationSender.java index 66934fb2..761ca306 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationSender.java +++ b/src/main/java/gov/usgs/earthquake/distribution/EIDSNotificationSender.java @@ -110,10 +110,12 @@ public void startup() throws Exception { super.startup(); } + /** @return serverPolldir */ public File getServerPolldir() { return serverPolldir; } + /** @param serverPolldir file to set */ public void setServerPolldir(File serverPolldir) { this.serverPolldir = serverPolldir; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/EmbeddedPDLClient.java b/src/main/java/gov/usgs/earthquake/distribution/EmbeddedPDLClient.java index ca7bf742..8e3cc320 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/EmbeddedPDLClient.java +++ b/src/main/java/gov/usgs/earthquake/distribution/EmbeddedPDLClient.java @@ -9,7 +9,7 @@ /** * An example of an embedded PDL client. - * + * * Creates a notification receiver, which store it's information in a specified * directory. Listeners can be added to this receiver before its startup() * method is called, which starts the distribution process. @@ -30,7 +30,7 @@ public class EmbeddedPDLClient { /** * Construct an embedded PDL client. - * + * * @param dataDirectory * directory where receiver files are stored. * @param serverHost @@ -39,7 +39,7 @@ public class EmbeddedPDLClient { * PDL hub port. * @param alternateServersList * comma separated list of "hostname:port" alternate pdl hubs. - * @throws Exception + * @throws Exception if error occurs */ public EmbeddedPDLClient(final File dataDirectory, final String serverHost, final Integer serverPort, final String alternateServersList) @@ -51,7 +51,7 @@ public EmbeddedPDLClient(final File dataDirectory, final String serverHost, client.setTrackingFileName(new File(dataDirectory, EMBEDDED_TRACKING_FILE).getCanonicalPath()); - + eidsReceiver = new EIDSNotificationReceiver(); eidsReceiver.setName(EMBEDDED_NAME); eidsReceiver.setNotificationIndex(new JDBCNotificationIndex(new File( @@ -69,7 +69,7 @@ public EmbeddedPDLClient(final File dataDirectory, final String serverHost, * Get the embedded EIDSNotificationReceiver object for further * configuration, adding/removing listeners, and starting/stopping * distribution. - * + * * @return the embedded EIDSNotificationReceiver object. */ public EIDSNotificationReceiver getReceiver() { @@ -78,10 +78,10 @@ public EIDSNotificationReceiver getReceiver() { /** * Example main method that uses the EmbeddedPDLClient. - * + * * @param args * not used. - * @throws Exception + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { // disable product tracker messages diff --git a/src/main/java/gov/usgs/earthquake/distribution/ExecutorListenerNotifier.java b/src/main/java/gov/usgs/earthquake/distribution/ExecutorListenerNotifier.java index 5dde45b9..37487376 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ExecutorListenerNotifier.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ExecutorListenerNotifier.java @@ -57,6 +57,10 @@ public class ExecutorListenerNotifier extends DefaultConfigurable implements /** When throttling, wait this many milliseconds between queue size checks. */ protected long throttleWaitInterval = 5000L; + /** + * Constructor + * @param receiver DefaultNotificationReceiver + */ public ExecutorListenerNotifier(final DefaultNotificationReceiver receiver) { this.receiver = receiver; } @@ -120,13 +124,19 @@ public void removeNotificationListener(NotificationListener listener) * * @param event * the notification being sent to listeners. - * @throws Exception + * @throws Exception if error occurs */ @Override public void notifyListeners(final NotificationEvent event) throws Exception { this.notifyListeners(event, this.notificationListeners.keySet()); } + /** + * Calls queueNotification with event and listener for each listener + * @param event NotificationEvent + * @param listeners Collection of NotificationListeners + * @throws Exception if error occurs + */ public void notifyListeners(final NotificationEvent event, final Collection listeners) throws Exception { @@ -138,6 +148,10 @@ public void notifyListeners(final NotificationEvent event, } } + /** + * @param listener NotificationListener + * @param event NotificationEvent + */ protected void queueNotification(final NotificationListener listener, final NotificationEvent event) { if (acceptBeforeQueuing @@ -261,14 +275,17 @@ public void startup() throws Exception { AUTOLOADED_INDEXES.add(index.getName()); } + /** @return default notification receiver */ public DefaultNotificationReceiver getReceiver() { return receiver; } + /** @param receiver of the default notification variety */ public void setReceiver(DefaultNotificationReceiver receiver) { this.receiver = receiver; } + /** @return map of status */ public Map getStatus() { HashMap status = new HashMap(); @@ -308,12 +325,19 @@ public Integer getMaxQueueSize() { * If longest queue has more than 50k notifications, * wait until longest queue has 25k notifications before returning. * - * @throws InterruptedException + * @throws InterruptedException if error occurs */ public void throttleQueues() throws InterruptedException { throttleQueues(null); } + /** + * If longest queue has more than 50k notifications, + * wait until longest queue has 25k notifications before returning. + * + * @param remaining integer + * @throws InterruptedException if error occurs + */ public void throttleQueues(Integer remaining) throws InterruptedException { // try to keep queue size managable during restart int limit = throttleStartThreshold; @@ -356,13 +380,19 @@ public Map getExecutors() { return notificationListeners; } + /** @return int throttle start threshold */ public int getThrottleStartThreshold() { return this.throttleStartThreshold; } + /** @param n int throttle start threshold */ public void setThrottleStartThreshold(final int n) { this.throttleStartThreshold = n; } + /** @return int throttle stop threshold */ public int getThrottleStopThreshold() { return this.throttleStopThreshold; } + /** @param n int throttle stop threshold */ public void setThrottleStopThreshold(final int n) { this.throttleStopThreshold = n; } + /** @return int throttle wait interval */ public long getThrottleWaitInterval() { return this.throttleWaitInterval; } + /** @param ms long throttle wait interval in ms */ public void setThrottleWaitInterval(final long ms) { this.throttleWaitInterval = ms; } } diff --git a/src/main/java/gov/usgs/earthquake/distribution/ExternalNotificationListener.java b/src/main/java/gov/usgs/earthquake/distribution/ExternalNotificationListener.java index 4245ed67..6b655de5 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ExternalNotificationListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ExternalNotificationListener.java @@ -24,22 +24,22 @@ /** * An external process that is called when new products arrive. - * + * * The ExternalNotificationListener implements the Configurable interface and * can use the following configuration parameters: - * + * *
    *
    command
    *
    (Required) The command to execute. This must be an executable command and * may include arguments. Any product specific arguments are appended at the end * of command.
    - * + * *
    storage
    *
    (Required) A directory used to store all products. Each product is * extracted into a separate directory within this directory and is referenced * by the --directory=/path/to/directory argument when command is executed.
    *
    - * + * */ public class ExternalNotificationListener extends DefaultNotificationListener { @@ -66,7 +66,7 @@ public class ExternalNotificationListener extends DefaultNotificationListener { /** * Construct a new ExternalNotificationListener. - * + * * The listener must be configured with a FileProductStorage and command to * function. */ @@ -75,7 +75,7 @@ public ExternalNotificationListener() { /** * Configure an ExternalNotificationListener using a Config object. - * + * * @param config * the config containing a */ @@ -136,11 +136,11 @@ public void startup() throws Exception { /** * Append product arguments to the base command. - * + * * @param product * the product used to generate arguments. * @return command as a string. - * @throws Exception + * @throws Exception if error occurs */ public String getProductCommand(final Product product) throws Exception { StringBuffer buf = new StringBuffer(command); @@ -210,12 +210,12 @@ public String getProductCommand(final Product product) throws Exception { /** * Split a command string into a command array. - * + * * This version uses a StringTokenizer to split arguments. Quoted arguments * are supported (single or double), with quotes removed before passing to * runtime. Double quoting arguments will preserve quotes when passing to * runtime. - * + * * @param command * command to run. * @return Array of arguments suitable for passing to @@ -275,9 +275,9 @@ protected static String[] splitCommand(final String command) { /** * Call the external process for this product. - * - * @param product - * @throws Exception + * + * @param product Product + * @throws Exception if error occurs */ public void onProduct(final Product product) throws Exception { // store product @@ -334,10 +334,10 @@ public void onProduct(final Product product) throws Exception { /** * Called when the command finishes executing normally. - * + * * This implementation throws a NotificationListenerException if the * exitValue is non-zero. - * + * * @param product * the product being processed. * @param command @@ -366,10 +366,10 @@ public void commandComplete(final Product product, final String command, /** * Called when an exception occurs while running command. - * + * * This implementation throws a NotificationListenerException with exception * as the cause. - * + * * @param product * product being processed * @param productCommand diff --git a/src/main/java/gov/usgs/earthquake/distribution/Factory.java b/src/main/java/gov/usgs/earthquake/distribution/Factory.java index 3887bed2..bf137471 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/Factory.java +++ b/src/main/java/gov/usgs/earthquake/distribution/Factory.java @@ -7,6 +7,14 @@ public class Factory { + /** + * Creates EIDS Client using given params + * @param serverHost host + * @param serverPort port + * @param alternateServers for list of alternate servers + * @param trackingFileName tracking file name + * @return EIDSClient + */ public EIDSClient createEIDSClient(final String serverHost, final Integer serverPort, final String alternateServers, final String trackingFileName) { @@ -20,6 +28,15 @@ public EIDSClient createEIDSClient(final String serverHost, return client; } + /** + * Creates EIDS Notification Receiver + * @param serverList serverlist + * @param receiverStorageDirectory file of storage directory + * @param receiverIndexFile file of receiver index + * @param client EIDSClient + * @return new EIDSNotificationReceiver + * @throws Exception if error occurs + */ public EIDSNotificationReceiver createEIDSNotificationReceiver( final String serverList, final File receiverStorageDirectory, final File receiverIndexFile, final EIDSClient client) @@ -36,6 +53,15 @@ public EIDSNotificationReceiver createEIDSNotificationReceiver( return receiver; } + /** + * Create new socket product receiver + * @param port int of port + * @param numThreads int of threads + * @param receiverStorageDirectory file of storage directory + * @param receiverIndexFile file of receiver index + * @return new SocketProductReceiver + * @throws Exception if error occurs + */ public SocketProductReceiver createSocketProductReceiver(final int port, final int numThreads, final File receiverStorageDirectory, final File receiverIndexFile) throws Exception { @@ -50,6 +76,15 @@ public SocketProductReceiver createSocketProductReceiver(final int port, return receiver; } + /** + * create new EIDS Notification Sender + * @param corbaHost String of host + * @param corbaPort String of port + * @param eidsPolldir file of eidsPoll directory + * @param htdocs file of htdocs + * @param htdocsURL URL of htdocs + * @return new EIDSNotificationSender + */ public EIDSNotificationSender createEIDSNotificationSender( final String corbaHost, final String corbaPort, final File eidsPolldir, final File htdocs, final URL htdocsURL) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/FileProductStorage.java b/src/main/java/gov/usgs/earthquake/distribution/FileProductStorage.java index f6a7ed31..6b346c0d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/FileProductStorage.java +++ b/src/main/java/gov/usgs/earthquake/distribution/FileProductStorage.java @@ -272,7 +272,10 @@ public String getProductPath(final ProductId id) { return getNormalProductPath(id); } } - + /** + * @param id Specific productID + * @return string buffer of hashed product path + */ protected String getHashedProductPath(final ProductId id) { try { MessageDigest digest; @@ -330,6 +333,10 @@ private String toHexString(final byte[] bytes) { return buf.toString(); } + /** + * @param id ProductId + * @return string buffer of normal product path + */ public String getNormalProductPath(final ProductId id) { StringBuffer buf = new StringBuffer(); buf.append(id.getType()); @@ -351,6 +358,7 @@ public String getNormalProductPath(final ProductId id) { * @param file * a file that should be converted into a ProductHandler. * @return the ProductHandler. + * @throws Exception if error occurs */ protected ProductHandler getProductHandlerFormat(final File file) throws Exception { @@ -366,6 +374,7 @@ protected ProductHandler getProductHandlerFormat(final File file) * @param file * a file that should be converted into a ProductSource. * @return the ProductSource. + * @throws Exception if error occurs */ protected ProductSource getProductSourceFormat(final File file) throws Exception { @@ -415,7 +424,7 @@ public Product getProduct(ProductId id) throws Exception { * @param id * the product to retrieve. * @return the loaded product. - * @throws Exception + * @throws Exception if error occurs */ public Product getInMemoryProduct(ProductId id) throws Exception { LOGGER.finest("[" + getName() + "] acquiring read lock for product id=" diff --git a/src/main/java/gov/usgs/earthquake/distribution/FutureListenerNotifier.java b/src/main/java/gov/usgs/earthquake/distribution/FutureListenerNotifier.java index 21a48033..598d9463 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/FutureListenerNotifier.java +++ b/src/main/java/gov/usgs/earthquake/distribution/FutureListenerNotifier.java @@ -28,6 +28,10 @@ public class FutureListenerNotifier extends ExecutorListenerNotifier { /** Service where tasks execute using futures for timeouts. */ private ExecutorService backgroundService; + /** + * Constructor + * @param receiver DefaultNotificationReceiver + */ public FutureListenerNotifier(final DefaultNotificationReceiver receiver) { super(receiver); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/HashFileProductStorage.java b/src/main/java/gov/usgs/earthquake/distribution/HashFileProductStorage.java index fa7a8481..c90194fe 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/HashFileProductStorage.java +++ b/src/main/java/gov/usgs/earthquake/distribution/HashFileProductStorage.java @@ -54,10 +54,18 @@ public class HashFileProductStorage extends FileProductStorage { */ public static final int DIRECTORY_NAME_LENGTH = 3; + /** + * Basic Constructor + * Sets baseDirectory to FileProductsStorage' DEFAULT_DIRECTORY of 'Storage' + */ public HashFileProductStorage() { super(); } + /** + * Constructor taking in specific File directory + * @param directory base directory for storage path + */ public HashFileProductStorage(final File directory) { super(directory); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatInfo.java b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatInfo.java index 9535d827..efe8ea9e 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatInfo.java +++ b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatInfo.java @@ -8,9 +8,9 @@ /** * HeartbeatInfo stores a single heartbeat key/value message, together with a * timestamp - * + * * @author tene - * + * */ public class HeartbeatInfo { @@ -19,9 +19,9 @@ public class HeartbeatInfo { /** * Message constructor - * - * @param message - * @param date + * + * @param message string + * @param date Date */ public HeartbeatInfo(String message, Date date) { this.message = message; @@ -44,8 +44,8 @@ public Date getDate() { /** * Set message content - * - * @param message + * + * @param message string to set */ public void setMessage(String message) { this.message = message; @@ -53,8 +53,8 @@ public void setMessage(String message) { /** * Set message timestamp - * - * @param date + * + * @param date to set */ public void setDate(Date date) { this.date = date; @@ -62,8 +62,8 @@ public void setDate(Date date) { /** * Test if a message is older than a purgeDate - * - * @param purgeDate + * + * @param purgeDate Date * @return true if {@link #getDate()} is before purgeDate */ public boolean isExpired(Date purgeDate) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatListener.java b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatListener.java index 71b7a80b..09061705 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatListener.java @@ -64,6 +64,7 @@ public class HeartbeatListener extends DefaultNotificationListener { * Create a new HeartbeatListener. * * Sets up the includeTypes list to contain "heartbeat". + * @throws Exception if error occurs */ public HeartbeatListener() throws Exception { LISTENING = true; @@ -119,9 +120,9 @@ public void onProduct(final Product product) throws Exception { /** * Send heartbeat data to heartbeat listener * - * @param component - * @param key - * @param value + * @param component String component + * @param key Heartbeat key + * @param value Heartbeat value */ public static void sendHeartbeatMessage(final String component, final String key, final String value) { @@ -152,7 +153,7 @@ public static void sendHeartbeatMessage(final String component, * Write heartbeat data for all components to the heartbeat file * * @return true - * @throws IOException + * @throws IOException if IO error occurs */ public boolean writeHeartbeat() throws IOException { String tempFileName = heartbeatFile.getName() + "-temp"; @@ -231,18 +232,22 @@ public void cleanup() { } + /** @return heartbeatFile */ public File getHeartbeatFile() { return heartbeatFile; } + /** @param heartbeatFile to set */ public void setHeartbeatFile(File heartbeatFile) { this.heartbeatFile = heartbeatFile; } + /** @return storageTimeout */ public long getStorageTimeout() { return storageTimeout; } + /** @param storageTimeout to set */ public void setStorageTimeout(long storageTimeout) { this.storageTimeout = storageTimeout; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatStatus.java b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatStatus.java index 47f814d4..b16d8507 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/HeartbeatStatus.java +++ b/src/main/java/gov/usgs/earthquake/distribution/HeartbeatStatus.java @@ -11,7 +11,7 @@ /** * Heartbeat status information for a single component - * + * */ public class HeartbeatStatus { @@ -19,7 +19,7 @@ public class HeartbeatStatus { /** * Create a new HeartbeatStatus. - * + * */ public HeartbeatStatus() { statuses = new HashMap(); @@ -27,26 +27,28 @@ public HeartbeatStatus() { /** * Add or update a Heartbeat's key/value pair - * - * @param key - * @param value + * + * @param key String key + * @param value String value of heartbeat info */ public void updateStatus(String key, String value) { statuses.put(key, new HeartbeatInfo(value, new Date())); } + /** @return statuses - map of string, heartbeatInfo */ public Map getStatuses() { return statuses; } + /** @return boolean - checking statuses */ public boolean isEmpty() { return (statuses.size() == 0); } /** * Purge all heartbeatStatus data for this component older than given date - * - * @param purgeDate + * + * @param purgeDate purge data until this date */ public void clearDataOlderThanDate(Date purgeDate) { Iterator iterator = statuses.keySet().iterator(); diff --git a/src/main/java/gov/usgs/earthquake/distribution/JDBCNotificationIndex.java b/src/main/java/gov/usgs/earthquake/distribution/JDBCNotificationIndex.java index 337513e1..7c780389 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/JDBCNotificationIndex.java +++ b/src/main/java/gov/usgs/earthquake/distribution/JDBCNotificationIndex.java @@ -90,9 +90,11 @@ public class JDBCNotificationIndex extends JDBCConnection implements /** Default SQLite database filename. */ private static final String JDBC_DEFAULT_FILE = "pd_index.db"; - // This is the property key used in the configuration file to specify a - // different SQLite database file. If this file doesn't exist it will be - // created at startup time + /** + * This is the property key used in the configuration file to specify a + * different SQLite database file. If this file doesn't exist it will be + * created at startup time + */ protected static final String JDBC_FILE_PROPERTY = "indexfile"; /** SQL stub for adding a notification to the index. */ @@ -280,6 +282,12 @@ public JDBCNotificationIndex() throws Exception { this((String) null); } + /** + * Constructor call from filename, where filename is jdbc index file + * If null, then index file defaults + * @param filename String - What will be the index file + * @throws Exception if error occurs + */ public JDBCNotificationIndex(final String filename) throws Exception { Class.forName(JDBC_DRIVER_CLASS); _jdbc_index_file = filename; @@ -914,6 +922,13 @@ protected Notification parseNotification(String source, String type, return n; } + /** + * @param sources List string of sources + * @param types List string of types + * @param codes List string of codes + * @return prepared query based on what is/is not null + * @throws Exception if error occurs + */ protected PreparedStatement getCorrectStatement(List sources, List types, List codes) throws Exception { if (sources != null && types != null && codes != null) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/ListenerNotifier.java b/src/main/java/gov/usgs/earthquake/distribution/ListenerNotifier.java index 2dee15ef..3b7d05cb 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ListenerNotifier.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ListenerNotifier.java @@ -4,12 +4,27 @@ public interface ListenerNotifier extends Configurable { + /** + * Interface method to add NotificationListener + * @param listener NotificationListener + * @throws Exception if error occurs + */ public void addNotificationListener(NotificationListener listener) throws Exception; + /** + * Interface method to remove NotificationListener + * @param listener NotificationListener + * @throws Exception if error occurs + */ public void removeNotificationListener(NotificationListener listener) throws Exception; + /** + * Interface method to notify Listener + * @param event NotificationEvent + * @throws Exception if error occurs + */ public void notifyListeners(final NotificationEvent event) throws Exception; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/Notification.java b/src/main/java/gov/usgs/earthquake/distribution/Notification.java index b4f03be6..ad70c73c 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/Notification.java +++ b/src/main/java/gov/usgs/earthquake/distribution/Notification.java @@ -14,16 +14,25 @@ */ public interface Notification { - /** The product that is available. */ + /** The product that is available. + * @return ProductId + */ public ProductId getProductId(); - /** How long the product is available. */ + /** How long the product is available. + * @return Date + */ public Date getExpirationDate(); - /** A tracking url where status updates can be sent. */ + /** A tracking url where status updates can be sent. + * @return Tracker URL + */ public URL getTrackerURL(); - - /** A comparison method to see if two notifications are equal. */ + + /** A comparison method to see if two notifications are equal. + * @param that Notification + * @return boolean + */ public boolean equals(Notification that); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/NotificationListenerException.java b/src/main/java/gov/usgs/earthquake/distribution/NotificationListenerException.java index 0f9385ef..d6085d46 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/NotificationListenerException.java +++ b/src/main/java/gov/usgs/earthquake/distribution/NotificationListenerException.java @@ -8,15 +8,28 @@ public class NotificationListenerException extends Exception { private static final long serialVersionUID = 1L; + /** + * NotificationListener exception only taking a message + * @param message String + */ public NotificationListenerException(final String message) { super(message); } + /** + * NotificationListener exception taking a message and cause + * @param message String + * @param cause Exception that occured + */ public NotificationListenerException(final String message, final Exception cause) { super(message, cause); } + /** + * NotificationListener exception only taking a throwable cause + * @param cause Throwable + */ public NotificationListenerException(final Throwable cause) { super(cause); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/NotificationReceiver.java b/src/main/java/gov/usgs/earthquake/distribution/NotificationReceiver.java index 433a957c..e791169d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/NotificationReceiver.java +++ b/src/main/java/gov/usgs/earthquake/distribution/NotificationReceiver.java @@ -11,16 +11,16 @@ /** * Receives and processes notifications. - * + * * A NotificationReceiver receives and processes notifications, alerting * NotificationListeners after they are processed. - * + * */ public interface NotificationReceiver extends Configurable { /** * Receive and process a notification. - * + * * @param notification * the notification being received. * @throws Exception @@ -32,7 +32,7 @@ public void receiveNotification(final Notification notification) /** * If a NotificationReceiver stores notifications, all expired notifications * and products should be removed when this method is called. - * + * * @throws Exception * if errors occur while removing expired notifications. */ @@ -40,12 +40,12 @@ public void receiveNotification(final Notification notification) /** * NotificationListeners use this method to request a product. - * + * * A NotificationReceiver may have many listeners, and should try to * retrieve products once for each product id. This will typically generate * a "local" notification, that, when expiring, signals the product may be * removed. - * + * * @param id * the product to retrieve. * @return the retrieved product, or null if not available. @@ -56,37 +56,41 @@ public void receiveNotification(final Notification notification) /** * Add a NotificationListener. - * + * * Notifications processed after this call will be sent to listener. - * + * * @param listener * the listener to add. + * @throws Exception + * if errors occur. */ public void addNotificationListener(final NotificationListener listener) throws Exception; /** * Remove a NotificationListener. - * + * * Notifications processed after this call will not be sent to listener. - * + * * @param listener * the listener to remove. + * @throws Exception + * if errors occur. */ public void removeNotificationListener(final NotificationListener listener) throws Exception; /** * Send matching notifications to the listener. - * + * * This method is a way for listeners to search notifications that were * processed while not an active listener. If sources, types, and codes are * all null, a notifications for each known ProductId will be sent to * listener. - * + * * For example, a new shakemap NotificationListener may wish to know about * all known shakemaps. - * + * *
     	 * NotificationListener shakemapListener;
     	 * // register to receive new notifications as they arrive
    @@ -97,7 +101,7 @@ public void removeNotificationListener(final NotificationListener listener)
     	 * types.add("shakemap-scenario");
     	 * receiver.sendNotifications(shakemapListener, null, types, null);
     	 * 
    - * + * * @param listener * the listener that will receive any matching notifications. * @param sources @@ -106,6 +110,8 @@ public void removeNotificationListener(final NotificationListener listener) * a list of types to search, or null for all types. * @param codes * a list of codes to search, or null for all codes. + * @throws Exception + * if errors occur. */ public void sendNotifications(final NotificationListener listener, final List sources, final List types, diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductBuilder.java b/src/main/java/gov/usgs/earthquake/distribution/ProductBuilder.java index 8bceeb4f..c3e307f2 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductBuilder.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductBuilder.java @@ -61,10 +61,12 @@ public class ProductBuilder extends DefaultConfigurable { /** Send in parallel. */ public static final String PARALLEL_SEND_PROPERTY = "parallelSend"; + /** Bool for parallel send */ public static final String DEFAULT_PARALLEL_SEND = "true"; /** Timeout in seconds for parallel send. */ public static final String PARALLEL_SEND_TIMEOUT_PROPERTY = "parallelSendTimeout"; + /** time in ms for parallel send timemout */ public static final String DEFAULT_PARALLEL_SEND_TIMEOUT = "300"; /** Default tracker url. */ @@ -98,6 +100,7 @@ public class ProductBuilder extends DefaultConfigurable { /** How long to wait before parallel send timeout. */ protected long parallelSendTimeout = 300L; + /** Default product builder constructor */ public ProductBuilder() { trackerURL = DEFAULT_TRACKER_URL; } @@ -167,7 +170,7 @@ public List getProductSenders() { /** * Add a ProductSender. * - * @param sender + * @param sender to add */ public void addProductSender(final ProductSender sender) { senders.add(sender); @@ -176,33 +179,38 @@ public void addProductSender(final ProductSender sender) { /** * Remove a previously added ProductSender. * - * @param sender + * @param sender to remove */ public void removeProductSender(final ProductSender sender) { senders.remove(sender); } + /** @return trackerURL */ public URL getTrackerURL() { return trackerURL; } + /** @param trackerURL to set */ public void setTrackerURL(URL trackerURL) { this.trackerURL = trackerURL; } + /** @return privateKey */ public PrivateKey getPrivateKey() { return privateKey; } + /** @param privateKey to set */ public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } - + /** @return signatureVersion */ public Version getSignatureVersion() { return signatureVersion; } + /** @param signatureVersion to set */ public void setSignatureVersion(Version signatureVersion) { this.signatureVersion = signatureVersion; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductClient.java b/src/main/java/gov/usgs/earthquake/distribution/ProductClient.java index 05b86a19..a6b66f0a 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductClient.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductClient.java @@ -139,7 +139,9 @@ public class ProductClient extends DefaultConfigurable implements /** Property used to disable tracker updates. */ public static final String ENABLE_TRACKER_PROPERTY_NAME = "enableTracker"; + /** Property used to enable Admin Socket */ public static final String ENABLE_ADMIN_SOCKET = "enableAdminSocket"; + /** Default bool for admin socket property */ public static final String DEFAULT_ENABLE_ADMIN_SOCKET = "false"; /** List of receivers that generate notifications. */ @@ -177,7 +179,7 @@ public void configure(Config config) throws Exception { * * @param config * the configuration. - * @throws Exception + * @throws Exception if error occurs */ public void loadListeners(final Config config) throws Exception { Iterator iter = StringUtils.split( @@ -205,7 +207,7 @@ public void loadListeners(final Config config) throws Exception { * * @param config * the configuration - * @throws Exception + * @throws Exception if error occurs */ public void loadReceivers(final Config config) throws Exception { Iterator iter = StringUtils.split( @@ -291,7 +293,7 @@ public void shutdown() throws Exception { /** * Entry point into Product Distribution. * - * @param args + * @param args argument */ public void run(final String[] args) throws Exception { try { @@ -422,6 +424,7 @@ public List getListeners() { return listeners; } + /** @return Product usage */ public static String getUsage() { StringBuffer buf = new StringBuffer(); diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductKey.java b/src/main/java/gov/usgs/earthquake/distribution/ProductKey.java index 9b1669f8..d53c7cd1 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductKey.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductKey.java @@ -16,11 +16,12 @@ /** * This represents a public key used to verify product signatures. - * + * * A key should have at least one source and/or one type. */ public class ProductKey extends DefaultConfigurable { + /** Logger for use in file */ public final Logger LOGGER = Logger.getLogger(ProductKey.class.getName()); /** Property name for sources. */ @@ -49,9 +50,9 @@ public ProductKey() { /** * Construct a new ProductPublicKey. - * + * * Sources - * + * * @param key * the public key. * @param sources @@ -72,10 +73,10 @@ public ProductKey(final PublicKey key, final List sources, /** * Check whether this key is a candidate for verifying a signature. - * + * * If any sources, product source must be in list. If any types, product * type must be in list. - * + * * @param id * which product to check. * @return true if this key might verify the signature for given product. diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductKeyChain.java b/src/main/java/gov/usgs/earthquake/distribution/ProductKeyChain.java index 3175038b..28ed743d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductKeyChain.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductKeyChain.java @@ -26,14 +26,27 @@ public class ProductKeyChain { /** List of candidate keys. */ private List keychain = new LinkedList(); + /** Empty constructor */ public ProductKeyChain() { } + /** + * Constructor for a string of keys + * @param keys String of keys, separated by commas + * @param config Config file + * @throws Exception if error occurs + */ public ProductKeyChain(final String keys, final Config config) throws Exception { this(StringUtils.split(keys, ","), config); } + /** + * Constructor for list of keys + * @param keys String list of keys + * @param config Config file + * @throws Exception if error occurs + */ public ProductKeyChain(final List keys, final Config config) throws Exception { Iterator iter = keys.iterator(); @@ -56,8 +69,8 @@ public List getKeychain() { /** * Find public keys based on configured Keys. - * - * @param id + * + * @param id ID of product * @return an array of candidate keys used to verify a signature. */ public PublicKey[] getProductKeys(final ProductId id) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductResender.java b/src/main/java/gov/usgs/earthquake/distribution/ProductResender.java index dd73bfeb..581ab44b 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductResender.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductResender.java @@ -28,10 +28,19 @@ public class ProductResender { private static final Logger LOGGER = Logger.getLogger(ProductResender.class .getName()); + /** Servers arguments */ public static final String SERVERS_ARGUMENT = "--servers="; + /** Batch arguments */ public static final String BATCH_ARGUMENT = "--batch"; + /** Private Key Argument */ public static final String PRIVATE_KEY_ARGUMENT = "--privateKey="; + /** + * Command Line Interface to ProductResender. + * + * @param args CLI arguments + * @throws Exception if error occurs + */ public static void main(final String[] args) throws Exception { // disable tracker ProductTracker.setTrackerEnabled(false); @@ -128,6 +137,13 @@ public static void main(final String[] args) throws Exception { System.exit(0); } + /** + * Sends product to builder + * @param builder ProductBuilder + * @param product Product + * @param batchMode bool + * @throws Exception if error occurs + */ protected static void sendProduct(final ProductBuilder builder, final Product product, final boolean batchMode) throws Exception { // extracted from CLIProductBuilder diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductStorage.java b/src/main/java/gov/usgs/earthquake/distribution/ProductStorage.java index 1d2b9cc6..e5ce9a74 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductStorage.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductStorage.java @@ -10,7 +10,7 @@ /** * Stores and retrieves Products. - * + * * This is typically used by a NotificationReceiver to store downloaded * products. */ @@ -18,11 +18,11 @@ public interface ProductStorage extends Configurable { /** * A method to check whether a product is already in storage. - * + * * Implementers should define this method as more than * "getProduct(id) != null" when it is significantly less expensive to check * whether a product exists, compared to loading a product from storage. - * + * * @param id * the product to check. * @return true if the product is in this storage, false otherwise. @@ -33,13 +33,13 @@ public interface ProductStorage extends Configurable { /** * Retrieve a stored product. - * + * * May be implemented as - * + * *
     	 * return ObjectProductHandler.getProduct(getProductInput(id));
     	 * 
    - * + * * @param id * which product to retrieve. * @return the retrieved product, or null if the product isn't in storage. @@ -50,13 +50,13 @@ public interface ProductStorage extends Configurable { /** * Store a product. - * + * * May be implemented as - * + * *
     	 * return storeProductSource(new ObjectProductInput(product));
     	 * 
    - * + * * @param product * the product to store. * @return the stored product's id. @@ -67,7 +67,7 @@ public interface ProductStorage extends Configurable { /** * Retrieve a ProductSource for a stored product. - * + * * @param id * which product to retrieve. * @return a ProductInput for the stored product, or null if not in storage. @@ -78,7 +78,7 @@ public interface ProductStorage extends Configurable { /** * Store a ProductSource. - * + * * @param input * the product to store. * @return the stored product's id. @@ -90,7 +90,7 @@ public ProductId storeProductSource(final ProductSource input) /** * Remove a Product from storage, if it exists. - * + * * @param id * which product to remove. * @throws Exception @@ -101,15 +101,16 @@ public ProductId storeProductSource(final ProductSource input) /** * Notifies StorageListeners of the change to the * ProductStorage. - * + * * @param event + * StorageEvent */ public void notifyListeners(final StorageEvent event); /** * Adds a StorageListener to be notified when a change occurs * in this ProductStorage. - * + * * @param listener * The listener to notify of changes. */ @@ -118,7 +119,7 @@ public ProductId storeProductSource(final ProductSource input) /** * Removes a StorageListener from being notified when a change * occurs in this ProductStorage. - * + * * @param listener * The listener to remove */ diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductTracker.java b/src/main/java/gov/usgs/earthquake/distribution/ProductTracker.java index 95a0c18b..ecdfbfc4 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductTracker.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductTracker.java @@ -80,6 +80,7 @@ public static void setTrackerEnabled(final boolean enabled) { /** * Create a new ProductTracker object. + * @param trackerURL location of tracker */ public ProductTracker(final URL trackerURL) { this.trackerURL = trackerURL; @@ -107,7 +108,7 @@ public void setTrackerURL(URL trackerURL) { * the update to send to the tracker. * @return the update object processed by the tracker, including sequence * number, or null if unable to send. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate sendUpdate(final ProductTrackerUpdate update) throws Exception { @@ -137,7 +138,7 @@ public ProductTrackerUpdate sendUpdate(final ProductTrackerUpdate update) * @param update * the update to send to the tracker. * @return the raw XML returned by the tracker, or null if unable to send. - * @throws Exception + * @throws Exception if error occurs */ public String sendUpdateXML(final ProductTrackerUpdate update) throws Exception { @@ -183,7 +184,21 @@ public String sendUpdateXML(final ProductTrackerUpdate update) return null; } - /** Same as getUpdates with 0 for startid. */ + /** + * Same as getUpdates with 0 for startid + * @param source + * product source. + * @param type + * product type. + * @param code + * product code. + * @param updateTime + * product update time. + * @param className + * module name. + * @return updates matching the provided fields. + * @throws Exception if error occurs + */ public List getUpdates(final String source, final String type, final String code, final Date updateTime, final String className) throws Exception { @@ -206,8 +221,10 @@ public List getUpdates(final String source, * product update time. * @param className * module name. + * @param startid + * starting ID * @return updates matching the provided fields. - * @throws Exception + * @throws Exception if error occurs */ public List getUpdates(final String source, final String type, final String code, final Date updateTime, @@ -223,13 +240,19 @@ public List getUpdates(final String source, * Search for updates on this tracker, returning raw xml. * * @param source + * product source. * @param type + * product type. * @param code + * product code. * @param updateTime + * product update time. * @param className + * module name. * @param startid + * start id * @return the raw xml response from the tracker. - * @throws Exception + * @throws Exception if error occurs */ public String getUpdateXML(final String source, final String type, final String code, final Date updateTime, final String className, @@ -273,7 +296,7 @@ public String getUpdateXML(final String source, final String type, * @param message * the message about the product. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate sendUpdate(final String className, final ProductId id, final String message) throws Exception { @@ -290,7 +313,7 @@ public ProductTrackerUpdate sendUpdate(final String className, * @param id * the product that was created. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate productCreated(final String className, final ProductId id) throws Exception { @@ -307,7 +330,7 @@ public ProductTrackerUpdate productCreated(final String className, * @param id * the product that was indexed. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate productIndexed(final String className, final ProductId id) throws Exception { @@ -324,7 +347,7 @@ public ProductTrackerUpdate productIndexed(final String className, * @param notification * the notification that was sent. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate notificationSent(final String className, final Notification notification) throws Exception { @@ -342,7 +365,7 @@ public ProductTrackerUpdate notificationSent(final String className, * @param notification * the notification that was received. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate notificationReceived(final String className, final Notification notification) throws Exception { @@ -360,7 +383,7 @@ public ProductTrackerUpdate notificationReceived(final String className, * @param id * the product that was downloaded. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate productDownloaded(final String className, final ProductId id) throws Exception { @@ -378,7 +401,7 @@ public ProductTrackerUpdate productDownloaded(final String className, * @param id * the product that was received. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate productReceived(final String className, final ProductId id) throws Exception { @@ -398,7 +421,7 @@ public ProductTrackerUpdate productReceived(final String className, * @param e * the exception that was caught. * @return the sent update. - * @throws Exception + * @throws Exception if error occurs */ public ProductTrackerUpdate exception(final String className, final ProductId id, final Exception e) throws Exception { @@ -414,7 +437,7 @@ public ProductTrackerUpdate exception(final String className, * @param data * a map containing name value pairs for encoding. * @return a string of encoded data. - * @throws Exception + * @throws Exception if error occurs */ public static String encodeURLData(final Map data) throws Exception { @@ -440,7 +463,7 @@ public static String encodeURLData(final Map data) * @param data * the data to send. * @return the response text. - * @throws Exception + * @throws Exception if error occurs */ public static String post(final URL url, final Map data) throws Exception { @@ -498,8 +521,8 @@ public List parseTrackerResponse( /** * Command Line Interface to ProductTracker. * - * @param args - * @throws Exception + * @param args CLI arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { // whether we are sending an update (true) @@ -595,6 +618,9 @@ public static void main(final String[] args) throws Exception { } } + /** Usage for ProductTracker + * @return CLI usage + */ public static String getUsage() { StringBuffer buf = new StringBuffer(); diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerParser.java b/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerParser.java index c9898dfd..a7dff978 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerParser.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerParser.java @@ -29,19 +29,25 @@ public class ProductTrackerParser extends SAXAdapter { /** The current update being parsed. */ private ProductTrackerUpdate update = null; - /** Create a new TrackerUpdateParser. */ + /** + * Create a new TrackerUpdateParser. + * @param trackerURL URL that generated the list being parsed + */ public ProductTrackerParser(final URL trackerURL) { this.trackerURL = trackerURL; } - /** Get the parsed updates. */ + /** + * Get the parsed updates. + * @return list of parsed updates + */ public List getUpdates() { return updates; } /** * SAXAdapter start element handler. - * + * * @param uri * element uri. * @param localName @@ -82,7 +88,7 @@ public void onStartElement(final String uri, final String localName, /** * SAXAdapter end element handler. Content only includes characters that * were read from this element, NOT any characters from child elements. - * + * * @param uri * element uri. * @param localName diff --git a/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerUpdate.java b/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerUpdate.java index 9525283f..0fd59b90 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerUpdate.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ProductTrackerUpdate.java @@ -15,12 +15,19 @@ */ public class ProductTrackerUpdate { + /** String for products created */ public static final String PRODUCT_CREATED = "Product Created"; + /** String for products received */ public static final String PRODUCT_RECEIVED = "Product Received"; + /** String for product exception*/ public static final String PRODUCT_EXCEPTION = "Exception"; + /** String for notification sent*/ public static final String NOTIFICATION_SENT = "Notification Sent"; + /** String for notification received*/ public static final String NOTIFICATION_RECEIVED = "Notification Received"; + /** String for product downloaded*/ public static final String PRODUCT_DOWNLOADED = "Product Downloaded"; + /** String for product indexed*/ public static final String PRODUCT_INDEXED = "Product Indexed"; /** Which ProductTracker stored this update. */ @@ -49,11 +56,11 @@ public class ProductTrackerUpdate { /** * Create a tracker update for submission. Calls other constructor with null * arguments for those that are not included. - * - * @param trackerURL - * @param id - * @param className - * @param message + * + * @param trackerURL url of ProductTracker + * @param id the id of the product being updated + * @param className which component is sending the update + * @param message the update being send */ public ProductTrackerUpdate(final URL trackerURL, final ProductId id, final String className, final String message) { @@ -62,14 +69,14 @@ public ProductTrackerUpdate(final URL trackerURL, final ProductId id, /** * Create a new ProductTrackerUpdate object. - * - * @param trackerURL - * @param sequenceNumber - * @param created - * @param host - * @param id - * @param className - * @param message + * + * @param trackerURL url of ProductTracker + * @param sequenceNumber assigned by ProductTracker + * @param created When the update was created + * @param host Host that sent the update + * @param id the id of the product being updated + * @param className which component is sending the update + * @param message the update being send */ public ProductTrackerUpdate(final URL trackerURL, final Long sequenceNumber, final Date created, diff --git a/src/main/java/gov/usgs/earthquake/distribution/RelayProductListener.java b/src/main/java/gov/usgs/earthquake/distribution/RelayProductListener.java index 9a5b9fda..847cfa3b 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/RelayProductListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/RelayProductListener.java @@ -20,7 +20,9 @@ public class RelayProductListener extends DefaultNotificationListener { private static final Logger LOGGER = Logger .getLogger(RelayProductListener.class.getName()); + /** property for senderType */ public static final String SENDER_TYPE_PROPERTY = "senderType"; + /** property saying the sender type is aws */ public static final String SENDER_TYPE_AWS = "aws"; /** Sender used to send products. */ diff --git a/src/main/java/gov/usgs/earthquake/distribution/ReplicationStorageListener.java b/src/main/java/gov/usgs/earthquake/distribution/ReplicationStorageListener.java index 710cb48f..5741d5d3 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/ReplicationStorageListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/ReplicationStorageListener.java @@ -82,6 +82,13 @@ public class ReplicationStorageListener extends DefaultStorageListener { public ReplicationStorageListener() { } + /** + * Customer initialization of the constructor + * @param archiveFlag Bool flag of what to do on archive + * @param replCmd Replication command on host system + * @param replTimeout Replication in ms + * @param replHosts List of Replication hosts + */ public ReplicationStorageListener(final boolean archiveFlag, String replCmd, final long replTimeout, final List replHosts) { this.archiveFlag = archiveFlag; @@ -90,6 +97,10 @@ public ReplicationStorageListener(final boolean archiveFlag, setReplHosts(replHosts); } + /** + * Set new Replication hosts + * @param replHosts string list of new hosts + */ protected void setReplHosts(List replHosts) { this.replHosts = new HashMap(); Iterator replHostsIter = replHosts.iterator(); @@ -198,6 +209,13 @@ public void onProductRemoved(StorageEvent event) throws Exception { + event.getProductId().toString() + ")"); } + /** + * + * @param storage FileProductStorage to use as the base directory + * @param id ID of product in storage + * @param deleting Bool flag for deleting + * @throws IOException if IO error occurs + */ protected void syncProductContents(FileProductStorage storage, ProductId id, boolean deleting) throws IOException { @@ -216,7 +234,7 @@ protected void syncProductContents(FileProductStorage storage, /** * Create the replication command. - * + * * @param baseDir * The directory from which replication will be executed. * @param path @@ -226,10 +244,10 @@ protected void syncProductContents(FileProductStorage storage, * = user@host:path * @param deleting * Flag whether this should be a deleting replication or not - * + * * @return The command and arguments as a list suitable for a * ProcessBuilder. - * @throws IOException + * @throws IOException if IO error occurs */ protected List createReplicationCommand(final File baseDir, final String path, final String host, final boolean deleting) throws IOException { @@ -274,7 +292,6 @@ protected List createReplicationCommand(final File baseDir, return command; } - protected class ReplicationTask extends Thread { // Command to execute @@ -290,6 +307,14 @@ protected class ReplicationTask extends Thread { // Executor service to repeat this task if appropriate private ExecutorService service = null; + /** + * Constructor of a replication task + * @param command command to execute + * @param cwd Direcetory to execute the command + * @param numTries How many times to try the replication + * @param timeout in ms + * @param service Executor service + */ public ReplicationTask(final List command, final File cwd, final int numTries, final long timeout, final ExecutorService service) { diff --git a/src/main/java/gov/usgs/earthquake/distribution/SignatureVerifier.java b/src/main/java/gov/usgs/earthquake/distribution/SignatureVerifier.java index 351a948d..0ddd273d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/SignatureVerifier.java +++ b/src/main/java/gov/usgs/earthquake/distribution/SignatureVerifier.java @@ -89,34 +89,42 @@ else if (!verifySignatures.equals(DEFAULT_VERIFY_SIGNATURE)) { } } + /** @return boolean RejectInvalidSignatures */ public boolean isRejectInvalidSignatures() { return rejectInvalidSignatures; } + /** @param rejectInvalidSignatures boolean to set */ public void setRejectInvalidSignatures(boolean rejectInvalidSignatures) { this.rejectInvalidSignatures = rejectInvalidSignatures; } + /** @return boolean TestSignatures */ public boolean isTestSignatures() { return testSignatures; } + /** @param testSignatures boolean to set */ public void setTestSignatures(boolean testSignatures) { this.testSignatures = testSignatures; } + /** @return Product keychain */ public ProductKeyChain getKeychain() { return keychain; } + /** @param keychain ProductKeyChain to set */ public void setKeychain(ProductKeyChain keychain) { this.keychain = keychain; } + /** @return boolean AllowUnknownSigner */ public boolean isAllowUnknownSigner() { return allowUnknownSigner; } + /** @param allowUnknownSigner boolean to set */ public void setAllowUnknownSigner(boolean allowUnknownSigner) { this.allowUnknownSigner = allowUnknownSigner; } @@ -131,7 +139,7 @@ public void setAllowUnknownSigner(boolean allowUnknownSigner) { * if rejectInvalidSignatures=true, and signature was not * verified; allowUnknownSigner=true prevents this exception * when no keys are found in the keychain for the product. - * @throws Exception + * @throws Exception if error occurs */ public boolean verifySignature(final Product product) throws Exception { boolean verified = false; diff --git a/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiver.java b/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiver.java index 38334c17..75613343 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiver.java +++ b/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiver.java @@ -16,21 +16,21 @@ /** * Receive Products directly via a Socket. - * + * * The received products are sent using a SocketProductSender. - * + * * A SocketProductReceiver receives products directly and notifies listeners of * received notifications. - * + * * These are typically used on hubs with an EIDSNotificationSender or * RelayProductReceiver. - * + * * The NotificationReceiver uses a NotificationIndex to track received * notifications, and a ProductStorage to store retrieved products. - * + * * The DefaultNotificationReceiver implements the Configurable interface and * uses the following configuration parameters: - * + * * Each listener has a separate queue of notifications. Each listener is * allocated one thread to process notifications from this queue. */ @@ -44,9 +44,9 @@ public class SocketProductReceiver extends DefaultNotificationReceiver private static final String PRODUCT_PORT_PROPERTY = "port"; private static final String DEFAULT_PRODUCT_PORT = "11235"; - + private static final String SIZE_LIMIT_PROPERTY = "sizeLimit"; - + private static final String DEFAULT_SIZE_LIMIT = "-1"; @@ -59,6 +59,10 @@ public class SocketProductReceiver extends DefaultNotificationReceiver private SocketAcceptor acceptor = null; + /** + * Default constructor setting port, threads, and sizeLimit to default + * @throws Exception if error occurs + */ public SocketProductReceiver() throws Exception { super(); this.port = Integer.parseInt(DEFAULT_PRODUCT_PORT); @@ -66,6 +70,11 @@ public SocketProductReceiver() throws Exception { this.sizeLimit = Long.parseLong(DEFAULT_SIZE_LIMIT); } + /** + * Constructor based on config file + * @param config Configuration file + * @throws Exception if error occurs + */ public SocketProductReceiver(Config config) throws Exception { this(); configure(config); @@ -141,6 +150,12 @@ public void onSocket(Socket socket) { + socket.toString()); } + /** + * Stores ProductSource as a notification, tracks it, and notifies Listeners + * @param source ProductSource + * @return String note for log file + * @throws Exception if error occurs + */ protected String storeAndNotify(final ProductSource source) throws Exception { Notification notification = storeProductSource(source); @@ -163,26 +178,32 @@ protected String storeAndNotify(final ProductSource source) } } + /** @return port */ public int getPort() { return port; } + /** @param port int to set */ public void setPort(int port) { this.port = port; } + /** @return sizeLimit */ public long getSizeLimit() { return sizeLimit; } + /** @param sizeLimit long to set */ public void setSizeLimit(long sizeLimit) { this.sizeLimit = sizeLimit; } + /** @return threads */ public int getThreads() { return threads; } + /** @param threads int to set */ public void setThreads(int threads) { this.threads = threads; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiverHandler.java b/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiverHandler.java index 914fa170..47a07823 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiverHandler.java +++ b/src/main/java/gov/usgs/earthquake/distribution/SocketProductReceiverHandler.java @@ -19,14 +19,23 @@ public class SocketProductReceiverHandler implements Runnable { private static final Logger LOGGER = Logger.getLogger(SocketProductReceiverHandler.class.getName()); + /** buffer for PDL protocol. Set to 1024 */ public static final int PDL_PROTOCOL_BUFFER = 1024; + /** Protected Variable for BinaryIO */ protected final BinaryIO io = new BinaryIO(); + /** Protected Variable for SocketProductReceiver */ protected final SocketProductReceiver receiver; + /** Protected Variable for Socket */ protected final Socket socket; + /** Protected Variable for a string of protocolVersion */ protected String protocolVersion; - + /** + * Constructor + * @param receiver SocketProductReceiver + * @param socket Socket + */ public SocketProductReceiverHandler(final SocketProductReceiver receiver, final Socket socket) { this.receiver = receiver; this.socket = socket; @@ -72,7 +81,7 @@ public void releaseWriteLock(final ProductId id) { * @param in input stream to read * @return version, or null if not the PDL protocol. * - * @throws IOException + * @throws IOException if IO error occurs */ public String readProtocolVersion(final InputStream in) throws IOException { String version = null; @@ -208,6 +217,7 @@ public void sendException(final OutputStream out, final Exception e) { * * @param out output stream where exception message is written * @param str string to write + * @throws IOException if IO error occurs */ public void sendString(final OutputStream out, final String str) throws IOException { try { diff --git a/src/main/java/gov/usgs/earthquake/distribution/SocketProductSender.java b/src/main/java/gov/usgs/earthquake/distribution/SocketProductSender.java index 7e398b0f..7ea70692 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/SocketProductSender.java +++ b/src/main/java/gov/usgs/earthquake/distribution/SocketProductSender.java @@ -31,20 +31,20 @@ /** * Send Products to SocketProductReceivers. - * + * * The SocketProductSender implements the Configurable interface and uses the * following configuration parameters: - * + * *
    *
    host
    *
    (Required) The IP address or hostname of a SocketProductReceiver.
    - * + * *
    port
    *
    (Optional, default=11235) The port on host of a SocketProductReceiver
    *
    - * + * * @author jmfee - * + * */ public class SocketProductSender extends DefaultConfigurable implements ProductSender { @@ -53,19 +53,27 @@ public class SocketProductSender extends DefaultConfigurable implements private static final Logger LOGGER = Logger .getLogger(SocketProductSender.class.getName()); + /** property for sender host */ public static final String SENDER_HOST_PROPERTY = "host"; + /** property for sender port */ public static final String SENDER_PORT_PROPERTY = "port"; /** The default port number for SocketProductReceivers. */ public static final String DEFAULT_SENDER_PORT = "11235"; + /** property for connectTimeout */ public static final String CONNECT_TIMEOUT_PROPERTY = "connectTimeout"; + /** Default connection timeout */ public static final String DEFAULT_CONNECT_TIMEOUT = "15000"; + /** property for readTimeout */ public static final String READ_TIMEOUT_PROPERTY = "readTimeout"; + /** Default read timeout */ public static final String DEFAULT_READ_TIMEOUT = "15000"; + /** property for writeTimeout */ public static final String WRITE_TIMEOUT_PROPERTY = "writeTimeout"; + /** Default write timeout */ public static final String DEFAULT_WRITE_TIMEOUT = "-1"; /** Property name to configure binary or xml format. */ @@ -78,16 +86,25 @@ public class SocketProductSender extends DefaultConfigurable implements /** Default value for whether to use deflate compression. */ public static final String ENABLE_DEFLATE_DEFAULT = "true"; + /** property for deflateLevel */ public static final String DEFLATE_LEVEL_PROPERTY = "deflateLevel"; + /** Default deflate level */ public static final String DEFLATE_LEVEL_DEFAULT = "1"; + /** Property to enablePdlProtocol */ public static final String ENABLE_PDL_PROTOCOL_PROPERTY = "enablePdlProtocol"; + /** Default for enable pdl protocol */ public static final String DEFAULT_ENABLE_PDL_PROTOCOL = "true"; + /** Byte array for protocl header */ public static final byte[] PROTOCOL_HEADER = { 'P', 'D', 'L' }; + /** Static var for v0.1 protocol */ public static final String PROTOCOL_VERSION_0_1 = "v0.1"; + /** Static var for unknown product */ public static final String UNKNOWN_PRODUCT = "Unknown product"; + /** Static var for alreadying having the product */ public static final String ALREADY_HAVE_PRODUCT = "Already have product"; + /** Static var for a receive error */ public static final String RECEIVE_ERROR = "Error receiving product"; /** Whether to store in binary format (true), or xml format (false). */ @@ -115,15 +132,21 @@ public class SocketProductSender extends DefaultConfigurable implements private Socket socket = null; /** - * Construct a new ProductSender. - * - * @param host - * @param port + * Construct a new ProductSender with default connection timeout. + * + * @param host Host of product sender + * @param port Port of product sender */ public SocketProductSender(final String host, final int port) { this(host, port, Integer.parseInt(DEFAULT_CONNECT_TIMEOUT)); } + /** + * Construct a new ProductSender with default read and write timeouts + * @param host Host of product sender + * @param port Port of product sender + * @param connectTimeout Timeout in ms + */ public SocketProductSender(final String host, final int port, final int connectTimeout) { this(host, port, connectTimeout, @@ -131,6 +154,15 @@ public SocketProductSender(final String host, final int port, .parseInt(DEFAULT_WRITE_TIMEOUT)); } + /** + * + * Construct a new ProductSender + * @param host Host of product sender + * @param port Port of product sender + * @param connectTimeout connect timeout in ms + * @param readTimeout read timeout in ms + * @param writeTimeout write timeout in ms + */ public SocketProductSender(final String host, final int port, final int connectTimeout, final int readTimeout, final int writeTimeout) { @@ -147,9 +179,9 @@ public SocketProductSender() { /** * Construct a new ProductSender using a Config object. - * - * @param config - * @throws Exception + * + * @param config Config object + * @throws Exception if error occurs */ public SocketProductSender(Config config) throws Exception { configure(config); @@ -157,10 +189,10 @@ public SocketProductSender(Config config) throws Exception { /** * Implement the ProductSender interface. - * + * * Connects to host:port and sends a Deflaterped xml encoded Product. There * is no direct response over the socket at this time. - * + * * Updates may be retrieved from a ProductTracker. */ public void sendProduct(Product product) throws Exception { @@ -293,7 +325,7 @@ public void sendProduct(Product product) throws Exception { /** * Reads the host and port from config. - * + * * @param config * a Config object with host and port properties. */ diff --git a/src/main/java/gov/usgs/earthquake/distribution/StorageEvent.java b/src/main/java/gov/usgs/earthquake/distribution/StorageEvent.java index e6130e2f..88f7eab9 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/StorageEvent.java +++ b/src/main/java/gov/usgs/earthquake/distribution/StorageEvent.java @@ -8,16 +8,29 @@ public class StorageEvent extends EventObject { /** Enumeration of StorageEventTypes **/ public static enum StorageEventType { - PRODUCT_STORED, PRODUCT_REMOVED + /** StorageEventType enum for stored */ + PRODUCT_STORED, + /** StorageEventType enum for removed */ + PRODUCT_REMOVED } + /** Variable of StorageEventType, for the PRODUCT_STORED enum */ public static final StorageEventType PRODUCT_STORED = StorageEventType.PRODUCT_STORED; + /** Variable of StorageEventType, for the PRODUCT_REMOVED enum */ public static final StorageEventType PRODUCT_REMOVED = StorageEventType.PRODUCT_REMOVED; private static final long serialVersionUID = 0x019A1A8BL; + /** The product ID */ private ProductId id = null; + /** The StorageEventType */ private StorageEventType type = null; + /** + * Construct a new StorageEvent + * @param storage ProductStorage + * @param id ProductId + * @param type StorageEventType + */ public StorageEvent(ProductStorage storage, ProductId id, StorageEventType type) { super(storage); @@ -25,14 +38,17 @@ public StorageEvent(ProductStorage storage, ProductId id, this.type = type; } + /** @return ProductStorage */ public ProductStorage getProductStorage() { return (ProductStorage) getSource(); } + /** @return Product ID */ public ProductId getProductId() { return id; } + /** @return StorageEventType */ public StorageEventType getType() { return type; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationJSONConverter.java b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationJSONConverter.java index 470a4dd4..08f07556 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationJSONConverter.java +++ b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationJSONConverter.java @@ -12,15 +12,28 @@ public class URLNotificationJSONConverter { + /** attribute for product id */ public static final String ATTRIBUTE_PRODUCT_ID = "id"; + /** attribute for source */ public static final String ATTRIBUTE_SOURCE = "source"; + /** attribute for type */ public static final String ATTRIBUTE_TYPE = "type"; + /** attribute for code */ public static final String ATTRIBUTE_CODE = "code"; + /** attribute for updatetime */ public static final String ATTRIBUTE_UPDATE_TIME = "updatetime"; + /** attribute for trackerURL */ public static final String ATTRIBUTE_TRACKER_URL = "trackerURL"; + /** attribute for expires */ public static final String ATTRIBUTE_EXPIRES = "expires"; + /** attribute for url */ public static final String ATTRIBUTE_URL = "url"; + /** + * Converts a URLNotification into a JSON string + * @param notification URLNotification to convert + * @return JSON string + */ public static String toJSON(final URLNotification notification) { //id ProductId id = notification.getProductId(); @@ -39,6 +52,12 @@ public static String toJSON(final URLNotification notification) { return json.toString(); } + /** + * parse a message from the input stream + * @param message InputStream message + * @return URLNotification + * @throws Exception if error occurs + */ public static URLNotification parseJSON(final InputStream message) throws Exception{ JsonReader jsonReader = Json.createReader(message); JsonObject json = jsonReader.readObject(); @@ -47,6 +66,12 @@ public static URLNotification parseJSON(final InputStream message) throws Except return parseJSON(json); } + /** + * Parse a JsonObject + * @param json JsonObject + * @return URLNotification + * @throws Exception if error occurs + */ public static URLNotification parseJSON(final JsonObject json) throws Exception{ JsonObject idJson = json.getJsonObject(ATTRIBUTE_PRODUCT_ID); @@ -63,6 +88,11 @@ public static URLNotification parseJSON(final JsonObject json) throws Exception{ new URL(json.getString(ATTRIBUTE_URL))); } + /** + * Main function to run a test JSON-ifying a URLnotification + * @param args arguments + * @throws Exception if error occurs + */ public static void main(String[] args) throws Exception{ URLNotification testNotification = new URLNotification(new ProductId("testSource","testType","testCode"), new Date(), new URL("http://localhost/tracker/"), new URL("http://localhost/product/")); diff --git a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationParser.java b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationParser.java index 9ce04408..c0d66f7d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationParser.java +++ b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationParser.java @@ -15,13 +15,20 @@ public class URLNotificationParser extends SAXAdapter { + /** Namespace for product XML */ public static final String PRODUCT_XML_NAMESPACE = "http://earthquake.usgs.gov/distribution/product"; + /** static var for notification element */ public static final String NOTIFICATION_ELEMENT = "notification"; + /** attribute for product id */ public static final String ATTRIBUTE_PRODUCT_ID = "id"; + /** attribute for updated */ public static final String ATTRIBUTE_PRODUCT_UPDATED = "updated"; + /** attribute for trackerURL */ public static final String ATTRIBUTE_TRACKER_URL = "trackerURL"; + /** attribute for expires */ public static final String ATTRIBUTE_EXPIRES = "expires"; + /** attribute for url */ public static final String ATTRIBUTE_URL = "url"; /** The parsed notification. */ @@ -44,7 +51,7 @@ public URLNotification getNotification() { /** * SAXAdapter start element handler. - * + * * @param uri * element uri. * @param localName diff --git a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationXMLConverter.java b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationXMLConverter.java index fabf06a0..dd8632fe 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/URLNotificationXMLConverter.java +++ b/src/main/java/gov/usgs/earthquake/distribution/URLNotificationXMLConverter.java @@ -6,13 +6,20 @@ public class URLNotificationXMLConverter { + /** Namespace for product XML */ public static final String PRODUCT_XML_NAMESPACE = "http://earthquake.usgs.gov/distribution/product"; + /** static var for notification element */ public static final String NOTIFICATION_ELEMENT = "notification"; + /** attribute for product id */ public static final String ATTRIBUTE_PRODUCT_ID = "id"; + /** attribute for updated */ public static final String ATTRIBUTE_PRODUCT_UPDATED = "updated"; + /** attribute for trackerURL */ public static final String ATTRIBUTE_TRACKER_URL = "trackerURL"; + /** attribute for expires */ public static final String ATTRIBUTE_EXPIRES = "expires"; + /** attribute for url */ public static final String ATTRIBUTE_URL = "url"; /** diff --git a/src/main/java/gov/usgs/earthquake/distribution/URLProductStorage.java b/src/main/java/gov/usgs/earthquake/distribution/URLProductStorage.java index b1c13b47..a11d896e 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/URLProductStorage.java +++ b/src/main/java/gov/usgs/earthquake/distribution/URLProductStorage.java @@ -28,9 +28,13 @@ */ public class URLProductStorage extends FileProductStorage { + /** Different types of formats */ public enum Format { + /** Enum for BINARY/bin format */ BINARY("bin"), + /** Enum for JSON format */ JSON("json"), + /** Enum for XML format */ XML("xml"); private String value; @@ -43,6 +47,11 @@ public String toString() { return this.value; } + /** + * Takes a string value and returns ENUM of its format + * @param value String + * @return Format ENUM + */ public static Format fromString(final String value) { if (BINARY.value.equals(value)) { return BINARY; @@ -65,9 +74,12 @@ public static Format fromString(final String value) { /** The URL which corresponds to baseDirectory. */ private URL baseURL; + /** Property for storageFormat */ public static final String STORAGE_FORMAT_PROPERTY = "storageFormat"; + /** Property for storagePath */ public static final String STORAGE_PATH_PROPERTY = "storagePath"; + /** Sets up default storage path */ public static final String DEFAULT_STORAGE_PATH = "{source}_{type}_{code}_{updateTime}.{format}"; /** (Deprecated, use STORAGE_PATH) Property name to configure binary or xml format. */ @@ -139,7 +151,7 @@ public void configure(final Config config) throws Exception { * @param id * which product. * @return the URL to a product. - * @throws Exception + * @throws Exception if error occurs */ public URL getProductURL(final ProductId id) throws Exception { return new URL(baseURL, getProductPath(id)); @@ -210,18 +222,22 @@ protected ProductSource getProductSourceFormat(final File file) } } + /** @return storageFormat */ public Format getStorageFormat() { return this.storageFormat; } + /** @param format set a storageFormat */ public void setStorageFormat(final Format format) { this.storageFormat = format; } + /** @return storagePath */ public String getStoragePath() { return this.storagePath; } + /** @param path set a string as the storagePath */ public void setStoragePath(final String path) { this.storagePath = path; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/WebSocketClient.java b/src/main/java/gov/usgs/earthquake/distribution/WebSocketClient.java index 201dce0e..43be53cc 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/WebSocketClient.java +++ b/src/main/java/gov/usgs/earthquake/distribution/WebSocketClient.java @@ -19,8 +19,11 @@ public class WebSocketClient { private long timeoutMillis; private boolean retryOnClose; + /** Default number of attempts */ public static final int DEFAULT_ATTEMPTS = 3; + /** Default timeout in ms */ public static final long DEFAULT_TIMEOUT_MILLIS = 100; + /** Default for trying to retry on close */ public static final boolean DEFAULT_RETRY_ON_CLOSE = true; /** @@ -30,6 +33,7 @@ public class WebSocketClient { * @param listener a WebSocketListener to handle incoming messages * @param attempts an integer number of times to try the connection * @param timeoutMillis a long for the wait time between attempts + * @param retryOnClose boolean for if the connection should retry when closed * @throws Exception on thread interrupt or connection failure */ public WebSocketClient(URI endpoint, WebSocketListener listener, int attempts, long timeoutMillis, boolean retryOnClose) throws Exception { @@ -42,10 +46,20 @@ public WebSocketClient(URI endpoint, WebSocketListener listener, int attempts, l connect(); } + /** + * Constructs the client + * @param endpoint the URI to connect to + * @param listener a WebSocketListener to handle incoming messages + * @throws Exception thread interrupt or connection failure + */ public WebSocketClient(URI endpoint, WebSocketListener listener) throws Exception { this(endpoint, listener, DEFAULT_ATTEMPTS, DEFAULT_TIMEOUT_MILLIS, DEFAULT_RETRY_ON_CLOSE); } + /** + * Connect to server + * @throws Exception if error occurs + */ public void connect() throws Exception { // try to connect to server WebSocketContainer container = ContainerProvider.getWebSocketContainer(); @@ -70,12 +84,24 @@ public void connect() throws Exception { } } + /** + * Sets the session and listener + * @param session Session + * @throws IOException if IO error occurs + */ @OnOpen public void onOpen(Session session) throws IOException { this.session = session; this.listener.onOpen(session); } + /** + * Closes the session on the lister, sets constructor session to null + * Check if should be retryed + * @param session Session + * @param reason for close + * @throws IOException if IO error occurs + */ @OnClose public void onClose(Session session, CloseReason reason) throws IOException { this.listener.onClose(session, reason); @@ -90,20 +116,35 @@ public void onClose(Session session, CloseReason reason) throws IOException { } } + /** + * Gives listener the message + * @param message String + * @throws IOException if IO error occurs + */ @OnMessage public void onMessage(String message) throws IOException { this.listener.onMessage(message); } + /** + * Sets retry to false, then closes session + * @throws Exception if error occurs + */ public void shutdown() throws Exception { this.retryOnClose = false; this.session.close(); } + /** @param listener set WebSocketListener */ public void setListener(WebSocketListener listener) { this.listener = listener; } + /** + * Checks if there is an open session + * @return boolean + * @throws IOException if IO error occurs + */ public boolean isConnected() throws IOException { return this.session != null && this.session.isOpen(); } diff --git a/src/main/java/gov/usgs/earthquake/distribution/WebSocketListener.java b/src/main/java/gov/usgs/earthquake/distribution/WebSocketListener.java index cde99c29..1ec479e8 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/WebSocketListener.java +++ b/src/main/java/gov/usgs/earthquake/distribution/WebSocketListener.java @@ -9,9 +9,32 @@ * Allows overridden onMessage for different behavior of WebSocketClient onMessage */ public interface WebSocketListener { + /** Interface method to be overriden by WebSocket files and AwsProductReceiver + * @param session Session to open + * @throws IOException IOException + */ public void onOpen(Session session) throws IOException; + + /** Interface method to be overriden by WebSocket files and AwsProductReceiver + * @param message String message + * @throws IOException IOException + */ public void onMessage(String message) throws IOException; + + /** Interface method to be overriden by WebSocket files and AwsProductReceiver + * @param session Session to close + * @param closeReason Reason for closing session + * @throws IOException IOException + */ public void onClose(Session session, CloseReason closeReason) throws IOException; + + /** Interface method to be overriden by WebSocket files and AwsProductReceiver + * @throws IOException IOException + */ public void onConnectFail() throws IOException; + + /** Interface method to be overriden by WebSocket files and AwsProductReceiver + * @throws IOException IOException + */ public void onReconnectFail() throws IOException; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/WebSocketNotificationReceiver.java b/src/main/java/gov/usgs/earthquake/distribution/WebSocketNotificationReceiver.java index a90930f6..b871fcfc 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/WebSocketNotificationReceiver.java +++ b/src/main/java/gov/usgs/earthquake/distribution/WebSocketNotificationReceiver.java @@ -21,27 +21,44 @@ */ public class WebSocketNotificationReceiver extends DefaultNotificationReceiver implements WebSocketListener { + /** Logger for use in the file */ public static final Logger LOGGER = Logger .getLogger(WebSocketNotificationReceiver.class.getName()); + /** Property for serverHost */ public static final String SERVER_HOST_PROPERTY = "serverHost"; + /** Property for serverPort */ public static final String SERVER_PORT_PROPERTY = "serverPort"; + /** Property for serverPath */ public static final String SERVER_PATH_PROPERTY = "serverPath"; + /** Property for sequence */ public static final String SEQUENCE_PROPERTY = "sequence"; + /** Property for timestamp */ public static final String TIMESTAMP_PROPERTY = "timestamp"; + /** Property for trackingFileName */ public static final String TRACKING_FILE_NAME_PROPERTY = "trackingFileName"; + /** Property for connectAttempts */ public static final String CONNECT_ATTEMPTS_PROPERTY = "connectAttempts"; + /** Property for connectTimeout */ public static final String CONNECT_TIMEOUT_PROPERTY = "connectTimeout"; + /** Property for retryOnClose */ public static final String RETRY_ON_CLOSE_PROPERTY = "retryOnClose"; + /** Default server host */ public static final String DEFAULT_SERVER_HOST = "http://www.google.com"; + /** Default server port */ public static final String DEFAULT_SERVER_PORT = "4222"; + /** Default server path */ public static final String DEFAULT_SERVER_PATH = "/sequence/"; + /** Default tracking file */ public static final String DEFAULT_TRACKING_FILE_NAME = "data/WebSocketReceiverInfo"; + /** Default number of connect attempts */ public static final String DEFAULT_CONNECT_ATTEMPTS = "5"; + /** Default timeout in ms */ public static final String DEFAULT_CONNECT_TIMEOUT = "1000"; + /** Default condiction for retry on close */ public static final String DEFAULT_RETRY_ON_CLOSE = "true"; - + /** attribute for data */ public static final String ATTRIBUTE_DATA = "data"; private String serverHost; @@ -70,7 +87,7 @@ public void configure(Config config) throws Exception { /** * Reads a sequence from a tracking file if it exists. Otherwise, starting sequence is 0. * Connects to web socket - * @throws Exception + * @throws Exception if error occurs */ @Override public void startup() throws Exception{ @@ -91,7 +108,7 @@ public void startup() throws Exception{ /** * Closes web socket - * @throws Exception + * @throws Exception if error occurs */ @Override public void shutdown() throws Exception{ @@ -102,7 +119,7 @@ public void shutdown() throws Exception{ /** * Writes tracking file to disc, storing latest sequence - * @throws Exception + * @throws Exception if error occurs */ public void writeTrackingFile() throws Exception { JsonObject json = Json.createObjectBuilder() @@ -121,7 +138,7 @@ public void writeTrackingFile() throws Exception { /** * Reads tracking file from disc * @return JsonObject tracking file - * @throws Exception + * @throws Exception if error occurs */ public JsonObject readTrackingFile() throws Exception { JsonObject json = null; @@ -144,7 +161,7 @@ public void onOpen(Session session) { /** * Message handler function passed to WebSocketClient * Parses the message as JSON, receives the contained URL notification, and writes the tracking file. - * @param message + * @param message String */ @Override public void onMessage(String message) { @@ -188,58 +205,72 @@ public void onReconnectFail() { // do nothing } + /** @return serverHost */ public String getServerHost() { return serverHost; } + /** @param serverHost to set */ public void setServerHost(String serverHost) { this.serverHost = serverHost; } + /** @return serverPort */ public String getServerPort() { return serverPort; } + /** @param serverPort to set */ public void setServerPort(String serverPort) { this.serverPort = serverPort; } + /** @return serverPath */ public String getServerPath() { return serverPath; } + /** @param serverPath to set */ public void setServerPath(String serverPath) { this.serverPath = serverPath; } + /** @return trackingFileName */ public String getTrackingFileName() { return trackingFileName; } + /** @param trackingFileName to set */ public void setTrackingFileName(String trackingFileName) { this.trackingFileName = trackingFileName; } + /** @return sequence */ public String getSequence() { return sequence; } + /** @param sequence to set */ public void setSequence(String sequence) { this.sequence = sequence; } + /** @return attempts */ public int getAttempts() { return attempts; } + /** @param attempts to set */ public void setAttempts(int attempts) { this.attempts = attempts; } + /** @return timeout */ public long getTimeout() { return timeout; } + /** @param timeout to set */ public void setTimeout(long timeout) { this.timeout = timeout; } diff --git a/src/main/java/gov/usgs/earthquake/distribution/roundrobinnotifier/RoundRobinListenerNotifier.java b/src/main/java/gov/usgs/earthquake/distribution/roundrobinnotifier/RoundRobinListenerNotifier.java index 5c9e606a..7319db5d 100644 --- a/src/main/java/gov/usgs/earthquake/distribution/roundrobinnotifier/RoundRobinListenerNotifier.java +++ b/src/main/java/gov/usgs/earthquake/distribution/roundrobinnotifier/RoundRobinListenerNotifier.java @@ -19,7 +19,7 @@ /** * Use round-robin queues to notify listeners. - * + * * This attempts to prevent any one product source+type from blocking processing * of notifications from other product source+type. */ @@ -44,7 +44,7 @@ public class RoundRobinListenerNotifier extends DefaultConfigurable implements /** * Create new RoundRobinListenerNotifier. - * + * * @param receiver * the receiver using this notifier. */ @@ -112,14 +112,15 @@ public void notifyListeners(NotificationEvent event) throws Exception { /** * Notify a specific list of listeners. - * + * * Used during renotification to only notify listeners that have an index. - * + * * @param event * notification. * @param toNotify * list of listeners to notify. * @throws Exception + * if error occurs */ protected void notifyListeners(NotificationEvent event, final Collection toNotify) throws Exception { @@ -163,8 +164,8 @@ public void run() { /** * Requeue existing notifications at startup. - * - * @throws Exception + * + * @throws Exception if error occurs */ protected void requeue() throws Exception { NotificationIndex index = receiver.getNotificationIndex(); diff --git a/src/main/java/gov/usgs/earthquake/dyfi/DYFIIndexerWedge.java b/src/main/java/gov/usgs/earthquake/dyfi/DYFIIndexerWedge.java index a7485f50..639b07fa 100644 --- a/src/main/java/gov/usgs/earthquake/dyfi/DYFIIndexerWedge.java +++ b/src/main/java/gov/usgs/earthquake/dyfi/DYFIIndexerWedge.java @@ -16,9 +16,11 @@ public class DYFIIndexerWedge extends ExternalNotificationListener { private static final Logger LOGGER = Logger .getLogger("gov.usgs.earthquake.dyfi.DYFIIndexerWedge"); + /** Property for baseDirectory */ public static final String BASE_DIRECTORY_PROPERTY = "baseDirectory"; private String baseDirectory = null; + /** Constructor */ public DYFIIndexerWedge() { getIncludeTypes().add("dyfi"); } @@ -27,10 +29,10 @@ public DYFIIndexerWedge() { * Builds the command to index the product. Just appends the relative * product directory (from the DYFILegacyStorage) to the configured index * command. - * + * * @param product * the Product used to build the indexing command. - * @throws Exception + * @throws Exception if error occurs */ @Override public String getProductCommand(final Product product) throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/dyfi/DYFIProduct.java b/src/main/java/gov/usgs/earthquake/dyfi/DYFIProduct.java index 24169784..872d23d4 100644 --- a/src/main/java/gov/usgs/earthquake/dyfi/DYFIProduct.java +++ b/src/main/java/gov/usgs/earthquake/dyfi/DYFIProduct.java @@ -15,15 +15,17 @@ */ public class DYFIProduct extends Product { - // References the event_data.xml file in the Product + /** References the event_data.xml file in the Product */ public static final String DYFI_EVENT_XML_ATTACHMENT = "event_data.xml"; - // These attributes are read from the XML file + /** Attribute for number of responses. Read from XML */ public static final String DYFI_NUM_RESP_ATTRIBUTE = "nresponses"; + /** Attribute for max intensity. Read from XML */ public static final String DYFI_MAX_MMI_ATTRIBUTE = "max_intensity"; - // These properties are what we set internally + /** Internally set number of responses property */ public static final String DYFI_NUM_RESP_PROPERTY = "numResp"; + /** Internally set max intensity property */ public static final String DYFI_MAX_MMI_PROPERTY = "maxmmi"; /** @@ -45,6 +47,7 @@ public DYFIProduct(final Product product) { } } + /** Reads in DYFI Event EXL and parses it into a EventDataXMLHandler */ protected void loadEventXml() { // Parse event_data.xml for more information about product Content source = getContents().get(DYFI_EVENT_XML_ATTACHMENT); diff --git a/src/main/java/gov/usgs/earthquake/dyfi/EventDataXMLHandler.java b/src/main/java/gov/usgs/earthquake/dyfi/EventDataXMLHandler.java index 83a2a20d..d187836f 100644 --- a/src/main/java/gov/usgs/earthquake/dyfi/EventDataXMLHandler.java +++ b/src/main/java/gov/usgs/earthquake/dyfi/EventDataXMLHandler.java @@ -14,15 +14,19 @@ */ public class EventDataXMLHandler extends DefaultHandler { - // XML Element Names + /** XML Element Name for event_data */ public static final String DYFI_EVENTDATA_ELEMENT = "event_data"; + /** XML Element Name for event */ public static final String DYFI_EVENT_ELEMENT = "event"; + /** XML Element Name for cdi_summary */ public static final String DYFI_CDI_SUMMARY_ELEMENT = "cdi_summary"; + /** XML Element Name for products */ public static final String DYFI_PRODUCTS_ELEMENT = "products"; + /** Static string to stop parsing before list of products */ public static final String DYFI_STOP_PARSING_BEFORE_PRODUCTS = "Stop parsing before list of product files."; - // XML Attributes + /** Map of XML attributes */ public static final Map DYFI_ELEMENT_ATTRIBUTES = new HashMap(); static { // Statically add all these attributes and associate them to their @@ -36,18 +40,30 @@ public class EventDataXMLHandler extends DefaultHandler { private DYFIProduct dyfi = null; + /** + * Constructor + * @param dyfi takes in DYFIProduct + */ public EventDataXMLHandler(final DYFIProduct dyfi) { this.dyfi = dyfi; } + /** @return DYFIProduct */ public DYFIProduct getDYFI() { return this.dyfi; } + /** @param dyfi Product to set */ public void setDYFI(final DYFIProduct dyfi) { this.dyfi = dyfi; } + /** + * + * @param in XML object to parse + * @return DYFIProduct + * @throws Exception if exception message equals stop_parsing string + */ public DYFIProduct parse(final Object in) throws Exception { try { XmlUtils.parse(in, this); diff --git a/src/main/java/gov/usgs/earthquake/eids/DebugProductSender.java b/src/main/java/gov/usgs/earthquake/eids/DebugProductSender.java index 1becca9a..3a8ff313 100644 --- a/src/main/java/gov/usgs/earthquake/eids/DebugProductSender.java +++ b/src/main/java/gov/usgs/earthquake/eids/DebugProductSender.java @@ -12,6 +12,7 @@ */ public class DebugProductSender extends DefaultConfigurable implements ProductSender { + /** Constructor */ public DebugProductSender() { setName("debug_sender"); } diff --git a/src/main/java/gov/usgs/earthquake/eids/EIDSInputWedge.java b/src/main/java/gov/usgs/earthquake/eids/EIDSInputWedge.java index aaae2490..61ff4aaf 100644 --- a/src/main/java/gov/usgs/earthquake/eids/EIDSInputWedge.java +++ b/src/main/java/gov/usgs/earthquake/eids/EIDSInputWedge.java @@ -55,28 +55,42 @@ public class EIDSInputWedge extends ProductBuilder implements Runnable, private static final Logger LOGGER = Logger.getLogger(EIDSInputWedge.class .getName()); + /** Property for parser class */ public static final String PARSER_CLASS_PROPERTY = "parserClass"; + /** Default parser class */ public static final String DEFAULT_PARSER_CLASS = "gov.usgs.earthquake.event.QuakemlToQuakemlConverter"; + /** Property for polldir */ public static final String POLLDIR_PROPERTY = "directory"; + /** Default polldir */ public static final String DEFAULT_POLLDIR = "polldir"; private File polldir = new File(DEFAULT_POLLDIR); + /** Property for storage directory */ public static final String STORAGEDIR_PROPERTY = "oldinputdir"; + /** Default storage directory */ public static final String DEFAULT_STORAGEDIR = "oldinput"; private File storagedir = new File(DEFAULT_STORAGEDIR); + /** Property for error directory */ public static final String ERRORDIR_PROPERTY = "errordir"; + /** Default error directory */ public static final String DEFAULT_ERRORDIR = "errordir"; private File errordir = new File(DEFAULT_ERRORDIR); + /** Property for validate */ public static final String VALIDATE_PROPERTY = "validate"; + /** Default status of validate */ public static final String DEFAULT_VALIDATE = "false"; + /** Property for sendOriginWhenPhasesExist */ public static final String SEND_ORIGIN_WHEN_PHASES_EXIST_PROPERTY = "sendOriginWhenPhasesExist"; + /** Default status of sendOrigin... */ public static final String DEFAULT_SEND_ORIGIN_WHEN_PHASES_EXIST = "false"; + /** Property for sendMechanismWhenPhasesExist */ public static final String SEND_MECHANISM_WHEN_PHASES_EXIST_PROPERTY = "sendMechanismWhenPhasesExist"; + /** Default status of sendMechanism... */ public static final String DEFAULT_SEND_MECHANISM_WHEN_PHASES_EXIST = "false"; /** Convert parsed quakeml to a product. */ @@ -84,34 +98,56 @@ public class EIDSInputWedge extends ProductBuilder implements Runnable, /** Whether created products should be converted to internal types. */ public static final String CREATE_INTERNAL_PRODUCTS_PROPERTY = "createInternalProducts"; + /** Default status of CREATE_INTERNAL_PRODUCTS */ public static final String DEFAULT_CREATE_INTERNAL_PRODUCTS = "false"; private boolean createInternalProducts = false; /** Whether created products should be converted to scenario types. */ public static final String CREATE_SCENARIO_PRODUCTS_PROPERTY = "createScenarioProducts"; + /** Default status of CREATE_SCENARIO_PRODUCTS */ public static final String DEFAULT_CREATE_SCENARIO_PRODUCTS = "false"; private boolean createScenarioProducts = false; /** Directory polling object. */ private DirectoryPoller directoryPoller; + /** Poll interval property */ public static final String POLLINTERVAL_PROPERTY = "interval"; + /** Default interval for POLLINTERVAL */ public static final String DEFAULT_POLLINTERVAL = "1000"; private long pollInterval = 1000L; + /** Property for pollCarefully */ public static final String POLL_CAREFULLY_PROPERTY = "pollCarefully"; + /** Default status of POLL_CAREFULLY */ public static final String DEFAULT_POLL_CAREFULLY = "false"; private boolean pollCarefully = false; + /** Property for doBufferFix */ public static final String DO_BUFFER_FIX_PROPERTY = "doBufferFix"; + /** Default status of DO_BUFFER_FIX property */ public static final String DEFAULT_DO_BUFFER_FIX = "true"; private boolean doBufferFix = true; private Thread pollThread = null; + /** + * Empty constructor + * @throws Exception if error occurs + */ public EIDSInputWedge() throws Exception { } + /** + * Gets products from file and iterates through each product + * During iteration, sets type to internal/scenario if createInternalProducts + * or createScenarioProducts is true. Attaches Content files to product, + * Sends product + * @param file File containing products + * @param attachContent Map of String and Content + * @return Map of product IDs and sent products + * @throws Exception if error occurs + */ public Map> parseAndSend( final File file, final Map attachContent) throws Exception { @@ -148,6 +184,10 @@ public Map> parseAndSend( return sendProductResults; } + /** + * Parses given file, looking for send exceptions and reports statistics + * @param file to parse and look for errors + */ public void onFile(File file) { Date inputtime = new Date(); LOGGER.info("Reading file " + file.getName()); @@ -346,58 +386,72 @@ public void startup() throws Exception { } } + /** @return polldir */ public File getPolldir() { return polldir; } + /** @param polldir File to set */ public void setPolldir(File polldir) { this.polldir = polldir; } + /** @return storagedir */ public File getStoragedir() { return storagedir; } + /** @param storagedir File to set */ public void setStoragedir(File storagedir) { this.storagedir = storagedir; } + /** @return errordir */ public File getErrordir() { return errordir; } + /** @param errordir File to send */ public void setErrordir(File errordir) { this.errordir = errordir; } + /** @return productCreator */ public ProductCreator getProductCreator() { return productCreator; } + /** @param productCreator to set */ public void setProductCreator(ProductCreator productCreator) { this.productCreator = productCreator; } + /** @return directoryPoller */ public DirectoryPoller getDirectoryPoller() { return directoryPoller; } + /** @param directoryPoller to set */ public void setDirectoryPoller(DirectoryPoller directoryPoller) { this.directoryPoller = directoryPoller; } + /** @return pollInterval long */ public long getPollInterval() { return pollInterval; } + /** @param pollInterval long to set */ public void setPollInterval(long pollInterval) { this.pollInterval = pollInterval; } + /** @return pollCarefully boolean */ public boolean isPollCarefully() { return pollCarefully; } + /** @param pollCarefully boolean to set */ public void setPollCarefully(boolean pollCarefully) { this.pollCarefully = pollCarefully; } @@ -432,6 +486,15 @@ public void setCreateScenarioProducts(boolean createScenarioProducts) { this.createScenarioProducts = createScenarioProducts; } + /** + * Parses a string of servers into SocketProductSenders, all put into a list + * of product senders + * @param servers String of servers, split by commas + * @param connectTimeout int timeout + * @param binaryFormat boolean if binary format + * @param enableDeflate boolean if Deflate should be enabled + * @return List of product senders + */ public static List parseServers(final String servers, final Integer connectTimeout, final boolean binaryFormat, final boolean enableDeflate) { @@ -451,36 +514,61 @@ public static List parseServers(final String servers, return senders; } + /** Argument for help */ public static final String HELP_ARGUMENT = "--help"; + /** Argument for poll */ public static final String POLL_ARGUMENT = "--poll"; + /** Argument for poleCarefully */ public static final String POLL_CAREFULLY_ARGUMENT = "--pollCarefully"; + /** Argument for polldir */ public static final String POLLDIR_ARGUMENT = "--polldir="; + /** Argument for errordir */ public static final String ERRORDIR_ARGUMENT = "--errordir="; + /** Argument for storagedir */ public static final String STORAGEDIR_ARGUMENT = "--oldinputdir="; + /** Argument for poll interval */ public static final String POLL_INTERVAL_ARGUMENT = "--pollInterval="; + /** Argument for tracker url */ public static final String TRACKER_URL_ARGUMENT = "--trackerURL="; + /** Argument for file */ public static final String FILE_ARGUMENT = "--file="; + /** Argument for parser */ public static final String PARSER_ARGUMENT = "--parser="; + /** Argument for validate */ public static final String VALIDATE_ARGUMENT = "--validate"; + /** Argument for privateKey */ public static final String PRIVATE_KEY_ARGUMENT = "--privateKey="; + /** Argument for signatureVersion */ public static final String SIGNATURE_VERSION_ARGUMENT = "--signatureVersion="; + /** Argument for servers */ public static final String SERVERS_ARGUMENT = "--servers="; + /** Default server for server argument */ public static final String SERVERS_DEFAULT = "prod01-pdl01.cr.usgs.gov:11235,prod02-pdl01.cr.usgs.gov:11235"; + /** Argument for connection timeout */ public static final String CONNECT_TIMEOUT_ARGUMENT = "--connectTimeout="; + /** Default timeout for connection */ public static final Integer DEFAULT_CONNECT_TIMEOUT = 15000; + /** Argument for binaryFormat */ public static final String BINARY_FORMAT_ARGUMENT = "--binaryFormat"; + /** Argument for disableDeflate */ public static final String DISABLE_DEFLATE_ARGUMENT = "--disableDeflate"; + /** Argument for attach */ public static final String ATTACH_ARGUMENT = "--attach="; + /** Argument for sending origin with phases */ public static final String SEND_ORIGINS_WITH_PHASES = "--sendOriginWhenPhasesExist"; + /** Argument for sending mechanisms with phases */ public static final String SEND_MECHANISMS_WITH_PHASES = "--sendMechanismWhenPhasesExist"; + /** Argument for creating internal products */ public static final String CREATE_INTERNAL_PRODUCTS = "--internal"; + /** Argument for creating scenario products */ public static final String CREATE_SCENARIO_PRODUCTS = "--scenario"; + /** Argument for testing */ public static final String TEST_ARGUMENT = "--test"; /** @@ -695,6 +783,7 @@ else if (poll) { } + /** Usage for interface */ public static void printUsage() { System.err .println("\nUsage:\n\n" diff --git a/src/main/java/gov/usgs/earthquake/eids/EIDSOutputWedge.java b/src/main/java/gov/usgs/earthquake/eids/EIDSOutputWedge.java index 987d3c80..0cf1519a 100644 --- a/src/main/java/gov/usgs/earthquake/eids/EIDSOutputWedge.java +++ b/src/main/java/gov/usgs/earthquake/eids/EIDSOutputWedge.java @@ -16,20 +16,28 @@ public class EIDSOutputWedge extends DefaultNotificationListener { private static final Logger LOGGER = Logger .getLogger(EIDSOutputWedge.class.getName()); + /** String for output type of EQXML */ public static final String OUTPUT_TYPE_EQXML = "eqxml.xml"; + /** String for output type of quakeml */ public static final String OUTPUT_TYPE_QUAKEML = "quakeml.xml"; + /** String for output type of cube */ public static final String OUTPUT_TYPE_CUBE = "cube.txt"; - // Config keys + /** Property for output directory */ public static final String OUTPUT_DIRECTORY_PROPERTY = "directory"; + /** Property for temp directory */ public static final String TEMP_DIRECTORY_PROPERTY = "tempDirectory"; + /** Property for file name */ public static final String FILE_NAME_PROPERTY = "contentFile"; + /** Property for output format */ public static final String OUTPUT_FORMAT_PROPERTY = "outputFormat"; - // Defaults + /** Default output directory */ public static final File DEFAULT_DIRECTORY = new File("outputdir"); + /** Default temp directory */ public static final File DEFAULT_TEMP_DIRECTORY = new File( System.getProperty("java.io.tmpdir")); + /** Sets default output format to cube.txt */ public static final String DEFAULT_OUTPUT_FORMAT = OUTPUT_TYPE_CUBE; // Local Variables @@ -41,7 +49,7 @@ public class EIDSOutputWedge extends DefaultNotificationListener { /** * Create a new EIDSOutputWedge. - * + * * Sets up the includeTypes list to contain "origin". Override this if you * want the behavior to extend past origin products. */ @@ -52,8 +60,8 @@ public EIDSOutputWedge() { /** * Receive a product from Product Distribution. - * - * @param product + * + * @param product A product */ @Override public void onProduct(final Product product) throws Exception { @@ -85,7 +93,7 @@ public void configure(final Config config) throws Exception { /** * Writes the content of the file you wish to extract to disk with a unique * name and at the directory specified in configuration - * + * * @param data * @throws Exception */ @@ -108,32 +116,37 @@ private void write(byte[] data) throws Exception { FileUtils.writeFileThenMove(srcFile, destFile, data); } - // Getters + /** @return directory */ public File getDirectory() { return directory; } + /** @return tempDirectory */ public File getTempDirectory() { return tempDirectory; } + /** @return outputFormat */ public String getOutputFormat() { return outputFormat; } + /** @return legacy converter */ public LegacyConverter getConverter() { return converter; } - // Setters + /** @param directory file to set */ public void setDirectory(File directory) { this.directory = directory; } + /** @param tempDirectory file to set */ public void setTempDirectory(File tempDirectory) { this.tempDirectory = tempDirectory; } + /** @param outputFormat string to set */ public void setOutputFormat(String outputFormat) { if (outputFormat.equals(OUTPUT_TYPE_EQXML)) { converter = LegacyConverter.eqxmlConverter(); diff --git a/src/main/java/gov/usgs/earthquake/eids/EIDSProductBuilder.java b/src/main/java/gov/usgs/earthquake/eids/EIDSProductBuilder.java index 3aeae329..f5bd4314 100644 --- a/src/main/java/gov/usgs/earthquake/eids/EIDSProductBuilder.java +++ b/src/main/java/gov/usgs/earthquake/eids/EIDSProductBuilder.java @@ -18,7 +18,7 @@ /** * Convert messages from EIDS into products. - * + * * Listens to messages from an EIDSClient. Uses EQXMLProductParser and * EventAddonParser to build products. Any built products are sent to all * configured productSenders. @@ -37,7 +37,7 @@ public class EIDSProductBuilder extends ProductBuilder implements EIDSListener { /** * Receive EIDS messages from an EIDSClient. - * + * * Any received messages are parsed and sent to any ProductSenders. If the * message is not EQXML, this method returns immediately. */ @@ -121,11 +121,11 @@ public synchronized void onEIDSMessage(EIDSMessageEvent event) { /** * Main method to test EQXMLProductBuilder. - * + * * Connects an eids client to the product builder, and uses a dummy product * sender that outputs to stderr. - * - * @param args + * + * @param args arguments included in the running of main */ public static void main(final String[] args) { EIDSProductBuilder builder = new EIDSProductBuilder(); diff --git a/src/main/java/gov/usgs/earthquake/eids/EQMessageProductCreator.java b/src/main/java/gov/usgs/earthquake/eids/EQMessageProductCreator.java index c98061ad..41b00922 100644 --- a/src/main/java/gov/usgs/earthquake/eids/EQMessageProductCreator.java +++ b/src/main/java/gov/usgs/earthquake/eids/EQMessageProductCreator.java @@ -48,7 +48,7 @@ /** * Convert EQXML messages to Products. - * + * *

    * Product source is EQMessage/Source. *

    @@ -64,7 +64,7 @@ *

    * Product updateTime is EQMessage/Sent. *

    - * + * *

    * Origin properties appear only on origin type products. Magnitude properties * appear on both magnitude and origin products. @@ -75,10 +75,12 @@ public class EQMessageProductCreator implements ProductCreator { private static final Logger LOGGER = Logger .getLogger(EQMessageProductCreator.class.getName()); + /** Static var for the xml content type */ public static final String XML_CONTENT_TYPE = "application/xml"; /** Path to content where source message is stored in created product. */ public static final String EQMESSAGE_CONTENT_PATH = "eqxml.xml"; + /** Path to contests xml */ public static final String CONTENTS_XML_PATH = "contents.xml"; /** @@ -123,13 +125,13 @@ public EQMessageProductCreator() { /** * Get all the products contained in an EQMessage. - * + * * Same as getEQMessageProducts(message, null). - * + * * @param message * the EQMessage containing products. * @return a list of created products. - * @throws Exception + * @throws Exception if error occurs */ public synchronized List getEQMessageProducts( final EQMessage message) throws Exception { @@ -138,16 +140,16 @@ public synchronized List getEQMessageProducts( /** * Get all the products contained in an EQMessage. - * + * * Parses rawEqxml string into an EQMessage, but preserves raw eqxml in * created products. - * + * * Same as getEQMessageProducts(EQMessageParser.parse(rawEqxml), rawEqxml); - * + * * @param rawEqxml * the raw EQXML message. * @return a list of created products. - * @throws Exception + * @throws Exception if error occurs */ public synchronized List getEQMessageProducts(final String rawEqxml) throws Exception { @@ -157,14 +159,14 @@ public synchronized List getEQMessageProducts(final String rawEqxml) /** * Get all the products contained in an EQMessage. - * + * * @param message * the EQMessage containing products. * @param rawEqxml * the raw EQXML message. When null, an EQXML message is * serialized from the object. * @return a list of created products. - * @throws Exception + * @throws Exception if error occurs */ public synchronized List getEQMessageProducts( final EQMessage message, final String rawEqxml) throws Exception { @@ -209,11 +211,11 @@ public synchronized List getEQMessageProducts( /** * Get products from an event. - * + * * @param event * the event containing products. * @return a list of created products. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List getEventProducts(final Event event) throws Exception { @@ -268,14 +270,16 @@ protected synchronized List getEventProducts(final Event event) /** * Get origin product(s). - * + * * This implementation only creates one origin (the first one) regardless of * how many origins are provided. - * + * * @param origins * the list of origins. + * @param event + * A specific event * @return a list of created products. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List getOriginProducts( final List origins, final Event event) throws Exception { @@ -447,9 +451,9 @@ protected synchronized List getOriginProducts( /** * Build magnitude products. - * + * * This implementation builds at most one magnitude product (the first). - * + * * @param magnitudes * a list of candidate magsnitude objects. * @return a list of built magnitude products, which may be empty. @@ -502,6 +506,11 @@ protected synchronized List getMagnitudeProducts( return products; } + /** + * Gets a list of Focal Mechanism products from momentTensors + * @param momentTensors List of Moment Tensors + * @return a list of products + */ protected synchronized List getFocalMechanismProducts( final List momentTensors) { List products = new LinkedList(); @@ -639,12 +648,11 @@ protected synchronized List getFocalMechanismProducts( /** * Get product(s) from a ProductLink object. - * - * + * * @param link * the link object. * @return a list of found products. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List getProductLinkProducts( final ProductLink link) throws Exception { @@ -690,11 +698,11 @@ protected synchronized List getProductLinkProducts( /** * Get product(s) from a Comment object. - * + * * @param comment * the comment object. * @return a list of found products. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List getCommentProducts( final Comment comment) throws Exception { @@ -738,11 +746,11 @@ protected synchronized List getCommentProducts( /** * Build a product skeleton based on the current state. - * + * * Product type is : [internal-](origin,magnitude,addon)[-(scenario|test)] * where the optional scope is not "Public", and the optional usage is not * "Actual". - * + * * @param type * short product type, like "origin", "magnitude". * @param action @@ -829,6 +837,9 @@ protected synchronized Product getProduct(final String type, return product; } + /** + * @return a buffer of XML content + */ protected Content getContentsXML() { StringBuffer buf = new StringBuffer(); buf.append("\n"); @@ -851,12 +862,12 @@ protected Content getContentsXML() { /** * Extract a CUBE_Code from a Comment. - * + * * This is the ISTI convention for preserving CUBE information in EQXML * messages. Checks a list of Comment objects for one with * TypeKey="CUBE_Code" and Text="CUBE_Code X", where X is the returned cube * code. - * + * * @param comments * the list of comments. * @return the cube code, or null if not found. @@ -878,10 +889,14 @@ protected synchronized String getCubeCode(final List comments) { return cubeCode; } + /** + * @return boolean sendOriginWhenPhasesExist + */ public boolean isSendOriginWhenPhasesExist() { return sendOriginWhenPhasesExist; } + /** @param sendOriginWhenPhasesExist boolean to set */ public void setSendOriginWhenPhasesExist(boolean sendOriginWhenPhasesExist) { this.sendOriginWhenPhasesExist = sendOriginWhenPhasesExist; } @@ -945,34 +960,45 @@ public List getProducts(File file) throws Exception { return this.getEQMessageProducts(eqxml, rawEqxml); } + /** Type for general text */ public static final String GENERAL_TEXT_TYPE = "general-text"; + /** Empty string array for general text addons */ public static final String[] GENERAL_TEXT_ADDONS = new String[] {}; + /** Type for scitech text */ public static final String SCITECH_TEXT_TYPE = "scitech-text"; + /** Empty string array for scitech text addons */ public static final String[] SCITECH_TEXT_ADDONS = new String[] {}; + /** Type for impact text */ public static final String IMPACT_TEXT_TYPE = "impact-text"; + /** String array for impact text addons */ public static final String[] IMPACT_TEXT_ADDONS = new String[] { "feltreports" }; /** Selected link type products have a mapping. */ public static final String GENERAL_LINK_TYPE = "general-link"; + /** String array for general link addons */ public static final String[] GENERAL_LINK_ADDONS = new String[] { "aftershock", "afterwarn", "asw", "generalmisc" }; + /** Type for scitech link */ public static final String SCITECH_LINK_TYPE = "scitech-link"; + /** String array for scitech link */ public static final String[] SCITECH_LINK_ADDONS = new String[] { "energy", "focalmech", "ncfm", "histmomenttensor", "finitefault", "momenttensor", "mtensor", "phase", "seiscrosssec", "seisrecsec", "traveltimes", "waveform", "seismograms", "scitechmisc" }; + /** Type for impact link */ public static final String IMPACT_LINK_TYPE = "impact-link"; + /** String array for impact link */ public static final String[] IMPACT_LINK_ADDONS = new String[] { "tsunamilinks", "impactmisc" }; /** * Map from cube style link addon to product type. - * - * @param addonType + * + * @param addonType String to find correct link type * @return null if link should not be converted to a product. */ public String getLinkAddonProductType(final String addonType) { @@ -1001,8 +1027,8 @@ public String getLinkAddonProductType(final String addonType) { /** * Map from cube style text addon to product type. - * - * @param addonType + * + * @param addonType to find correct addon type * @return null if comment should not be converted to a product. */ public String getTextAddonProductType(final String addonType) { diff --git a/src/main/java/gov/usgs/earthquake/eids/EventAddonParser.java b/src/main/java/gov/usgs/earthquake/eids/EventAddonParser.java index ae1b585d..d24e43e2 100644 --- a/src/main/java/gov/usgs/earthquake/eids/EventAddonParser.java +++ b/src/main/java/gov/usgs/earthquake/eids/EventAddonParser.java @@ -21,7 +21,7 @@ /** * Parser for event addon messages. - * + * * Maps these messages into an EQMessage with a * product link. */ @@ -34,6 +34,12 @@ public class EventAddonParser extends SAXAdapter { /** The parsed addon object. */ private EventAddon addon; + /** + * Takes a EIDSMessage event and returns the EQMessage + * @param event EIDSMessageEvent to parse + * @return an EQmessage + * @throws Exception if error occurs + */ public EQMessage parseMessage(EIDSMessageEvent event) throws Exception { // create a parser object for this message EventAddonParser parser = new EventAddonParser(); @@ -60,24 +66,36 @@ public EQMessage parseMessage(EIDSMessageEvent event) throws Exception { */ public static class EventAddon { + /** fileName */ public String fileName; + /** Submitter */ public String submitter; + /** Submit time */ public Date submitTime; + /** email */ public String email; + /** event id */ public String eventid; + /** type */ public String type; + /** version */ public String version; + /** action */ public String action; + /** description */ public String description; + /** link */ public String link; + /** text */ public String text; + /** Constructor */ public EventAddon() { } /** * Parse eventaddon xml into a ProductLink. - * + * * @return null, if there is no link. */ public ProductLink getProductLink() { @@ -104,7 +122,7 @@ public ProductLink getProductLink() { /** * Parse eventaddon xml into a Comment. - * + * * @return null, if there is a link. */ public Comment getComment() { @@ -127,6 +145,7 @@ public Comment getComment() { return comment; } + /** @return event */ public Event getEvent() { Event event = new Event(); event.setDataSource(eventid.substring(0, 2)); @@ -143,6 +162,7 @@ public Event getEvent() { return event; } + /** @return EQMessage */ public EQMessage getEQMessage() { EQMessage message = new EQMessage(); message.setSent(submitTime); @@ -154,7 +174,7 @@ public EQMessage getEQMessage() { /** * Get parsed addon. - * + * * @return parsed addon, or null if nothing parsed. */ public EventAddon getAddon() { @@ -163,7 +183,7 @@ public EventAddon getAddon() { /** * SAXAdapter start element handler. - * + * * @param uri * element uri. * @param localName @@ -189,7 +209,7 @@ public void onStartElement(final String uri, final String localName, /** * SAXAdapter end element handler. Content only includes characters that * were read from this element, NOT any characters from child elements. - * + * * @param uri * element uri. * @param localName diff --git a/src/main/java/gov/usgs/earthquake/eids/LegacyConverter.java b/src/main/java/gov/usgs/earthquake/eids/LegacyConverter.java index b54ed3bb..49bec11b 100644 --- a/src/main/java/gov/usgs/earthquake/eids/LegacyConverter.java +++ b/src/main/java/gov/usgs/earthquake/eids/LegacyConverter.java @@ -17,20 +17,35 @@ */ public class LegacyConverter { + /** Different format types */ public static enum Format { - CUBE, EQXML, QUAKEML + /** Enum for Cube Format */ + CUBE, + /** Enum for EQXML Format */ + EQXML, + /** Enum for QUAKEML Format */ + QUAKEML }; + /** Cube Format */ public static final Format CUBE = Format.CUBE; + /** EQXML Format */ public static final Format EQXML = Format.EQXML; + /** QUAKEML Format */ public static final Format QUAKEML = Format.QUAKEML; + /** Path to EQXML content */ public static final String EQXML_CONTENT_PATH = "eqxml.xml"; + /** Path to Quakeml content */ public static final String QUAKEML_CONTENT_PATH = "quakeml.xml"; private final Format outputFormat; private final Converter converter; + /** + * Constructor + * @param outputFormat format you want to switch to + */ public LegacyConverter(final Format outputFormat) { this.outputFormat = outputFormat; this.converter = new Converter(); @@ -60,12 +75,12 @@ public static LegacyConverter quakemlConverter() { /** * Handles conversion from a product containing either eqxml or quakeml * contents to either eqxml, quakeml, or cube byte array. - * + * * @param product * the product object to convert. * @return byte array containing the output format, or null if unable to * convert. - * @throws Exception + * @throws Exception if error occurs */ public byte[] convert(final Product product) throws Exception { Map contents = product.getContents(); @@ -89,12 +104,12 @@ public byte[] convert(final Product product) throws Exception { /** * Handles conversion from an eqxml to either eqxml, quakeml, or cube byte * array. - * + * * @param eqxml * the eqxml object to convert. * @return byte array containing output format, or null if unable to * convert. - * @throws Exception + * @throws Exception if error occurs */ public byte[] convert(EQMessage eqxml) throws Exception { if (eqxml == null) { @@ -120,12 +135,12 @@ public byte[] convert(EQMessage eqxml) throws Exception { /** * Handles conversion from a quakeml message to either eqxml, quakeml, or * cube byte array. - * + * * @param quakeml * the quakeml object to convert. * @return byte array containing output format, or null if unable to * convert. - * @throws Exception + * @throws Exception if error occurs */ public byte[] convert(Quakeml quakeml) throws Exception { if (quakeml == null) { @@ -151,12 +166,12 @@ public byte[] convert(Quakeml quakeml) throws Exception { /** * Handles conversion from a cube message to either eqxml, quakeml, or cube * byte array. - * + * * @param cube * the cube object to convert. * @return byte array containing output format, or null if unable to * convert. - * @throws Exception + * @throws Exception if error occurs */ public byte[] convert(CubeMessage cube) throws Exception { if (cube == null) { diff --git a/src/main/java/gov/usgs/earthquake/eids/ProductCreator.java b/src/main/java/gov/usgs/earthquake/eids/ProductCreator.java index 080aa1b2..3a6d252e 100644 --- a/src/main/java/gov/usgs/earthquake/eids/ProductCreator.java +++ b/src/main/java/gov/usgs/earthquake/eids/ProductCreator.java @@ -7,17 +7,18 @@ /** * Interface used by the EIDSInputWedge to create products from files. - * + * * Parse a file (or directory) into a list of products. */ public interface ProductCreator { /** * Parse product(s) from a file or directory. - * + * * @param file * file or directory. * @return list of parsed products. + * @throws Exception if error occurs */ List getProducts(final File file) throws Exception; @@ -28,8 +29,8 @@ public interface ProductCreator { /** * Enable validation during getProducts method. - * - * @param validate + * + * @param validate boolean to enable/disable * @throws IllegalArgumentException * if creator doesn't support validation. */ diff --git a/src/main/java/gov/usgs/earthquake/eids/QuakemlProductCreator.java b/src/main/java/gov/usgs/earthquake/eids/QuakemlProductCreator.java index c0a6717b..c747505d 100644 --- a/src/main/java/gov/usgs/earthquake/eids/QuakemlProductCreator.java +++ b/src/main/java/gov/usgs/earthquake/eids/QuakemlProductCreator.java @@ -55,15 +55,21 @@ */ public class QuakemlProductCreator implements ProductCreator { + /** For use in logging issues */ public static final Logger LOGGER = Logger .getLogger(QuakemlProductCreator.class.getName()); + /** Content type for xml */ public static final String XML_CONTENT_TYPE = "application/xml"; + /** Content path for quakeml */ public static final String QUAKEML_CONTENT_PATH = "quakeml.xml"; + /** Contents XML path */ public static final String CONTENTS_XML_PATH = "contents.xml"; + /** Var for number of meters/kilometer... */ public static final BigDecimal METERS_PER_KILOMETER = new BigDecimal("1000"); + /** Version */ public static final String VERSION = "1.0"; /** @@ -91,19 +97,36 @@ public class QuakemlProductCreator implements ProductCreator { private boolean padForBase64Bug = false; + /** Default Constructor */ public QuakemlProductCreator() { super(); } + /** + * Constructor taking in argument for Base64 bug padding + * @param padForBase64Bug Boolean if needed to pad + */ public QuakemlProductCreator(boolean padForBase64Bug) { this.padForBase64Bug = padForBase64Bug; } + /** + * Gets Quakeml products with no rawQuakeml + * @param message Parsed quakeml message + * @return List of products + * @throws Exception if error occurs + */ public List getQuakemlProducts(final Quakeml message) throws Exception { return getQuakemlProducts(message, null); } + /** + * Gets Quakeml products with the message as a rawQuakeml + * @param message Parsed quakeml message + * @return List of products + * @throws Exception if error occurs + */ public List getQuakemlProducts(final String message) throws Exception { Quakeml quakeml = formatConverter.getQuakeml(message, validate); @@ -121,7 +144,7 @@ public List getQuakemlProducts(final String message) * original input, instead of always serializing from the quakeml * object. * @return list of products generated from quakeml message. - * @throws Exception + * @throws Exception if error occurs */ public List getQuakemlProducts(final Quakeml message, final String rawQuakeml) throws Exception { @@ -177,7 +200,7 @@ public List getQuakemlProducts(final Quakeml message, * @param event * the internal event element. * @return list of internal products found in event element, may be empty. - * @throws Exception + * @throws Exception if error occurs */ public List getInternalEventProducts(final Quakeml message, final InternalEvent event) throws Exception { @@ -201,7 +224,7 @@ public List getInternalEventProducts(final Quakeml message, * @param event * the scenario event element. * @return list of scenario products found in event element, may be empty. - * @throws Exception + * @throws Exception if error occurs */ public List getScenarioEventProducts(final Quakeml message, final ScenarioEvent event) throws Exception { @@ -222,7 +245,7 @@ public List getScenarioEventProducts(final Quakeml message, * @param event * the event element in the quakeml message. * @return list of products found in event element, may be empty. - * @throws Exception + * @throws Exception if error occurs */ public List getEventProducts(final Quakeml message, Event event) throws Exception { @@ -531,6 +554,13 @@ public List getEventProducts(final Quakeml message, Event event) return products; } + /** + * @param quakeml Quakeml + * @param event the event element in the quakeml message + * @param mech A focal mechanism + * @param quakemlContent String of content in Quakeml + * @return A product derived from a focal mechanism + */ protected Product getFocalMechanismProduct(final Quakeml quakeml, final Event event, final FocalMechanism mech, final String quakemlContent) { @@ -744,11 +774,24 @@ protected Product getFocalMechanismProduct(final Quakeml quakeml, return product; } + /** + * setProperty for RealQuantity values. No exponentials + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final RealQuantity value) { setProperty(properties, name, value, false); } + /** + * setProperty for RealQuantity values + * @param properties to add + * @param name of property + * @param value of property + * @param allowExponential if allowed + */ public void setProperty(final Map properties, final String name, final RealQuantity value, final boolean allowExponential) { @@ -759,6 +802,12 @@ public void setProperty(final Map properties, setProperty(properties, name, value.getValue(), allowExponential); } + /** + * setProperty for strings + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final String value) { if (value == null) { @@ -768,6 +817,12 @@ public void setProperty(final Map properties, properties.put(name, value); } + /** + * setProperty for TimeQuantities + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final TimeQuantity value) { if (value == null) { @@ -777,11 +832,24 @@ public void setProperty(final Map properties, properties.put(name, XmlUtils.formatDate(value.getValue())); } + /** + * setProperty taking in BigDecimals. No exponentials + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final BigDecimal value) { setProperty(properties, name, value, false); } + /** + * setProperty taking in BigDecimals + * @param properties to add + * @param name of property + * @param value of property + * @param allowExponential boolean + */ public void setProperty(final Map properties, final String name, final BigDecimal value, final boolean allowExponential) { @@ -793,6 +861,12 @@ public void setProperty(final Map properties, : value.toPlainString()); } + /** + * setProperty taking in BigIntegers. No exponentials + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final BigInteger value) { if (value == null) { @@ -802,6 +876,12 @@ public void setProperty(final Map properties, properties.put(name, value.toString()); } + /** + * setProperty taking in Integers + * @param properties to add + * @param name of property + * @param value of property + */ public void setProperty(final Map properties, final String name, final Integer value) { if (value == null) { @@ -811,10 +891,12 @@ public void setProperty(final Map properties, properties.put(name, value.toString()); } + /** @param converter FileToQuakeml Converter to set */ public void setConverter(FileToQuakemlConverter converter) { this.converter = converter; } + /** @return FileToQuakeml converter */ public FileToQuakemlConverter getConverter() { return converter; } @@ -844,6 +926,9 @@ public List getProducts(File file) throws Exception { } } + /** + * @return XML contents + */ protected Content getContentsXML() { StringBuffer buf = new StringBuffer(); buf.append("\n"); @@ -860,27 +945,33 @@ protected Content getContentsXML() { return content; } + /** @return boolean sendOriginWhenPhasesExist */ public boolean isSendOriginWhenPhasesExist() { return sendOriginWhenPhasesExist; } + /** @param sendOriginWhenPhasesExist boolean to set */ public void setSendOriginWhenPhasesExist(boolean sendOriginWhenPhasesExist) { this.sendOriginWhenPhasesExist = sendOriginWhenPhasesExist; } + /** @param sendMechanismWhenPhasesExist boolean to set */ public void setSendMechanismWhenPhasesExist( boolean sendMechanismWhenPhasesExist) { this.sendMechanismWhenPhasesExist = sendMechanismWhenPhasesExist; } + /** @return sendMechanismWhenPhasesExist boolean */ public boolean isSendMechanismWhenPhasesExist() { return sendMechanismWhenPhasesExist; } + /** @param padForBase64Bug to set */ public void setPadForBase64Bug(boolean padForBase64Bug) { this.padForBase64Bug = padForBase64Bug; } + /** @return padForBase64Bug */ public boolean isPadForBase64Bug() { return padForBase64Bug; } @@ -917,7 +1008,7 @@ public String fixRawQuakeml(String rawMessage) { * * @param args * a list of files to convert from quakeml to products. - * @throws Exception + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { QuakemlProductCreator creator = new QuakemlProductCreator(); diff --git a/src/main/java/gov/usgs/earthquake/eids/QuakemlUtils.java b/src/main/java/gov/usgs/earthquake/eids/QuakemlUtils.java index 531feee3..81239ccd 100644 --- a/src/main/java/gov/usgs/earthquake/eids/QuakemlUtils.java +++ b/src/main/java/gov/usgs/earthquake/eids/QuakemlUtils.java @@ -31,8 +31,8 @@ public class QuakemlUtils { * If a quakeml event object does not exist, check for the first internal or * scenario event. * - * @param eventParameters - * @return + * @param eventParameters to find event from + * @return first event */ public static Event getFirstEvent(final EventParameters eventParameters) { // only process first event @@ -61,7 +61,7 @@ public static Event getFirstEvent(final EventParameters eventParameters) { /** * Find the preferred Origin in an Event. * - * @param event + * @param event event * @return Origin with publicID equal to event.getPreferredOriginID(), or null * if not found. */ @@ -147,7 +147,7 @@ public static FocalMechanism getFocalMechanism(final Event event, final String i * Flatten multiple creation info objects, but using the most specific (at end * of list) value that is not null. * - * @param infos + * @param infos to flatten * @return a CreationInfo object with the most specific properties (later in * arguments list), which may be null. */ @@ -185,7 +185,7 @@ public static CreationInfo getCreationInfo(final CreationInfo... infos) { } /** - * @param value + * @param value RealQuantity * @return value.getValue(), or null if value == null. */ public static BigDecimal getValue(final RealQuantity value) { @@ -197,7 +197,7 @@ public static BigDecimal getValue(final RealQuantity value) { } /** - * @param value + * @param value IntegerQuantity * @return value.getValue(), or null if value == null. */ public static BigInteger getValue(final IntegerQuantity value) { @@ -209,7 +209,7 @@ public static BigInteger getValue(final IntegerQuantity value) { } /** - * @param value + * @param value TimeQuantity * @return value.getValue(), or null if value == null. */ public static Date getValue(final TimeQuantity value) { @@ -220,6 +220,9 @@ public static Date getValue(final TimeQuantity value) { } } + /** + * @param magnitudeType to return + * @return MagntitudeType string */ public static String getMagnitudeType(final String magnitudeType) { if (magnitudeType == null) { return null; @@ -428,7 +431,7 @@ public static Quakeml getLightweightFocalMechanism(final Quakeml q, final String * * omits anies, events, and other attributes. * - * @param oldEventParameters + * @param oldEventParameters to copy * @return a new EventParameters object. */ public static EventParameters shallowClone(final EventParameters oldEventParameters) { @@ -446,7 +449,7 @@ public static EventParameters shallowClone(final EventParameters oldEventParamet * omits amplitudes, anies, event descriptions, mechanisms, magnitudes, origins, * other attributes, picks, preferred*ID, and station magnitudes. * - * @param oldEvent + * @param oldEvent to copy * @return a new Event object. */ public static Event shallowClone(final Event oldEvent) { @@ -468,7 +471,7 @@ public static Event shallowClone(final Event oldEvent) { * * omits anies, arrivals, and other attributes. * - * @param oldOrigin + * @param oldOrigin to copy * @return a new Origin object. */ public static Origin shallowClone(final Origin oldOrigin) { @@ -505,7 +508,7 @@ public static Origin shallowClone(final Origin oldOrigin) { * * omits anies, other attributes, and station magnitude contributions. * - * @param oldMagnitude + * @param oldMagnitude to copy * @return a new Magnitude object. */ public static Magnitude shallowClone(final Magnitude oldMagnitude) { @@ -533,7 +536,7 @@ public static Magnitude shallowClone(final Magnitude oldMagnitude) { * * omits anies, other attributes. * - * @param oldMech + * @param oldMech to copy * @return a new FocalMechanism object. */ public static FocalMechanism shallowClone(final FocalMechanism oldMech) { diff --git a/src/main/java/gov/usgs/earthquake/eidsutil/CorbaSender.java b/src/main/java/gov/usgs/earthquake/eidsutil/CorbaSender.java index c767fc54..06ba0253 100644 --- a/src/main/java/gov/usgs/earthquake/eidsutil/CorbaSender.java +++ b/src/main/java/gov/usgs/earthquake/eidsutil/CorbaSender.java @@ -61,11 +61,11 @@ public class CorbaSender { * messages using this CorbaSender. * @param port The port number to send messages to on the host. * - * @throws InvalidName If the RootPOA is not aware of the type of object we + * @throws InvalidName If the RootPOA is not aware of the type of object we * request from it. * @throws AdapterInactive If the poaManager is not active. */ - public CorbaSender(String host, String port) + public CorbaSender(String host, String port) throws InvalidName, AdapterInactive { // Create the corbaloc url @@ -89,12 +89,13 @@ public CorbaSender(String host, String port) } // END: constructor CorbaSender + /** Cleanup */ public void destroy() { try { feeder._release(); } catch (Exception ex) { /* ignore */ } try { object._release(); } catch (Exception ex) { /* ignore */ } try { orb.shutdown(true); } catch (Exception ex) { /* ignore */ } try { orb.destroy(); } catch (Exception ex) { /* ignore */ } - + feeder = null; object = null; poaManager = null; @@ -104,7 +105,7 @@ public void destroy() { /** * Retrieve a QWFeeder object associated with this CorbaSender. - * + * * First checks if the object is "non_existent", and if so re-narrows the object. * @return QWFeeder object, or null if unable to narrow. */ @@ -116,7 +117,7 @@ protected QWFeeder getFeeder() { object = null; } } catch (org.omg.CORBA.OBJECT_NOT_EXIST e) { - // feeder._non_existent throws the OBJECT_NOT_EXIST exception + // feeder._non_existent throws the OBJECT_NOT_EXIST exception // instead of returning true... feeder = null; object = null; @@ -144,9 +145,9 @@ protected QWFeeder getFeeder() { /** * Sends a data event message. If the event data does not begin with a - * “DataMessage” XML element then the data will be surrounded - * with one. The “sendSourced...” methods are preferred because - * the feeder-source host name and message number are used for improved + * “DataMessage” XML element then the data will be surrounded + * with one. The “sendSourced...” methods are preferred because + * the feeder-source host name and message number are used for improved * message tracking. * * @param message The data event message string. @@ -156,12 +157,12 @@ protected QWFeeder getFeeder() { public boolean sendMessage(String message) { return getFeeder().sendMessage(message); } - + /** * Sends a data event message. If the event data does not begin with a - * “DataMessage” XML element then the data will be surrounded - * with one. The “sendSourced...” methods are preferred because - * the feeder-source host name and message number are used for improved + * “DataMessage” XML element then the data will be surrounded + * with one. The “sendSourced...” methods are preferred because + * the feeder-source host name and message number are used for improved * message tracking. * * @param domain The domain name to use. @@ -178,9 +179,9 @@ public boolean sendMessage(String domain, String type, String message) { /** * Sends a data event message. If the event data does not begin with a - * “DataMessage” XML element then the data will be surrounded - * with one. The “sendSourced...” methods are preferred because - * the feeder-source host name and message number are used for improved + * “DataMessage” XML element then the data will be surrounded + * with one. The “sendSourced...” methods are preferred because + * the feeder-source host name and message number are used for improved * message tracking. * * @param domain The domain name to use. @@ -195,7 +196,7 @@ public boolean sendMessage(String domain, String type, String name, String message) { return getFeeder().sendDomainTypeNameMessage(domain, type, name, message); } - + /** * Sends a data event message. If the event data does not begin with a * “DataMessage” XML element then the data will be surrounded @@ -211,17 +212,17 @@ public boolean sendMessage(String domain, String type, String name, * @return true after the message has been successfully stored * and processed; false if an error occurred. */ - public boolean sendMessage(String message, String feederSourceHost, + public boolean sendMessage(String message, String feederSourceHost, long feederSrcHostMsgId) { - return getFeeder().sendSourcedMsg(message, feederSourceHost, + return getFeeder().sendSourcedMsg(message, feederSourceHost, feederSrcHostMsgId); } /** * Sends a data event message. If the event data does not begin with a - * “DataMessage” XML element then the data will be surrounded - * with one. The “sendSourced...” methods are preferred because - * the feeder-source host name and message number are used for improved + * “DataMessage” XML element then the data will be surrounded + * with one. The “sendSourced...” methods are preferred because + * the feeder-source host name and message number are used for improved * message tracking. * * @param domain The domain name to use. @@ -234,7 +235,7 @@ public boolean sendMessage(String message, String feederSourceHost, * @return true after the message has been successfully stored * and processed; false if an error occurred. */ - public boolean sendMessage(String domain, String type, String message, + public boolean sendMessage(String domain, String type, String message, String feederSourceHost, long feederSrcHostMsgId) { return getFeeder().sendSourcedDomainTypeMsg(domain, type, message, feederSourceHost, feederSrcHostMsgId); @@ -242,9 +243,9 @@ public boolean sendMessage(String domain, String type, String message, /** * Sends a data event message. If the event data does not begin with a - * “DataMessage” XML element then the data will be surrounded - * with one. The “sendSourced...” methods are preferred because - * the feeder-source host name and message number are used for improved + * “DataMessage” XML element then the data will be surrounded + * with one. The “sendSourced...” methods are preferred because + * the feeder-source host name and message number are used for improved * message tracking. * * @param domain The domain name to use. @@ -258,7 +259,7 @@ public boolean sendMessage(String domain, String type, String message, * @return true after the message has been successfully stored * and processed; false if an error occurred. */ - public boolean sendMessage(String domain, String type, String name, + public boolean sendMessage(String domain, String type, String name, String message, String feederSourceHost, long feederSrcHostMsgId) { return getFeeder().sendSourcedDomainTypeNameMsg(domain, type, name, message, feederSourceHost, feederSrcHostMsgId); diff --git a/src/main/java/gov/usgs/earthquake/eidsutil/EIDSClient.java b/src/main/java/gov/usgs/earthquake/eidsutil/EIDSClient.java index 8d821a0f..6191bfc8 100644 --- a/src/main/java/gov/usgs/earthquake/eidsutil/EIDSClient.java +++ b/src/main/java/gov/usgs/earthquake/eidsutil/EIDSClient.java @@ -77,17 +77,18 @@ public class EIDSClient implements EIDSListener { /** Whether we are debugging or not. Affects log level. */ private boolean debug; + /** Constructor using default host and port */ public EIDSClient() { this(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT); } /** * Construct an EIDSClient using only server host and port. - * + * * Calls other constructor with null values for other parameters. - * - * @param serverHost - * @param serverPort + * + * @param serverHost Specific host + * @param serverPort Specific port */ public EIDSClient(final String serverHost, final Integer serverPort) { this(serverHost, serverPort, ""); @@ -96,10 +97,12 @@ public EIDSClient(final String serverHost, final Integer serverPort) { /** * Construct an EIDSClient using serverHost, serverPort, and * alternateServersList. - * - * @param serverHost - * @param serverPort + * + * @param serverHost Host + * @param serverPort Port * @param alternateServersList + * a comma delimited list of host:port that are used when unable + * to connect to the primary serverHost and serverPort. */ public EIDSClient(final String serverHost, final Integer serverPort, final String alternateServersList) { @@ -110,7 +113,7 @@ public EIDSClient(final String serverHost, final Integer serverPort, /** * Constructor with all options. - * + * * @param serverHost * the eids server host or ip address. * @param serverPort @@ -123,6 +126,8 @@ public EIDSClient(final String serverHost, final Integer serverPort, * @param trackingFileName * location where tracking file is stored. This file is used to * track which messages have been received. + * @param clientRestartInterval + * How often to periodically restart the client, in milliseconds */ public EIDSClient(final String serverHost, final Integer serverPort, final String alternateServersList, @@ -138,7 +143,7 @@ public EIDSClient(final String serverHost, final Integer serverPort, /** * Runs the client. - * + * * Any listeners should be added before calling this method. */ public void startup() { @@ -177,7 +182,7 @@ public void run() { /** * Shuts down a running client. - * + * * Does not call system.exit. */ public void shutdown() { @@ -192,7 +197,7 @@ public void shutdown() { /** * Add a listener. - * + * * @param listener * the listener to add. */ @@ -202,7 +207,7 @@ public synchronized void addListener(final EIDSListener listener) { /** * Remove a listener. - * + * * @param listener * the listener to remove. */ @@ -294,22 +299,34 @@ public void setTrackingFileName(String trackingFileName) { this.trackingFileName = trackingFileName; } + /** + * @return clientRestartInterval + */ public Long getClientRestartInterval() { return clientRestartInterval; } + /** + * @param clientRestartInterval + * the clientRestartInterval to set + */ public void setClientRestartInterval(Long clientRestartInterval) { this.clientRestartInterval = clientRestartInterval; } + /** @param debug to set */ public void setDebug(boolean debug) { this.debug = debug; } + /** @return debug boolean */ public boolean isDebug() { return debug; } + /** + * @return result of reinitialzing the client connection + */ public boolean reinitConnection() { if (client != null) { return client.getConnManagerObj().reinitConnection(); @@ -319,9 +336,9 @@ public boolean reinitConnection() { /** * A method to test the EIDSClient. - * - * @param args - * @throws Exception + * + * @param args arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { EIDSListener listener = new EIDSListener() { diff --git a/src/main/java/gov/usgs/earthquake/eidsutil/QWEmbeddedClient.java b/src/main/java/gov/usgs/earthquake/eidsutil/QWEmbeddedClient.java index 772c26a1..0829ba03 100644 --- a/src/main/java/gov/usgs/earthquake/eidsutil/QWEmbeddedClient.java +++ b/src/main/java/gov/usgs/earthquake/eidsutil/QWEmbeddedClient.java @@ -61,17 +61,18 @@ public class QWEmbeddedClient extends QWTrackingClient implements EIDSListener { /** Console log level. */ private String consoleLogLevel = "Info"; + /** Constructor using the default host and port */ public QWEmbeddedClient() { this(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT); } /** * Construct an EIDSClient using only server host and port. - * + * * Calls other constructor with null values for other parameters. - * - * @param serverHost - * @param serverPort + * + * @param serverHost host of EIDS client + * @param serverPort port of EIDS client */ public QWEmbeddedClient(final String serverHost, final Integer serverPort) { this(serverHost, serverPort, ""); @@ -80,10 +81,12 @@ public QWEmbeddedClient(final String serverHost, final Integer serverPort) { /** * Construct an EIDSClient using serverHost, serverPort, and * alternateServersList. - * - * @param serverHost - * @param serverPort + * + * @param serverHost host of EIDS client + * @param serverPort port of EIDS client * @param alternateServersList + * a comma delimited list of host:port that are used when unable + * to connect to the primary serverHost and serverPort. */ public QWEmbeddedClient(final String serverHost, final Integer serverPort, final String alternateServersList) { @@ -93,7 +96,7 @@ public QWEmbeddedClient(final String serverHost, final Integer serverPort, /** * Constructor with all options. - * + * * @param serverHost * the eids server host or ip address. * @param serverPort @@ -118,7 +121,7 @@ public QWEmbeddedClient(final String serverHost, final Integer serverPort, } /** - * + * */ public void setupConfiguration(CfgProperties userPropsObj, Object connGroupSelObj, Object logGroupSelObj, @@ -150,7 +153,7 @@ public void setupConfiguration(CfgProperties userPropsObj, /** * Runs the client. - * + * * Any listeners should be added before calling this method. */ public void startup() { @@ -169,7 +172,7 @@ public void startup() { /** * Shuts down a running client. - * + * * Does not call system.exit. */ public void shutdown() { @@ -191,7 +194,7 @@ public void shutdown() { /** * Add a listener. - * + * * @param listener * the listener to add. */ @@ -201,7 +204,7 @@ public synchronized void addListener(final EIDSListener listener) { /** * Remove a listener. - * + * * @param listener * the listener to remove. */ @@ -293,19 +296,21 @@ public void setTrackingFileName(String trackingFileName) { this.trackingFileName = trackingFileName; } + /** @return console Log level */ public String getConsoleLogLevel() { return consoleLogLevel; } + /** @param consoleLogLevel to set */ public void setConsoleLogLevel(String consoleLogLevel) { this.consoleLogLevel = consoleLogLevel; } /** * A method to test the EIDSClient. - * - * @param args - * @throws Exception + * + * @param args arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { EIDSListener listener = new EIDSListener() { diff --git a/src/main/java/gov/usgs/earthquake/geoserve/ANSSRegionsFactory.java b/src/main/java/gov/usgs/earthquake/geoserve/ANSSRegionsFactory.java index c48c8883..1991da8f 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/ANSSRegionsFactory.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/ANSSRegionsFactory.java @@ -28,32 +28,32 @@ */ public class ANSSRegionsFactory { - // logging object + /** logging object */ public static final Logger LOGGER = Logger.getLogger(ANSSRegionsFactory.class.getName()); - // milliseconds per day + /** milliseconds per day */ public static final long MILLISECONDS_PER_DAY = 86400000L; - // path to write regions.json + /** path to write regions.json */ public static final String DEFAULT_REGIONS_JSON = "regions.json"; - // global factory object + /** global factory object */ private static ANSSRegionsFactory SINGLETON; - // service used to load regions + /** service used to load regions */ private GeoserveLayersService geoserveLayersService; - // path to local regions file + /** path to local regions file */ private File localRegions = new File(DEFAULT_REGIONS_JSON); - // the current regions object + /** the current regions object */ private Regions regions; - // shutdown hook registered by startup + /** shutdown hook registered by startup */ private Thread shutdownHook; - // timer used to auto fetch region updates + /** timer used to auto fetch region updates */ private Timer updateTimer = new Timer(); @@ -66,6 +66,7 @@ public ANSSRegionsFactory () { /** * Use custom GeoserveLayersService. + * @param geoserveLayersService to use */ public ANSSRegionsFactory (final GeoserveLayersService geoserveLayersService) { this.geoserveLayersService = geoserveLayersService; @@ -74,11 +75,16 @@ public ANSSRegionsFactory (final GeoserveLayersService geoserveLayersService) { /** * Get the global ANSSRegionsFactory, * creating and starting if needed. + * @return ANSSRegionsFactory */ public static synchronized ANSSRegionsFactory getFactory() { return getFactory(true); } + /** + * @param startup if Factory should be created and started, if needed + * @return ANSSRegionsFactory + */ public static synchronized ANSSRegionsFactory getFactory(final boolean startup) { if (SINGLETON == null) { SINGLETON = new ANSSRegionsFactory(); @@ -92,6 +98,7 @@ public static synchronized ANSSRegionsFactory getFactory(final boolean startup) /** * Set the global ANSSRegionsFactory, * shutting down any existing factory if needed. + * @param factory to set */ public static synchronized void setFactory(final ANSSRegionsFactory factory) { if (SINGLETON != null) { @@ -129,6 +136,8 @@ public void fetchRegions () { /** * Read regions from local regions file. + * @return Regions + * @throws IOException if error occurs */ protected Regions loadFromFile() throws IOException { try (InputStream in = StreamUtils.getInputStream(this.localRegions)) { @@ -145,6 +154,8 @@ protected Regions loadFromFile() throws IOException { /** * Read regions from geoserve service. + * @return Regions + * @throws IOException if error occurs */ protected Regions loadFromGeoserve() throws IOException { LOGGER.fine("Fetching ANSS Authoritative Regions from Geoserve"); @@ -163,7 +174,9 @@ protected Regions loadFromGeoserve() throws IOException { /** * Store json to local regions file. * + * @param regionsFile to store to * @param json json response to store locally. + * @throws IOException if IO error occurs */ protected void saveToFile(final File regionsFile, final JsonObject json) throws IOException { LOGGER.fine("Storing ANSS Authoritative Regions to " + regionsFile); @@ -229,6 +242,7 @@ public void shutdown() { /** * Get the service. + * @return geoserveLayersService */ public GeoserveLayersService getGeoserveLayersService() { return this.geoserveLayersService; @@ -236,6 +250,7 @@ public GeoserveLayersService getGeoserveLayersService() { /** * Set the service. + * @param service GeoserveLayersService to set */ public void setGeoserveLayersService(final GeoserveLayersService service) { this.geoserveLayersService = service; @@ -243,6 +258,7 @@ public void setGeoserveLayersService(final GeoserveLayersService service) { /** * Get the local regions file. + * @return localRegions */ public File getLocalRegions() { return this.localRegions; @@ -250,6 +266,7 @@ public File getLocalRegions() { /** * Set the local regions file. + * @param localRegions file to set */ public void setLocalRegions(final File localRegions) { this.localRegions = localRegions; @@ -257,6 +274,7 @@ public void setLocalRegions(final File localRegions) { /** * Get the most recently fetched Regions. + * @return regions */ public Regions getRegions () { return this.regions; diff --git a/src/main/java/gov/usgs/earthquake/geoserve/GeoserveLayersService.java b/src/main/java/gov/usgs/earthquake/geoserve/GeoserveLayersService.java index 07e01f6b..6f02f0d1 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/GeoserveLayersService.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/GeoserveLayersService.java @@ -31,7 +31,7 @@ public GeoserveLayersService() { /** * Create a service using a custom URL. - * + * * @param endpointUrl layers service URL. * Should contain the string {type}, * which is replaced during the #{@link #getLayer(String)}. @@ -42,6 +42,7 @@ public GeoserveLayersService(final String endpointUrl) { /** * Get the endpoint URL. + * @return endpoint URL */ public String getEndpointURL() { return this.endpointUrl; @@ -49,6 +50,7 @@ public String getEndpointURL() { /** * Set the endpoint URL. + * @param url endpoint URL to set */ public void setEndpointURL(final String url) { this.endpointUrl = url; @@ -56,6 +58,10 @@ public void setEndpointURL(final String url) { /** * Fetch and parse a JSON response from the Geoserve layers service. + * @param type type of response to fetch + * @return JSONObject response + * @throws IOException on IO error + * @throws MalformedURLException Error on URL failure */ public JsonObject getLayer(final String type) throws IOException, MalformedURLException { final URL url = new URL(endpointUrl.replace("{type}", type)); diff --git a/src/main/java/gov/usgs/earthquake/geoserve/GeoservePlacesService.java b/src/main/java/gov/usgs/earthquake/geoserve/GeoservePlacesService.java index a60181f5..35505b9e 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/GeoservePlacesService.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/GeoservePlacesService.java @@ -14,10 +14,15 @@ import gov.usgs.util.StreamUtils; +/** + * Access places from the Geoserve Places service. + */ public class GeoservePlacesService { /** Default URL for GeoServe Places service. */ public static final String DEFAULT_ENDPOINT_URL = "https://earthquake.usgs.gov/ws/geoserve/places.json"; + /** Default connection timeout */ public static final int DEFAULT_CONNECT_TIMEOUT = 300; // ms + /** Default read timeout */ public static final int DEFAULT_READ_TIMEOUT = 1700; // ms /** Configured URL for GeoServe Places service. */ @@ -25,32 +30,58 @@ public class GeoservePlacesService { private int connectTimeout; private int readTimeout; + /** Default constructor */ public GeoservePlacesService() { this(DEFAULT_ENDPOINT_URL, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT); } + /** + * Constructor taking in endpointURL + * @param endpointUrl for places service + */ public GeoservePlacesService(final String endpointUrl) { this(endpointUrl, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT); } + /** + * Constructor taking in timeouts and using default endpoint URL + * @param connectTimeout in ms + * @param readTimeout in ms + */ public GeoservePlacesService(final int connectTimeout, final int readTimeout) { this(DEFAULT_ENDPOINT_URL, connectTimeout, readTimeout); } + /** + * Custom constructor + * @param endpointUrl for Places service + * @param connectTimeout in ms + * @param readTimeout in ms + */ public GeoservePlacesService(final String endpointUrl, final int connectTimeout, final int readTimeout) { this.setEndpointURL(endpointUrl); this.setConnectTimeout(connectTimeout); this.setReadTimeout(readTimeout); } + /** @return connectTimemout */ public int getConnectTimeout() { return this.connectTimeout; } + /** @return endpointURL */ public String getEndpointURL() { return this.endpointUrl; } + /** + * Find an event in the Places service via a latitude and longitude + * @param latitude of event + * @param longitude of event + * @return JSONObject of event + * @throws IOException on IO error + * @throws MalformedURLException or URL error + */ public JsonObject getEventPlaces(BigDecimal latitude, BigDecimal longitude) throws IOException, MalformedURLException { final URL url = new URL(this.endpointUrl + @@ -67,6 +98,14 @@ public JsonObject getEventPlaces(BigDecimal latitude, BigDecimal longitude) } } + /** + * Get nearest place to a latitude and longitude + * @param latitude of place + * @param longitude of place + * @return JSONObject of place + * @throws IOException on IO error + * @throws MalformedURLException on URL error + */ public JsonObject getNearestPlace(BigDecimal latitude, BigDecimal longitude) throws IOException, MalformedURLException { JsonObject places = this.getEventPlaces(latitude, longitude); JsonObject feature = places.getJsonArray("features").getJsonObject(0); @@ -74,18 +113,22 @@ public JsonObject getNearestPlace(BigDecimal latitude, BigDecimal longitude) thr return feature; } + /** @return readTimeout */ public int getReadTimeout() { return this.readTimeout; } + /** @param connectTimeout int to set */ public void setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; } + /** @param endpointUrl string to set */ public void setEndpointURL(final String endpointUrl) { this.endpointUrl = endpointUrl; } + /** @param readTimeout int to set */ public void setReadTimeout(final int readTimeout) { this.readTimeout = readTimeout; } diff --git a/src/main/java/gov/usgs/earthquake/geoserve/GeoserveRegionsService.java b/src/main/java/gov/usgs/earthquake/geoserve/GeoserveRegionsService.java index 3c853d8e..e6a4d8c4 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/GeoserveRegionsService.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/GeoserveRegionsService.java @@ -14,10 +14,15 @@ import gov.usgs.util.StreamUtils; +/** + * Access regions from the Geoserve regions service. + */ public class GeoserveRegionsService { /** Default URL for GeoServe Regions service. */ public static final String DEFAULT_ENDPOINT_URL = "https://earthquake.usgs.gov/ws/geoserve/regions.json"; + /** Default connection timeout */ public static final int DEFAULT_CONNECT_TIMEOUT = 300; // ms + /** Default read timeout */ public static final int DEFAULT_READ_TIMEOUT = 1700; // ms /** Configured URL for GeoServe Regions service. */ @@ -25,32 +30,58 @@ public class GeoserveRegionsService { private int connectTimeout; private int readTimeout; + /** Default constructor */ public GeoserveRegionsService() { this(DEFAULT_ENDPOINT_URL, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT); } + /** + * Constructor taking in endpointURL + * @param endpointUrl for places service + */ public GeoserveRegionsService(final String endpointUrl) { this(endpointUrl, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT); } + /** + * Constructor taking in timeouts and using default endpoint URL + * @param connectTimeout in ms + * @param readTimeout in ms + */ public GeoserveRegionsService(final int connectTimeout, final int readTimeout) { this(DEFAULT_ENDPOINT_URL, connectTimeout, readTimeout); } + /** + * Custom constructor + * @param endpointUrl for Places service + * @param connectTimeout in ms + * @param readTimeout in ms + */ public GeoserveRegionsService(final String endpointUrl, final int connectTimeout, final int readTimeout) { this.setEndpointURL(endpointUrl); this.setConnectTimeout(connectTimeout); this.setReadTimeout(readTimeout); } + /** @return connectTimemout */ public int getConnectTimeout() { return this.connectTimeout; } + /** @return endpointURL */ public String getEndpointURL() { return this.endpointUrl; } + /** + * Find an event in the Region service via a latitude and longitude + * @param latitude of event + * @param longitude of event + * @return JSONObject of Fe Region + * @throws IOException on IO error + * @throws MalformedURLException or URL error + */ public JsonObject getFeRegion(BigDecimal latitude, BigDecimal longitude) throws IOException, MalformedURLException { final URL url = new URL(this.endpointUrl + @@ -67,6 +98,14 @@ public JsonObject getFeRegion(BigDecimal latitude, BigDecimal longitude) } } + /** + * Get name of FeRegion + * @param latitude of event + * @param longitude of event + * @return string of FeRegion name + * @throws IOException on IO error + * @throws MalformedURLException or URL error + */ public String getFeRegionName(BigDecimal latitude, BigDecimal longitude) throws IOException, MalformedURLException { JsonObject region = this.getFeRegion(latitude, longitude); String feRegionName = region.getJsonArray("features") @@ -78,18 +117,22 @@ public String getFeRegionName(BigDecimal latitude, BigDecimal longitude) throws return feRegionName; } + /** @return readTimeout */ public int getReadTimeout() { return this.readTimeout; } + /** @param connectTimeout int to set */ public void setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; } + /** @param endpointUrl string to set */ public void setEndpointURL(final String endpointUrl) { this.endpointUrl = endpointUrl; } + /** @param readTimeout int to set */ public void setReadTimeout(final int readTimeout) { this.readTimeout = readTimeout; } diff --git a/src/main/java/gov/usgs/earthquake/geoserve/RegionsJSON.java b/src/main/java/gov/usgs/earthquake/geoserve/RegionsJSON.java index ed9f8bde..e77a0132 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/RegionsJSON.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/RegionsJSON.java @@ -18,6 +18,7 @@ public class RegionsJSON { * Parse {@link gov.usgs.earthquake.qdm.Regions} from a GeoJSON feature collection. * * @param json geojson feature collection. + * @return Regions */ public Regions parseRegions(final JsonObject json) { Regions regions = new Regions(); @@ -26,7 +27,7 @@ public Regions parseRegions(final JsonObject json) { JsonArray features = json.getJsonArray("features"); for (JsonValue value : features) { - JsonObject jsonRegion = value.asJsonObject(); + JsonObject jsonRegion = value.asJsonObject(); Region region = parseRegion(jsonRegion); regions.netids.add(region.netid); regions.regions.add(region); @@ -39,6 +40,7 @@ public Regions parseRegions(final JsonObject json) { * Parse {@link gov.usgs.earthquake.qdm.Region} from a GeoJSON feature. * * @param json geojson feature. + * @return region */ public Region parseRegion(final JsonObject json) { JsonObject properties = json.getJsonObject("properties"); diff --git a/src/main/java/gov/usgs/earthquake/geoserve/RegionsKML.java b/src/main/java/gov/usgs/earthquake/geoserve/RegionsKML.java index 4e55bb26..34953955 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/RegionsKML.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/RegionsKML.java @@ -14,6 +14,8 @@ public class RegionsKML { /** * Output ANSS Authoritative Regions in KML format. + * @param regions ANSS Authoritative regions + * @return string of ANSS regions in KML format */ public String formatKML(final Regions regions) { StringBuffer kml = new StringBuffer(String.join("\n", @@ -67,6 +69,8 @@ public String formatKML(final Regions regions) { /** * Download ANSS Authoritative Regions, * and print to console in Regions KML format. + * @param args Console arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { Regions regions = ANSSRegionsFactory.getFactory().getRegions(); diff --git a/src/main/java/gov/usgs/earthquake/geoserve/RegionsXML.java b/src/main/java/gov/usgs/earthquake/geoserve/RegionsXML.java index 677ed212..432ab1b9 100644 --- a/src/main/java/gov/usgs/earthquake/geoserve/RegionsXML.java +++ b/src/main/java/gov/usgs/earthquake/geoserve/RegionsXML.java @@ -20,6 +20,8 @@ public class RegionsXML { /** * Output ANSS Authoritative Regions in the legacy Regions XML format. + * @param regions ANSS Authoritative regions + * @return String on regions in an XML format */ public String formatXML(final Regions regions) { StringBuffer xml = new StringBuffer(String.join("\n", @@ -86,7 +88,9 @@ public String formatXML(final Regions regions) { /** * Parse regions from an XML input stream. * - * @throws Exception + * @param in input stream + * @throws Exception if error occurs + * @return Regions */ public static Regions getRegions(final InputStream in) throws Exception { RegionsHandler regionsHandler = new RegionsHandler(); @@ -100,6 +104,9 @@ public static Regions getRegions(final InputStream in) throws Exception { /** * Download ANSS Authoritative regions from Geoserve, * and print to the screen in Regions XML format. + * + * @param args console arguments + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { Regions regions = ANSSRegionsFactory.getFactory().getRegions(); diff --git a/src/main/java/gov/usgs/earthquake/indexer/ArchivePolicy.java b/src/main/java/gov/usgs/earthquake/indexer/ArchivePolicy.java index 5452c646..9f72924d 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ArchivePolicy.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ArchivePolicy.java @@ -17,13 +17,13 @@ * archived. Generally, archiving means the data for that product/event is * removed from the index as well as the storage. Upon archiving, an * EVENT_ARCHIVED type of IndexerEvent is sent to interested listeners. - * + * * All archive policies run in their own thread (one thread separate from * indexing for all archive policies, not one each) and execute at configured * intervals. - * + * * @author emartinez - * + * */ public class ArchivePolicy extends DefaultConfigurable { @@ -39,24 +39,37 @@ public class ArchivePolicy extends DefaultConfigurable { /** @deprecated */ public static final String ARCHIVE_MAX_AGE_PROPERTY = "maxAge"; + /** Property for archive minimum event age */ public static final String ARCHIVE_MIN_EVENT_AGE_PROPERTY = "minEventAge"; + /** Property for archive maximum event age */ public static final String ARCHIVE_MAX_EVENT_AGE_PROPERTY = "maxEventAge"; + /** Property for archive minimum event time */ public static final String ARCHIVE_MIN_EVENT_TIME_PROPERTY = "minEventTime"; + /** Property for archive maximum event time */ public static final String ARCHIVE_MAX_EVENT_TIME_PROPERTY = "maxEventTime"; + /** Property for archive minimum mag */ public static final String ARCHIVE_MIN_MAG_PROPERTY = "minMag"; + /** Property for archive maximum mag */ public static final String ARCHIVE_MAX_MAG_PROPERTY = "maxMag"; + /** Property for archive minimum latitude */ public static final String ARCHIVE_MIN_LAT_PROPERTY = "minLat"; + /** Property for archive maximum latitude */ public static final String ARCHIVE_MAX_LAT_PROPERTY = "maxLat"; + /** Property for archive minimum longitude */ public static final String ARCHIVE_MIN_LNG_PROPERTY = "minLng"; + /** Property for archive maximum longitude */ public static final String ARCHIVE_MAX_LNG_PROPERTY = "maxLng"; + /** Property for archive minimum depth */ public static final String ARCHIVE_MIN_DEPTH_PROPERTY = "minDepth"; + /** Property for archive maximum depth */ public static final String ARCHIVE_MAX_DEPTH_PROPERTY = "maxDepth"; + /** Property for archive event source */ public static final String ARCHIVE_EVENT_SOURCE_PROPERTY = "eventSource"; // -------------------------------------------------------------------- @@ -68,26 +81,40 @@ public class ArchivePolicy extends DefaultConfigurable { /** @deprecated */ protected Long maxAge = null; + /** Configured parameter var for minEventAge */ protected Long minEventAge = null; + /** Configured parameter var for maxEventAge */ protected Long maxEventAge = null; + /** Configured parameter var for minEventTime */ protected Long minEventTime = null; + /** Configured parameter var for maxEventTime */ protected Long maxEventTime = null; + /** Configured parameter var for minMag */ protected BigDecimal minMag = null; + /** Configured parameter var for maxMag */ protected BigDecimal maxMag = null; + /** Configured parameter var for minLat */ protected BigDecimal minLat = null; + /** Configured parameter var for maxLat */ protected BigDecimal maxLat = null; + /** Configured parameter var for minLng */ protected BigDecimal minLng = null; + /** Configured parameter var for maxLng */ protected BigDecimal maxLng = null; + /** Configured parameter var for minDepth */ protected BigDecimal minDepth = null; + /** Configured parameter var for maxDepth */ protected BigDecimal maxDepth = null; + /** Configured parameter var for eventSource */ protected String eventSource = null; + /** Default Constructor */ public ArchivePolicy() { // Default constructor } @@ -172,6 +199,7 @@ public void startup() throws Exception { // Nothing to do } + /** @return a ProductIndexQuery */ public ProductIndexQuery getIndexQuery() { ProductIndexQuery productIndexQuery = new ProductIndexQuery(); Date now = new Date(); @@ -198,9 +226,9 @@ public ProductIndexQuery getIndexQuery() { |------------------> minTime | | | |--------------------------------------> maxTime - + Simple Example (not to scale) - + 0 (Epoch) (Now) 100,000 |------------------- maxAge <--- (10,000) --------------------- | | | | @@ -211,7 +239,7 @@ Simple Example (not to scale) |----- (90,000) ---> minTime | | | |------------------------- (99,000) ---> maxTime - + Events occurring in the *** time span will match the query and be archived. */ @@ -248,12 +276,13 @@ Simple Example (not to scale) // their preferred properties productIndexQuery .setEventSearchType(ProductIndexQuery.SEARCH_EVENT_PREFERRED); - + productIndexQuery.setResultType(ProductIndexQuery.RESULT_TYPE_ALL); - + return productIndexQuery; } + /** @return boolean if the policy is valid */ public boolean isValidPolicy() { // Not valid if using both old and new configuration methods boolean valid = !((minAge != null || maxAge != null) && (minEventAge != null || maxEventAge != null)); @@ -267,6 +296,12 @@ public boolean isValidPolicy() { || maxDepth != null || eventSource != null); } + /** + * Gets the property 'name' from config and returns a BigDecimal of it + * @param config Config file + * @param name name of property from config + * @return BigDecimal of property + */ protected BigDecimal parseBigDecimal(Config config, String name) { BigDecimal property = null; try { @@ -280,6 +315,12 @@ protected BigDecimal parseBigDecimal(Config config, String name) { return property; } + /** + * Gets the property 'name' from config and returns a Date/Long of it + * @param config Config file + * @param name name of property from config + * @return Date/Long of property + */ protected Long parseDateOrLong(Config config, String name) { Long property = null; try { @@ -301,6 +342,12 @@ protected Long parseDateOrLong(Config config, String name) { return property; } + /** + * Gets the property 'name' from config and returns a Long of it + * @param config Config file + * @param name name of property from config + * @return Long of property + */ protected Long parseLong(Config config, String name) { Long property = null; try { @@ -314,126 +361,160 @@ protected Long parseLong(Config config, String name) { return property; } - /** @deprecated */ + /** @deprecated + * @return minAge + */ public Long getMinAge() { return minAge; } - /** @deprecated */ + /** @deprecated + * @param minAge to set + */ public void setMinAge(Long minAge) { this.minAge = minAge; } - /** @deprecated */ + /** @deprecated + * @return maxAge + */ public Long getMaxAge() { return maxAge; } - /** @deprecated */ + /** @deprecated + * @param maxAge to set + */ public void setMaxAge(Long maxAge) { this.maxAge = maxAge; } + /** @return minEventAge */ public Long getMinEventAge() { return minEventAge; } + /** @param minEventAge to set */ public void setMinEventAge(Long minEventAge) { this.minEventAge = minEventAge; } + /** @return maxEventAge */ public Long getMaxEventAge() { return maxEventAge; } + /** @param maxEventAge to set */ public void setMaxEventAge(Long maxEventAge) { this.maxEventAge = maxEventAge; } + /** @return minEventTime */ public Long getMinEventTime() { return minEventTime; } + /** @param minEventTime to set */ public void setMinEventTime(Long minEventTime) { this.minEventTime = minEventTime; } + /** @return maxEventTime */ public Long getMaxEventTime() { return maxEventTime; } + /** @param maxEventTime to set */ public void setMaxEventTime(Long maxEventTime) { this.maxEventTime = maxEventTime; } + /** @return minMag */ public BigDecimal getMinMag() { return minMag; } + /** @param minMag to set */ public void setMinMag(BigDecimal minMag) { this.minMag = minMag; } + /** @return maxMag */ public BigDecimal getMaxMag() { return maxMag; } + /** @param maxMag to set */ public void setMaxMag(BigDecimal maxMag) { this.maxMag = maxMag; } + /** @return minLat */ public BigDecimal getMinLat() { return minLat; } + /** @param minLat to set */ public void setMinLat(BigDecimal minLat) { this.minLat = minLat; } + /** @return maxLat */ public BigDecimal getMaxLat() { return maxLat; } + /** @param maxLat to set */ public void setMaxLat(BigDecimal maxLat) { this.maxLat = maxLat; } + /** @return minLng */ public BigDecimal getMinLng() { return minLng; } + /** @param minLng to set */ public void setMinLng(BigDecimal minLng) { this.minLng = minLng; } + /** @return maxLng */ public BigDecimal getMaxLng() { return maxLng; } + /** @param maxLng to set */ public void setMaxLng(BigDecimal maxLng) { this.maxLng = maxLng; } + /** @return minDepth */ public BigDecimal getMinDepth() { return minDepth; } + /** @param minDepth to set */ public void setMinDepth(BigDecimal minDepth) { this.minDepth = minDepth; } + /** @return maxDepth */ public BigDecimal getMaxDepth() { return maxDepth; } + /** @param maxDepth to set */ public void setMaxDepth(BigDecimal maxDepth) { this.maxDepth = maxDepth; } + /** @return eventSource */ public String getEventSource() { return eventSource; } + /** @param eventSource to set */ public void setEventSource(String eventSource) { this.eventSource = eventSource; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/Associator.java b/src/main/java/gov/usgs/earthquake/indexer/Associator.java index 0d717a4c..77f24206 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/Associator.java +++ b/src/main/java/gov/usgs/earthquake/indexer/Associator.java @@ -9,10 +9,10 @@ /** * Implement event association logic used by the indexer. - * + * * It is the associators job to describe how to find matching events, and then * choose the best matching event that was found. - * + * * The indexer uses the Associator to build a query used to search the * ProductIndex. After querying the ProductIndex, the indexer then calls the * chooseEvent method with any found events. @@ -21,7 +21,7 @@ public interface Associator { /** * Create a SearchRequest that can be used to find related events. - * + * * @param summary * the product summary being associated. * @return a SearchRequest that can be used to search the ProductIndex. @@ -31,7 +31,7 @@ public interface Associator { /** * Choose the best matching event for a product summary from a list of * events. If no events match, returns null. - * + * * @param events * a list of candidate events. * @param summary @@ -43,7 +43,7 @@ public Event chooseEvent(final List events, /** * Check if two events are associated. - * + * * @param event1 * the first event * @param event2 @@ -54,9 +54,9 @@ public Event chooseEvent(final List events, /** * Get a ProductIndexQuery that searches by eventid. - * - * @param eventSource - * @param eventCode + * + * @param eventSource relevant to event + * @param eventCode relevant to event * @return a ProductIndexQuery that searches by eventid. */ public ProductIndexQuery getEventIdQuery(final String eventSource, @@ -64,10 +64,10 @@ public ProductIndexQuery getEventIdQuery(final String eventSource, /** * Get a ProductIndexQuery that searches by location. - * - * @param time - * @param latitude - * @param longitude + * + * @param time of event + * @param latitude of event + * @param longitude of event * @return a ProductIndexQuery that searches by location. */ public ProductIndexQuery getLocationQuery(final Date time, diff --git a/src/main/java/gov/usgs/earthquake/indexer/DefaultAssociator.java b/src/main/java/gov/usgs/earthquake/indexer/DefaultAssociator.java index cc23dbd1..3a731082 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/DefaultAssociator.java +++ b/src/main/java/gov/usgs/earthquake/indexer/DefaultAssociator.java @@ -17,7 +17,7 @@ /** * Utilities for associating events. - * + * * Based on the QDM EQEventsUtils class. */ public class DefaultAssociator implements Associator { @@ -38,10 +38,10 @@ public class DefaultAssociator implements Associator { /** * Distance between related events latitude, in degrees. - * + * * This is based on the max number of kilometers per degree, and provides * the maximum latitude separation (assuming events share a longitude). - * + * * Used as a pre-filter before more expensive checks. */ public static final BigDecimal LOCATION_DIFF_DEGREES = new BigDecimal( @@ -76,7 +76,7 @@ public SearchRequest getSearchRequest(ProductSummary summary) { /** * Choose and return the most closely associated event. - * + * * @param events * a list of candidate events. * @param summary @@ -174,9 +174,9 @@ else if (filteredEvents.size() > 1) { * parameter from the product parameter, normalizing between 1 and -1, then * calculating the Euclidean distance in the 3D space composed of the * normalized lat, lon, and time vectors. - * - * @param summary - * @param events + * + * @param summary ProductSummary to compare events with + * @param events List of events * @return Event with lowest distance */ protected Event chooseMostSimilar(ProductSummary summary, List events) { @@ -242,7 +242,7 @@ protected Event chooseMostSimilar(ProductSummary summary, List events) { /** * Check if two events are associated to each other. - * + * * Reasons events may be considered disassociated: *

      *
    1. Share a common EVENTSOURCE with different EVENTSOURCECODE.
    2. @@ -250,14 +250,14 @@ protected Event chooseMostSimilar(ProductSummary summary, List events) { *
    3. Preferred location in space and time is NOT nearby, and no other * reason to associate.
    4. *
    - * + * * Reasons events may be considered associated: *
      *
    1. Share a common EVENTID
    2. *
    3. Either has an associate product for the other.
    4. *
    5. Their preferred location in space and time is nearby.
    6. *
    - * + * * @param event1 * candidate event to test. * @param event2 @@ -362,7 +362,7 @@ public boolean eventsAssociated(Event event1, Event event2) { /** * Build a ProductIndexQuery that searches based on event id. - * + * * @param eventSource * the eventSource to search * @param eventCode @@ -395,8 +395,8 @@ public ProductIndexQuery getEventIdQuery(final String eventSource, /** * Build a ProductIndexQuery that searches based on location. - * - * + * + * * @param time * the time to search around. * @param latitude @@ -468,7 +468,7 @@ public ProductIndexQuery getLocationQuery(final Date time, /** * Check if a location would be matched by a ProductIndexQuery. - * + * * @param query * location query * @param time diff --git a/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerListener.java b/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerListener.java index 30d6e72d..49b6ed09 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerListener.java +++ b/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerListener.java @@ -13,34 +13,34 @@ /** * DefaultIndexerListener provides a starting point from which all * IndexerListeners may extend. - * + * * As a child-class of the AbstractListener, this may be configured with all of * the parent parameters and also accepts the following: - * + * *
    *
    command
    *
    (Required) The command to execute. This must be an executable command and * may include arguments. Any product-specific arguments are appended at the end * of command.
    - * + * *
    storage
    *
    (Required) A directory used to store all products. Each product is * extracted into a separate directory within this directory and is referenced * by the --directory=/path/to/directory argument when command is executed.
    - * + * *
    processUnassociated
    *
    (Optional, Default = false) Whether or not to process unassociated * products. Valid values are "true" and "false".
    - * + * *
    processPreferredOnly
    *
    (Optional, Default = false) Whether or not to process only preferred * products of the type accepted by this listener. Valid values are "true" and * "false".
    - * + * *
    ignoreArchive
    *
    (Optional, Default = false) Whether or not to ignore EVENT_ARCHIVED and * PRODUCT_ARCHIVED indexer events. Value values are "true" and "false".
    - * + * *
    */ public class DefaultIndexerListener extends AbstractListener implements @@ -49,16 +49,24 @@ public class DefaultIndexerListener extends AbstractListener implements private static final Logger LOGGER = Logger .getLogger(DefaultIndexerListener.class.getName()); + /** Property for process preferred only */ public static final String PROCESS_PREFERRED_ONLY_PROPERTY = "processPreferredOnly"; + /** Default state of process preferred only */ public static final String PROCESS_PREFERRED_ONLY_DEFAULT = "false"; + /** Property for process unassociated */ public static final String PROCESS_UNASSOCIATED_PROPERTY = "processUnassociated"; + /** Default state of process unassociated */ public static final String PROCESS_UNASSOCIATED_DEFAULT = "true"; + /** Property for process only when event change */ public static final String PROCESS_ONLY_WHEN_EVENT_CHANGE_PROPERTY = "processOnlyWhenEventChanged"; + /** Default state of process only when event change */ public static final String PROCESS_ONLY_WHEN_EVENT_CHANGE_DEFAULT = "false"; + /** Property for Ignore archive */ public static final String IGNORE_ARCHIVE_PROPERTY = "ignoreArchive"; + /** Default state of ignore archive */ public static final String IGNORE_ARCHIVE_DEFAULT = "true"; /** Whether or not to process only preferred products. */ @@ -102,7 +110,7 @@ public void onIndexerEvent(IndexerEvent event) throws Exception { * @param change * the indexer event that has occurred * @return whether this external indexer listener handles this product type - * @throws Exception + * @throws Exception if error occurs */ public boolean accept(IndexerEvent change) throws Exception { String productType = null; @@ -155,6 +163,14 @@ public boolean accept(IndexerEvent change) throws Exception { return true; } + /** + * Returns a boolean based on if the preferred event params have changed + * Returns false if change is an archive indexer + * @param event an IndexerEvent + * @param change and IndexerChange + * @return boolean + * @throws Exception if error occurs + */ public boolean accept(IndexerEvent event, IndexerChange change) throws Exception { // check whether this is an archive indexer change @@ -246,28 +262,34 @@ public void setProcessOnlyPreferredProducts( this.processOnlyPreferredProducts = processOnlyPreferredProducts; } + /** @param processUnassociatedProducts to set */ public void setProcessUnassociatedProducts( final boolean processUnassociatedProducts) { this.processUnassociatedProducts = processUnassociatedProducts; } + /** @return boolean processUnassociatedProducts */ public boolean getProcessUnassociatedProducts() { return processUnassociatedProducts; } + /** @return boolean processOnlyWhenEventChanged */ public boolean isProcessOnlyWhenEventChanged() { return processOnlyWhenEventChanged; } + /** @param processOnlyWhenEventChanged to set */ public void setProcessOnlyWhenEventChanged( boolean processOnlyWhenEventChanged) { this.processOnlyWhenEventChanged = processOnlyWhenEventChanged; } + /** @return ignoreArchive */ public boolean isIgnoreArchive() { return ignoreArchive; } + /** @param ignoreArchive to set */ public void setIgnoreArchive(boolean ignoreArchive) { this.ignoreArchive = ignoreArchive; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerModule.java b/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerModule.java index 5764f0a3..6d6d2720 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerModule.java +++ b/src/main/java/gov/usgs/earthquake/indexer/DefaultIndexerModule.java @@ -30,6 +30,7 @@ public class DefaultIndexerModule extends DefaultConfigurable implements Indexer private static final Logger LOGGER = Logger.getLogger(DefaultIndexerModule.class.getName()); + /** Property for ignoreRegions */ public static final String IGNORE_REGIONS_PROPERTY = "ignoreRegions"; /** Initial preferred weight. */ @@ -100,6 +101,7 @@ public ProductSummary getProductSummary(final Product product) throws Exception * * @param summary the summary to calculate a preferred weight. * @return the absolute preferred weight. + * @throws Exception if error occurs */ protected long getPreferredWeight(final ProductSummary summary) throws Exception { long preferredWeight = DEFAULT_PREFERRED_WEIGHT; @@ -173,6 +175,7 @@ public String getBaseProductType(String type) { return type; } + /** @return ignoreRegions */ public List getIgnoreRegions() { return ignoreRegions; } @@ -187,10 +190,12 @@ public int getSupportLevel(final Product product) { return IndexerModule.LEVEL_DEFAULT; } + /** @return signatureVerifier */ public SignatureVerifier getSignatureVerifier() { return signatureVerifier; } + /** @param signatureVerifier to set */ public void setSignatureVerifier(SignatureVerifier signatureVerifier) { this.signatureVerifier = signatureVerifier; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/Event.java b/src/main/java/gov/usgs/earthquake/indexer/Event.java index e2c56168..ea38ec15 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/Event.java +++ b/src/main/java/gov/usgs/earthquake/indexer/Event.java @@ -21,17 +21,22 @@ /** * An event is a group of products that are nearby in space and time. - * + * * Which products appear in an event depend primarily on the * ProductIndexQuery.ResultType that is used when retrieving an event from the * index. Unless CURRENT is used, you may not get what you expect. */ public class Event implements Comparable { + /** Origin product type */ public static final String ORIGIN_PRODUCT_TYPE = "origin"; + /** Associate product type */ public static final String ASSOCIATE_PRODUCT_TYPE = "associate"; + /** Disassociate product type */ public static final String DISASSOCIATE_PRODUCT_TYPE = "disassociate"; + /** Property for othereventsource */ public static final String OTHEREVENTSOURCE_PROPERTY = "othereventsource"; + /** Property for othereventsourcecode */ public static final String OTHEREVENTSOURCECODE_PROPERTY = "othereventsourcecode"; /** An ID used by the ProductIndex. */ @@ -45,7 +50,7 @@ public class Event implements Comparable { /** * Default constructor. - * + * * All fields are set to null, and the list of products is empty. */ public Event() { @@ -53,7 +58,7 @@ public Event() { /** * Construct an event with only an indexId. The products map will be empty. - * + * * @param indexId * the indexId to set. */ @@ -63,7 +68,7 @@ public Event(final Long indexId) { /** * Construct and event with an indexId and a list of products. - * + * * @param indexId * the product index id. * @param products @@ -77,10 +82,10 @@ public Event(final Long indexId, /** * Copy constructor for event. - * + * * The products associated with this event are not cloned, but the list of * products is. - * + * * @param copy * the event to clone. */ @@ -90,7 +95,7 @@ public Event(final Event copy) { /** * Get the index id. - * + * * @return the indexId or null if one hasn't been assigned. */ public Long getIndexId() { @@ -99,7 +104,7 @@ public Long getIndexId() { /** * Set the index id. - * + * * @param indexId * the indexId to set. */ @@ -109,7 +114,7 @@ public void setIndexId(Long indexId) { /** * Get all products associated with event, even if they are deleted. - * + * * @return all products associated with event. */ public Map> getAllProducts() { @@ -118,11 +123,11 @@ public Map> getAllProducts() { /** * Get the event products. - * + * * Only returns products that have not been deleted or superseded. This * method returns a copy of the underlying product map that has been * filtered to remove deleted products. - * + * * @return a map of event products. * @see #getAllProducts() */ @@ -141,9 +146,9 @@ public Map> getProducts() { /** * Set products. - * + * * ProductSummaries are not cloned, but lists are. - * + * * @param newProducts * the products to set. */ @@ -161,9 +166,9 @@ public void setProducts(final Map> newProducts) { /** * A convenience method for adding a product summary to an event object. - * + * * Note: this method does not update any associated product index. - * + * * @param summary * the summary to add to this event. */ @@ -182,9 +187,9 @@ public void addProduct(final ProductSummary summary) { /** * A convenience method for removing a product summary from an event object. - * + * * Note: this method does not update any associated product index. - * + * * @param summary * the summary to remove from this event. */ @@ -205,10 +210,10 @@ public void removeProduct(final ProductSummary summary) { /** * Convenience method to get products of a given type. - * + * * This method always returns a copy of the internal list, and may be empty. * Only returns products that have not been deleted or superseded. - * + * * @param type * the product type. * @return a list of products of that type, which may be empty. @@ -227,7 +232,7 @@ public List getProducts(final String type) { /** * Get all event products (including those that are deleted or superseded). - * + * * @return a list of event products. */ public List getAllProductList() { @@ -243,7 +248,7 @@ public List getAllProductList() { /** * Get all event products that have not been deleted or superseded as a * list. - * + * * @return a list of event products. */ public List getProductList() { @@ -258,10 +263,10 @@ public List getProductList() { /** * Get preferred products of all types. - * + * * This map will contain one product of each type, chosen by preferred * weight. - * + * * @return a map from product type to the preferred product of that type. */ public Map getPreferredProducts() { @@ -280,7 +285,7 @@ public Map getPreferredProducts() { /** * Get the preferred product of a specific type. - * + * * @param type * type of product to get. * @return most preferred product of that type, or null if no product of @@ -292,9 +297,9 @@ public ProductSummary getPreferredProduct(final String type) { /** * Get a map of all event ids associated with this event. - * + * * Same as Event.getEventCodes(this.getAllProductList()); - * + * * @deprecated use {@link #getAllEventCodes(boolean)} instead. * @return map of all event ids associated with this event. */ @@ -304,9 +309,9 @@ public Map getEventCodes() { /** * Get a map of all event ids associated with this event. - * + * * Map key is eventSource, Map value is eventSourceCode. - * + * * @deprecated use {@link #getAllEventCodes(boolean)} instead. * @param summaries * the summaries list to extract event codes from. @@ -337,7 +342,7 @@ public static Map getEventCodes( * Get a map of all event ids associated with this event, recognizing that * one source may have multiple codes (they broke the rules, but it * happens). - * + * * @param includeDeleted * whether to include ids for sub events whose products have all * been deleted. @@ -385,7 +390,7 @@ public Map> getAllEventCodes( /** * Get a list of all the preferred products sorted based on their * authoritative weights - * + * * @return sorted list of ProductSummary objects */ public List getPreferredProductsSorted() { @@ -403,9 +408,9 @@ public List getPreferredProductsSorted() { /** * Get the event id. - * + * * The event id is the combination of event source and event source code. - * + * * @return the event id, or null if either event source or event source code * is null. * @see #getSource() @@ -419,10 +424,10 @@ public String getEventId() { return null; } - /* + /** * Get the preferred source for this event. If an origin product exists, * it's value is used. - * + * * @return Source from preferred product or null */ public String getSource() { @@ -433,10 +438,10 @@ public String getSource() { return null; } - /* + /** * Get the preferred source code for this event. If an origin product * exists, it's value is used. - * + * * @return Source code from preferred product or null */ public String getSourceCode() { @@ -449,9 +454,9 @@ public String getSourceCode() { /** * Get the product used for eventsource and eventsourcecode. - * + * * Event ID comes from the preferred origin product. - * + * * @return The most preferred product summary. This summary is used to * determine the eventsouce and eventsourcecode. * @see #getPreferredOriginProduct() @@ -466,7 +471,7 @@ protected ProductSummary getEventIdProduct() { /** * Get the most recent product with origin properties (id, lat, lon, time). - * + * * NOTE: this product may have been superseded by a delete. * When an event has not been deleted, this method should be consistent with * {@link #getPreferredOriginProduct()}. @@ -483,7 +488,7 @@ protected ProductSummary getEventIdProduct() { *
  • products superseded by a delete, * that have origin properties
  • * - * + * * @return the most recent product with origin properties. * @see #productHasOriginProperties(ProductSummary) */ @@ -545,7 +550,7 @@ public ProductSummary getProductWithOriginProperties() { /** * Get the most preferred origin-like product for this event. - * + * * The event is considered deleted if the returned product is null, deleted, * or does not have origin properties. Information about the event * may still be available using {@link #getProductWithOriginProperties()}. @@ -570,7 +575,7 @@ public ProductSummary getProductWithOriginProperties() { * *
  • * - * + * * @return the most recent product with origin properties. * @see #productHasOriginProperties(ProductSummary) */ @@ -640,7 +645,7 @@ public ProductSummary getPreferredOriginProduct() { /** * Check if a product can define an event (id, lat, lon, time). - * + * * @param product * product to check. * @return true if product has id, lat, lon, and time properties. @@ -656,19 +661,19 @@ public static boolean productHasOriginProperties( /** * Get the most preferred magnitude product for event. - * + * * Currently calls {@link #getPreferredOriginProduct()}. - * + * * @return the most preferred magnitude product for event. */ public ProductSummary getPreferredMagnitudeProduct() { return getPreferredOriginProduct(); } - /* + /** * Get the preferred time for this event. If an origin product exists, it's * value is used. - * + * * @return Time from preferred product or null */ public Date getTime() { @@ -679,10 +684,10 @@ public Date getTime() { return null; } - /* + /** * Get the preferred latitude for this event. If an origin product exists, * it's value is used. - * + * * @return Latitude from preferred product or null */ public BigDecimal getLatitude() { @@ -694,10 +699,10 @@ public BigDecimal getLatitude() { } - /* + /** * Get the preferred longitude for this event. If an origin product exists, * it's value is used. - * + * * @return Longitude from preferred product or null */ public BigDecimal getLongitude() { @@ -711,7 +716,7 @@ public BigDecimal getLongitude() { /** * Event update time is most recent product update time. - * + * * @return the most recent product update time. */ public Date getUpdateTime() { @@ -727,10 +732,10 @@ public Date getUpdateTime() { return updateTime; } - /* + /** * Get the preferred depth for this event. If an origin product exists, it's * value is used. - * + * * @return Depth from preferred product or null */ public BigDecimal getDepth() { @@ -741,6 +746,12 @@ public BigDecimal getDepth() { return null; } + /** + * Get the preferred magntitude for this event. If an origin product exists, it's + * value is used. + * + * @return magnitude from preferred product or null + */ public BigDecimal getMagnitude() { ProductSummary preferred = getPreferredMagnitudeProduct(); if (preferred != null) { @@ -749,11 +760,14 @@ public BigDecimal getMagnitude() { return null; } + /** + * @return boolean if the preferred event is deleted + */ public boolean isDeleted() { ProductSummary preferred = getPreferredOriginProduct(); if (preferred != null && !preferred.isDeleted() && Event.productHasOriginProperties(preferred)) { - // have "origin" type product, that isn't deleted, + // have "origin" type product, that isn't deleted, // and has origin properties return false; } @@ -763,7 +777,7 @@ public boolean isDeleted() { /** * Get the most preferred product from a list of products. - * + * * @param all * a list of products containing only one type of product. * @return the product with the highest preferred weight, and if tied the @@ -794,11 +808,11 @@ public static ProductSummary getPreferredProduct( /** * Summarize this event into preferred values. - * + * * NOTE: the event summary may include information from an origin product, * even when the preferred origin for the event has been deleted. Use * getPreferredOriginProduct() to check the preferred origin of the event. - * + * * @return an event summary. */ public EventSummary getEventSummary() { @@ -823,7 +837,7 @@ public EventSummary getEventSummary() { summary.setTime(originProduct.getEventTime()); summary.setDepth(originProduct.getEventDepth()); } - + ProductSummary magnitudeProduct = this.getPreferredMagnitudeProduct(); if (magnitudeProduct != null) { summary.setMagnitude(magnitudeProduct.getEventMagnitude()); @@ -842,7 +856,7 @@ public EventSummary getEventSummary() { /** * Comparison class that compares two ProductSummary objects based on their * preferred weight and update time. - * + * */ static class MostPreferredFirstComparator implements Comparator { @@ -892,13 +906,13 @@ public int compareTo(Event that) { /** * Find the most preferred product. - * + * * If preferredType is not null, products of this type are favored over * those not of this type. - * + * * If preferredNotNullProperty is not null, products that have this property * set are favored over those without this property set. - * + * * @param products * the list of products to search. * @param preferredType @@ -957,7 +971,7 @@ public static ProductSummary getMostPreferred( /** * Remove deleted products from the list. - * + * * @param products * list of products to filter. * @return copy of the products list with deleted products removed. @@ -979,7 +993,7 @@ public static List getWithoutDeleted( /** * Remove deleted products from the list. - * + * * @param products * list of products to filter. * @return copy of the products list with deleted products removed. @@ -1001,7 +1015,7 @@ public static List getWithEventId( /** * Remove old versions of products from the list. - * + * * @param products * list of products to filter. * @return a copy of the products list with products of the same @@ -1040,7 +1054,7 @@ public static List getWithoutSuperseded( /** * Sort a list of products, most preferred first. - * + * * @param products * the list of products to sort. * @return a copy of the list sorted with most preferred first. @@ -1086,16 +1100,16 @@ static Map> productListToTypeMap( /** * Return a list of sub-events that make up this event. - * + * * Event lines are drawn by eventid. Products that have no eventid are * included with the sub event whose id is considered preferred. - * + * * @return map from eventid to event object with products for that eventid. */ public Map getSubEvents() { // Map of sub-events keyed by product "eventId" Map subEvents = new HashMap(); - + // Map of events by source_type_code Map productEvents = new HashMap(); @@ -1151,7 +1165,7 @@ public Map getSubEvents() { /** * Check if this event has an associate product for another given Event. - * + * * @param otherEvent * the other event. * @return true if there is an associate product, false otherwise. @@ -1190,7 +1204,7 @@ public boolean hasAssociateProduct(final Event otherEvent) { /** * Check if this event has an disassociate product for another given Event. - * + * * @param otherEvent * the other event. * @return true if there is an disassociate product, false otherwise. @@ -1229,6 +1243,8 @@ public boolean hasDisassociateProduct(final Event otherEvent) { /** * Same as isAssociated(that, new DefaultAssociator()); + * @param that an event to test + * @return boolean true if associated, false otherwise */ public boolean isAssociated(final Event that) { return this.isAssociated(that, new DefaultAssociator()); @@ -1236,7 +1252,7 @@ public boolean isAssociated(final Event that) { /** * Check if an event is associated to this event. - * + * * Reasons events may be considered disassociated: *
      *
    1. Share a common EVENTSOURCE with different EVENTSOURCECODE.
    2. @@ -1244,22 +1260,28 @@ public boolean isAssociated(final Event that) { *
    3. Preferred location in space and time is NOT nearby, and no other * reason to associate.
    4. *
    - * + * * Reasons events may be considered associated: *
      *
    1. Share a common EVENTID
    2. *
    3. Either has an associate product for the other.
    4. *
    5. Their preferred location in space and time is nearby.
    6. *
    - * + * * @param that * candidate event to test. + * @param associator + * An associator to compare two events * @return true if associated, false otherwise. */ public boolean isAssociated(final Event that, final Associator associator) { return associator.eventsAssociated(this, that); } + /** + * Depending on logger level, takes in summary data and appends to buffer + * @param logger logger object + */ public void log(final Logger logger) { if (logger.isLoggable(Level.FINE)) { EventSummary summary = this.getEventSummary(); diff --git a/src/main/java/gov/usgs/earthquake/indexer/EventDetailQuery.java b/src/main/java/gov/usgs/earthquake/indexer/EventDetailQuery.java index 61593ee6..eb6ebb81 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/EventDetailQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/EventDetailQuery.java @@ -10,6 +10,10 @@ public class EventDetailQuery extends SearchQuery { private List result; + /** + * Constructor. Takes in a single ProductIndexQuery + * @param query ProductIndexQuery + */ public EventDetailQuery(final ProductIndexQuery query) { super(SearchMethod.EVENT_DETAIL, query); } @@ -19,6 +23,7 @@ public List getResult() { return result; } + /** @param event list of events to set as result */ public void setResult(final List event) { this.result = event; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/EventSummary.java b/src/main/java/gov/usgs/earthquake/indexer/EventSummary.java index 66c3e9bb..fe059534 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/EventSummary.java +++ b/src/main/java/gov/usgs/earthquake/indexer/EventSummary.java @@ -35,14 +35,20 @@ public class EventSummary implements Comparable { public EventSummary() { } + /** @param indexId to set */ public void setIndexId(Long indexId) { this.indexId = indexId; } + /** @return indexID */ public Long getIndexId() { return indexId; } + /** + * Combines source + source code for ID or returns null + * @return Id or null + */ public String getId() { if (source != null && sourceCode != null) { return source + sourceCode; @@ -50,66 +56,82 @@ public String getId() { return null; } + /** @return source */ public String getSource() { return source; } + /** @param source to set */ public void setSource(String source) { this.source = source; } + /** @return sourceCode */ public String getSourceCode() { return sourceCode; } + /** @param sourceCode to set */ public void setSourceCode(String sourceCode) { this.sourceCode = sourceCode; } + /** @return time */ public Date getTime() { return time; } + /** @param time to set */ public void setTime(Date time) { this.time = time; } + /** @return latitude */ public BigDecimal getLatitude() { return latitude; } + /** @param latitude to set */ public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } + /** @return longitude */ public BigDecimal getLongitude() { return longitude; } + /** @param longitude to set */ public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } + /** @return depth */ public BigDecimal getDepth() { return depth; } + /** @param depth to set */ public void setDepth(BigDecimal depth) { this.depth = depth; } + /** @return magnitude */ public BigDecimal getMagnitude() { return magnitude; } + /** @param magnitude to set */ public void setMagnitude(BigDecimal magnitude) { this.magnitude = magnitude; } + /** @param deleted to set */ public void setDeleted(final boolean deleted) { this.deleted = deleted; } + /** @return deleted */ public boolean isDeleted() { return deleted; } @@ -117,7 +139,7 @@ public boolean isDeleted() { /** * These properties are derived from product properties, and are those * desirable for searching at an event level. - * + * * @return The properties of this event. */ public Map getProperties() { @@ -125,7 +147,7 @@ public Map getProperties() { } /** - * + * * @return A map of event codes associated with this event. */ public Map getEventCodes() { diff --git a/src/main/java/gov/usgs/earthquake/indexer/EventsSummaryQuery.java b/src/main/java/gov/usgs/earthquake/indexer/EventsSummaryQuery.java index 1eba3d09..75f35e76 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/EventsSummaryQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/EventsSummaryQuery.java @@ -12,8 +12,8 @@ public class EventsSummaryQuery extends SearchQuery { /** * Construct an EventsSummaryQuery. - * - * @param query + * + * @param query ProductIndexQuery */ public EventsSummaryQuery(final ProductIndexQuery query) { super(SearchMethod.EVENTS_SUMMARY, query); @@ -24,6 +24,7 @@ public List getResult() { return result; } + /** @param events list of EventSummarys to set as result */ public void setResult(List events) { this.result = events; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/ExtentIndex.java b/src/main/java/gov/usgs/earthquake/indexer/ExtentIndex.java index 0c4459a5..f097f5a5 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ExtentIndex.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ExtentIndex.java @@ -14,15 +14,27 @@ */ public class ExtentIndex extends JDBCProductIndex { + /** Table for extentSummary */ public static final String EXTENT_TABLE = "extentSummary"; + /** Extent index id - productSummaryIndexId */ public static final String EXTENT_INDEX_ID = "productSummaryIndexId"; + /** Extent start time */ public static final String EXTENT_START_TIME = "starttime"; + /** Extent end time */ public static final String EXTENT_END_TIME = "endtime"; + /** Extent max latitude */ public static final String EXTENT_MAX_LAT = "maximum_latitude"; + /** Extent minimum latitude */ public static final String EXTENT_MIN_LAT = "minimum_latitude"; + /** Extent max longitude */ public static final String EXTENT_MAX_LONG = "maximum_longitude"; + /** Extent min longitude */ public static final String EXTENT_MIN_LONG = "minimum_longitude"; + /** + * Default constructor + * @throws Exception if error occurs + */ public ExtentIndex() throws Exception { super(); } @@ -30,6 +42,7 @@ public ExtentIndex() throws Exception { /** * Queries extentSummary table for the largest index id. * + * @return long last extent index id * @throws Exception if something goes wrong with database transaction */ public long getLastExtentIndexId() throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/indexer/ExtentSummary.java b/src/main/java/gov/usgs/earthquake/indexer/ExtentSummary.java index ac0e67d3..3607403f 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ExtentSummary.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ExtentSummary.java @@ -21,14 +21,21 @@ public class ExtentSummary { private BigDecimal maxLongitude; private BigDecimal minLongitude; + /** Property for Extent Start time */ public static final String EXTENT_START_TIME_PROPERTY = "starttime"; + /** Property for Extent End Time */ public static final String EXTENT_END_TIME_PROPERTY = "endtime"; + /** Property for Extent Max Lat */ public static final String EXTENT_MAX_LAT_PROPERTY = "maximum-latitude"; + /** Property for Extent Min lat */ public static final String EXTENT_MIN_LAT_PROPERTY = "minimum-latitude"; + /** Property for Extent Max Long */ public static final String EXTENT_MAX_LONG_PROPERTY = "maximum-longitude"; + /** Property for Extent Min Long */ public static final String EXTENT_MIN_LONG_PROPERTY = "minimum-longitude"; + /** Empty constructor */ public ExtentSummary() { //Do nothing; this is if member vars are to be set manually } @@ -36,7 +43,7 @@ public ExtentSummary() { /** * Builds an extentSummary from product properties. If the product has none of * the properties, the ExtentSummary is still built. - * + * * @param product the productSummary to build from */ public ExtentSummary(ProductSummary product) { @@ -67,64 +74,86 @@ public ExtentSummary(ProductSummary product) { /** * Returns TRUE if this extent should be put in the extentSummary table (at * least one property is not null) + * @return boolean */ public boolean isValid() { - return - startTime != null || - endTime != null || - maxLatitude != null || - maxLongitude != null || - minLatitude != null || + return + startTime != null || + endTime != null || + maxLatitude != null || + maxLongitude != null || + minLatitude != null || minLongitude != null; } + /** @return index Id */ public Long getIndexId() { return this.id; } + + /** @param id indexId to set */ public void setIndexId(Long id) { this.id = id; } + /** @return startTime */ public Date getStartTime() { return this.startTime; } + + /** @param startTime date to set */ public void setStartTime(Date startTime) { this.startTime = startTime; } - + + /** @return endTime */ public Date getEndTime() { return this.endTime; } + + /** @param endTime date to set */ public void setEndTime(Date endTime) { this.endTime = endTime; } + /** @return maxLatitude */ public BigDecimal getMaxLatitude() { return this.maxLatitude; } + + /** @param maxLatitude BigDecimal to set */ public void setMaxLatitude(BigDecimal maxLatitude) { this.maxLatitude = maxLatitude; } + /** @return minLatitude */ public BigDecimal getMinLatitude() { return this.minLatitude; } + + /** @param minLatitude BigDecimal to set */ public void setMinLatitude(BigDecimal minLatitude) { this.minLatitude = minLatitude; } + /** @return maxLongitude */ public BigDecimal getMaxLongitude() { return this.maxLongitude; } + + /** @param maxLongitude BigDecimal to set */ public void setMaxLongitude(BigDecimal maxLongitude) { this.maxLongitude = maxLongitude; } + /** @return minLongitude */ public BigDecimal getMinLongitude() { return this.minLongitude; } + + /** @param minLongitude to set */ public void setMinLongitude(BigDecimal minLongitude) { this.minLongitude = minLongitude; } -} \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/java/gov/usgs/earthquake/indexer/ExternalIndexerListener.java b/src/main/java/gov/usgs/earthquake/indexer/ExternalIndexerListener.java index 97dd719d..81243dbf 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ExternalIndexerListener.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ExternalIndexerListener.java @@ -69,16 +69,26 @@ public class ExternalIndexerListener extends DefaultIndexerListener { private static final Logger LOGGER = Logger .getLogger(ExternalIndexerListener.class.getName()); + /** Argument for event action */ public static final String EVENT_ACTION_ARGUMENT = "--action="; + /** Argument for event ids */ public static final String EVENT_IDS_ARGUMENT = "--eventids="; + /** Argument for preferred event id */ public static final String PREFERRED_ID_ARGUMENT = "--preferred-eventid="; + /** Argument for preferred eventsource */ public static final String PREFERRED_EVENTSOURCE_ARGUMENT = "--preferred-eventsource="; + /** Argument for preferred eventsourcecode */ public static final String PREFERRED_EVENTSOURCECODE_ARGUMENT = "--preferred-eventsourcecode="; + /** Argument for preferred magnitude */ public static final String PREFERRED_MAGNITUDE_ARGUMENT = "--preferred-magnitude="; + /** Argument for preferred longitude */ public static final String PREFERRED_LONGITUDE_ARGUMENT = "--preferred-longitude="; + /** Argument for preferred latitude */ public static final String PREFERRED_LATITUDE_ARGUMENT = "--preferred-latitude="; + /** Argument for preferred depth */ public static final String PREFERRED_DEPTH_ARGUMENT = "--preferred-depth="; + /** Argument for preferred eventitme */ public static final String PREFERRED_ORIGIN_TIME_ARGUMENT = "--preferred-eventtime="; /** Configuration parameter for storage directory product. */ public static final String STORAGE_NAME_PROPERTY = "storage"; @@ -91,6 +101,7 @@ public class ExternalIndexerListener extends DefaultIndexerListener { /** Configuration parameter for autoArchive. */ public static final String AUTO_ARCHIVE_PROPERTY = "autoArchive"; + /** Default state for auto archive */ public static final String AUTO_ARCHIVE_DEFAULT = "true"; /** Argument used to pass signature to external process. */ @@ -186,7 +197,7 @@ public void onIndexerEvent(IndexerEvent change) throws Exception { * * @param product product to be stored. * @return a new product object, read from the listener storage. - * @throws Exception + * @throws Exception if error occurs */ public Product storeProduct(final Product product) throws Exception { Product listenerProduct = null; @@ -213,7 +224,7 @@ public Product storeProduct(final Product product) throws Exception { * @param command command and arguments. * @param product product, when set and empty content (path "") is defined, * the content is provided to the command on stdin. - * @throws Exception + * @throws Exception if error occurs */ public void runProductCommand(final String command, final Product product) throws Exception { // execute @@ -278,8 +289,10 @@ public void run() { * * @param change * The IndexerEvent received by the ExternalIndexerListener + * @param indexerChange + * The IndexerChange * @return the command to execute with its arguments as a string - * @throws Exception + * @throws Exception if error occurs */ public String getProductSummaryCommand(IndexerEvent change, IndexerChange indexerChange) throws Exception { @@ -304,10 +317,10 @@ public String getProductSummaryCommand(IndexerEvent change, /** * Get the command for a specific event and summary. * - * @param event - * @param summary + * @param event Specific event + * @param summary Specific product summary * @return command line arguments as a string. - * @throws Exception + * @throws Exception if error occurs */ public String getProductSummaryCommand(Event event, ProductSummary summary) throws Exception { StringBuffer indexerCommand = new StringBuffer(getCommand()); @@ -410,6 +423,7 @@ public String getEventArguments(final Event event) { * * @param summary the product summary * @return command line arguments + * @throws IOException if IO error occurs */ public String getProductSummaryArguments(final ProductSummary summary) throws IOException { StringBuffer buf = new StringBuffer(); diff --git a/src/main/java/gov/usgs/earthquake/indexer/ExternalPreferredListener.java b/src/main/java/gov/usgs/earthquake/indexer/ExternalPreferredListener.java index 288a46ff..8d9a7e0b 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ExternalPreferredListener.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ExternalPreferredListener.java @@ -7,20 +7,24 @@ /** * (Experimental) Notify external processes when preferred product change within events. - * + * * @author jmfee * */ public class ExternalPreferredListener extends ExternalIndexerListener { + /** Argument for Preferred action */ public static final String PREFERRED_ACTION_ARGUMENT = "--preferred-action="; /** * Types of preferred product actions. */ public static enum PreferredAction { + /** Preferred added product enum */ PREFERRED_ADDED, + /** Preferred changed product enum */ PREFERRED_CHANGED, + /** Preferred removed product enum */ PREFERRED_REMOVED }; @@ -85,7 +89,7 @@ public void onIndexerEvent(final IndexerEvent event) throws Exception { /** * Compare preferred products before/after IndexerChange was applied. - * + * * @param change indexer change to evaluate. * @return map of preferred products that were changed. */ @@ -101,7 +105,7 @@ public static Map getIndexerChangePreferredActi changeType != IndexerChange.EVENT_UPDATED) { return changes; } - + Map newProducts = getPreferredProducts(change.getNewEvent()); Map originalProducts = getPreferredProducts(change.getOriginalEvent()); @@ -109,7 +113,7 @@ public static Map getIndexerChangePreferredActi for (String type : newProducts.keySet()) { ProductSummary newProduct = newProducts.get(type); ProductSummary originalProduct = originalProducts.get(type); - + if (originalProduct == null) { // no product of this type previously existed changes.put(newProduct, @@ -120,7 +124,7 @@ public static Map getIndexerChangePreferredActi PreferredAction.PREFERRED_CHANGED); } } - + for (String type : originalProducts.keySet()) { if (newProducts.get(type) == null) { // no product of this type exists anymore @@ -128,7 +132,7 @@ public static Map getIndexerChangePreferredActi PreferredAction.PREFERRED_REMOVED); } } - + return changes; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/Indexer.java b/src/main/java/gov/usgs/earthquake/indexer/Indexer.java index 3c4befb9..152d597e 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/Indexer.java +++ b/src/main/java/gov/usgs/earthquake/indexer/Indexer.java @@ -67,15 +67,16 @@ public class Indexer extends DefaultNotificationListener { /** Preferred weight for persistent trump. */ public static final long TRUMP_PREFERRED_WEIGHT = 100000000; - + /** Type for persistent trimp */ public static final String TRUMP_PRODUCT_TYPE = "trump"; + /** Prefix for persistent trump */ public static final String PERSISTENT_TRUMP_PREFIX = "trump-"; /** Property name to configure a custom associator. */ public static final String ASSOCIATOR_CONFIG_PROPERTY = "associator"; - + /** Property to associate using current products */ public static final String ASSOCIATE_USING_CURRENT_PRODUCTS_PROPERTY = "associateUsingCurrentProducts"; - + /** Default state for associate using current products */ public static final String DEFAULT_ASSOCIATE_USING_CURRENT_PRODUCTS = "false"; /** Property name to configure a custom storage. */ @@ -158,7 +159,9 @@ public class Indexer extends DefaultNotificationListener { private boolean disableArchive = false; // -- Configurable property names -- // + /** Configurable property for index archive internal */ public static final String INDEX_ARCHIVE_INTERVAL_PROPERTY = "archiveInterval"; + /** Configurable property for index archive policy */ public static final String INDEX_ARCHIVE_POLICY_PROPERTY = "archivePolicy"; // -- Default configurable property values -- // @@ -412,7 +415,7 @@ protected synchronized void notifyListeners(final IndexerEvent event) { * NOT synchronized to allow multiple threads to access. * readProductIndex.hasProduct is synchronized. * - * @param id + * @param id ProductId to check * @return true if product has already been indexed. */ protected boolean hasProductBeenIndexed(final ProductId id) { @@ -525,7 +528,7 @@ public void onProduct(final Product product) throws Exception { * @param force * Whether to reprocess products that have already been processed * (true), or skip (false). - * @throws Exception + * @throws Exception if error occurs */ public void onProduct(final Product product, final boolean force) throws Exception { ProductId id = product.getId(); @@ -568,6 +571,13 @@ public void onProduct(final Product product, final boolean force) throws Excepti } } + /** + * Stores a product + * @param product Product to store + * @param force if should skip already indexed check + * @return Product if stored, null if not + * @throws Exception if error occurs + */ public Product storeProduct(final Product product, final boolean force) throws Exception { final ProductId id = product.getId(); final long beginStore = new Date().getTime(); @@ -600,6 +610,9 @@ public Product storeProduct(final Product product, final boolean force) throws E /** * Use modules to summarize product. + * @param product To summarize + * @return A product summary + * @throws Exception if error occurs */ public ProductSummary summarizeProduct(final Product product) throws Exception { // Find best available indexer module @@ -609,6 +622,9 @@ public ProductSummary summarizeProduct(final Product product) throws Exception { /** * Add product summary to product index. + * @param productSummary to add + * @return Summary added to index + * @throws Exception if error occurs */ protected synchronized ProductSummary indexProduct( ProductSummary productSummary) throws Exception { @@ -1067,7 +1083,7 @@ protected ProductId getTrumpedProductId(final ProductSummary trumpSummary) { * @param id * id to find. * @return matching product summary or null. - * @throws Exception + * @throws Exception if error occurs */ protected ProductSummary getProductSummaryById(final ProductId id) throws Exception { @@ -1090,7 +1106,7 @@ protected ProductSummary getProductSummaryById(final ProductId id) * @param preferredWeight * the weight to set. * @return event with updated summary. - * @throws Exception + * @throws Exception if error occurs */ protected Event setSummaryWeight(Event event, ProductSummary summary, final Long preferredWeight) throws Exception { @@ -1124,7 +1140,7 @@ protected Event setSummaryWeight(Event event, ProductSummary summary, * @param summary * the summary. * @return event with updated summary. - * @throws Exception + * @throws Exception if error occurs */ protected Event resummarizeProduct(final Event event, final ProductSummary summary) throws Exception { @@ -1161,7 +1177,7 @@ protected Event resummarizeProduct(final Event event, * @param updatedEvent * the event after the indexer made any changes. * @return List of changes made during this method. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List checkForEventSplits( final ProductSummary summary, final Event originalEvent, @@ -1282,7 +1298,7 @@ protected synchronized List checkForEventSplits( * The event (with products) that will be removed from the root * @return copy of root without the products that have been removed. The * indexId property of leaf is updated to its new value. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized Event splitEvents(final Event root, final Event leaf) throws Exception { @@ -1319,7 +1335,8 @@ protected synchronized Event splitEvents(final Event root, final Event leaf) * The target event into which the child is merged. * @param child * The child event to be merged into the target. - * @throws Exception + * @return the updated event + * @throws Exception if error occurs */ protected synchronized Event mergeEvents(final Event target, final Event child) throws Exception { @@ -1352,7 +1369,7 @@ protected synchronized Event mergeEvents(final Event target, * @param updatedEvent * the event after the summary was associated. * @return list of any merge type changes. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized List checkForEventMerges( final ProductSummary summary, final Event originalEvent, @@ -1497,6 +1514,12 @@ protected synchronized List checkForEventMerges( return changes; } + /** + * Takes a summary return the previous + * @param summary A product summary + * @return The previous summary + * @throws Exception if error occurs + */ protected synchronized ProductSummary getPrevProductVersion( ProductSummary summary) throws Exception { ProductSummary prevSummary = null; @@ -1535,10 +1558,10 @@ protected synchronized ProductSummary getPrevProductVersion( * @see Associator#getSearchRequest(ProductSummary) * @see Associator#chooseEvent(List, ProductSummary) * - * @param summary + * @param summary ProductSummary * @return Event to which a productSummary is associated, or null if not * found. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized Event getPrevEvent(ProductSummary summary) throws Exception { @@ -1551,7 +1574,7 @@ protected synchronized Event getPrevEvent(ProductSummary summary) * @param summary the previous event. * @param associating whether associating (vs archiving). * @return previous event, or null if none found. - * @throws Exception + * @throws Exception if error occurs */ protected synchronized Event getPrevEvent(ProductSummary summary, boolean associating) throws Exception { @@ -1967,6 +1990,8 @@ public void run() { * the index. * * @see #archivePolicies + * @return Int array of size 2 + * @throws Exception if error occurs */ public synchronized int[] purgeExpiredProducts() throws Exception { int[] counts = { 0, 0 }; @@ -2089,7 +2114,7 @@ public synchronized int[] purgeExpiredProducts() throws Exception { /** * Removes the given event from the Indexer ProductIndex and ProductStorage. * - * @param event + * @param event event to remove * @throws Exception * If errors occur while removing the event */ @@ -2114,7 +2139,7 @@ protected synchronized void removeEvent(Event event) throws Exception { * Removes the given summary from the Indexer ProductIndex and * ProductStorage. * - * @param summary + * @param summary to remove * @throws Exception * If errors occur while removing the summary */ @@ -2186,7 +2211,7 @@ private synchronized Event createEvent(ProductSummary summary) * @param request * the search request. * @return the search response. - * @throws Exception + * @throws Exception if error occurs */ public synchronized SearchResponse search(SearchRequest request) throws Exception { @@ -2242,10 +2267,12 @@ else if (query instanceof ProductDetailQuery) { return response; } + /** @return disableArchive */ public boolean isDisableArchive() { return disableArchive; } + /** @param disableArchive boolean to set */ public void setDisableArchive(boolean disableArchive) { this.disableArchive = disableArchive; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/IndexerChange.java b/src/main/java/gov/usgs/earthquake/indexer/IndexerChange.java index fdd6dd37..f84946d4 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/IndexerChange.java +++ b/src/main/java/gov/usgs/earthquake/indexer/IndexerChange.java @@ -2,7 +2,7 @@ /** * Description of a specific change to a {@link ProductIndex}. - * + * * Multiple IndexerChange objects may be created, and grouped * into an {@link IndexerEvent}, in response to one product * being processed. @@ -11,21 +11,48 @@ public class IndexerChange { /** Enumeration of indexer event types. */ public static enum IndexerChangeType { - EVENT_ADDED, EVENT_UPDATED, EVENT_DELETED, EVENT_ARCHIVED, EVENT_MERGED, EVENT_SPLIT, + /** Enum for IndexerChangeType Event Added */ + EVENT_ADDED, + /** Enum for IndexerChangeType Event Updated */ + EVENT_UPDATED, + /** Enum for IndexerChangeType Event Deleted */ + EVENT_DELETED, + /** Enum for IndexerChangeType Event Archived */ + EVENT_ARCHIVED, + /** Enum for IndexerChangeType Event Merged */ + EVENT_MERGED, + /** Enum for IndexerChangeType Event Split */ + EVENT_SPLIT, - PRODUCT_ADDED, PRODUCT_UPDATED, PRODUCT_DELETED, PRODUCT_ARCHIVED + /** Enum for IndexerChangeType Product Added */ + PRODUCT_ADDED, + /** Enum for IndexerChangeType Product Updated */ + PRODUCT_UPDATED, + /** Enum for IndexerChangeType Product Deleted */ + PRODUCT_DELETED, + /** Enum for IndexerChangeType Product Archived */ + PRODUCT_ARCHIVED }; - + /** IndexerChangeType for Event Added */ public static final IndexerChangeType EVENT_ADDED = IndexerChangeType.EVENT_ADDED; + /** IndexerChangeType for Event Updated */ public static final IndexerChangeType EVENT_UPDATED = IndexerChangeType.EVENT_UPDATED; + /** IndexerChangeType for Event Deleted */ public static final IndexerChangeType EVENT_DELETED = IndexerChangeType.EVENT_DELETED; + /** IndexerChangeType for Event Archived */ public static final IndexerChangeType EVENT_ARCHIVED = IndexerChangeType.EVENT_ARCHIVED; + /** IndexerChangeType for Event Merged */ public static final IndexerChangeType EVENT_MERGED = IndexerChangeType.EVENT_MERGED; + /** IndexerChangeType for Event Split */ public static final IndexerChangeType EVENT_SPLIT = IndexerChangeType.EVENT_SPLIT; + /** IndexerChangeType for Product Added */ public static final IndexerChangeType PRODUCT_ADDED = IndexerChangeType.PRODUCT_ADDED; + /** IndexerChangeType for Product Updated */ public static final IndexerChangeType PRODUCT_UPDATED = IndexerChangeType.PRODUCT_UPDATED; + /** IndexerChangeType for Product Deleted */ public static final IndexerChangeType PRODUCT_DELETED = IndexerChangeType.PRODUCT_DELETED; + /** IndexerChangeType for Product Archived */ public static final IndexerChangeType PRODUCT_ARCHIVED = IndexerChangeType.PRODUCT_ARCHIVED; /** Indicates the type of change that is occurring */ @@ -41,7 +68,7 @@ public static enum IndexerChangeType { * Note the oldEvent and newEvent will have * particular meanings depending on the given type of change * that occurred. - * + * * @param type * The type of change that occurred. * @param originalEvent @@ -57,14 +84,17 @@ public IndexerChange(IndexerChangeType type, Event originalEvent, this.newEvent = newEvent; } + /** @return IndexerChangeType */ public IndexerChangeType getType() { return this.type; } + /** @return originalEvent */ public Event getOriginalEvent() { return this.originalEvent; } + /** @return newEvent */ public Event getNewEvent() { return this.newEvent; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/IndexerEvent.java b/src/main/java/gov/usgs/earthquake/indexer/IndexerEvent.java index 00a137b2..ad57daf2 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/IndexerEvent.java +++ b/src/main/java/gov/usgs/earthquake/indexer/IndexerEvent.java @@ -15,7 +15,7 @@ /** * A description of a change to a ProductIndex. - * + * * IndexerEvents are created by the Indexer, and sent to IndexerListeners. */ public class IndexerEvent extends EventObject { @@ -38,7 +38,7 @@ public class IndexerEvent extends EventObject { /** * Construct a new IndexerEvent. - * + * * @param source * the indexer that made the change. */ @@ -48,32 +48,39 @@ public IndexerEvent(final Indexer source) { this.indexerChanges = new Vector(5, 5); } + /** @return Indexer */ public Indexer getIndexer() { return (Indexer) getSource(); } + /** @return Product Index */ public ProductIndex getIndex() { return this.index; } + /** @param index to set */ public void setIndex(ProductIndex index) { this.index = index; } + /** @return product summary */ public ProductSummary getSummary() { return this.summary; } + /** @param summary to add */ public void setSummary(ProductSummary summary) { this.summary = summary; } + /** @param change to add */ public void addIndexerChange(IndexerChange change) { if (change != null) { this.indexerChanges.add(change); } } + /** @param changes list of changes to add */ public void addIndexerChanges(List changes) { if (changes == null) { return; @@ -85,15 +92,16 @@ public void addIndexerChanges(List changes) { } } + /** @return vector of Indexer Changes */ public Vector getIndexerChanges() { return this.indexerChanges; } /** * Convenience method to retrieve Product from Indexer storage. - * + * * @return Product object corresponding to ProductSummary. - * @throws Exception + * @throws Exception if error occurs */ public Product getProduct() throws Exception { if (summary == null) { @@ -105,7 +113,7 @@ public Product getProduct() throws Exception { /** * Retrieve a distinct list of events that were changed as part of this * IndexerEvent. - * + * * @return list of events */ public List getEvents() { diff --git a/src/main/java/gov/usgs/earthquake/indexer/IndexerListener.java b/src/main/java/gov/usgs/earthquake/indexer/IndexerListener.java index 2bb34232..105359f3 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/IndexerListener.java +++ b/src/main/java/gov/usgs/earthquake/indexer/IndexerListener.java @@ -13,9 +13,11 @@ public interface IndexerListener extends Configurable { /** * This method is called when the indexer makes a change to the * ProductIndex. - * + * * @param change * description of the change. + * @throws Exception + * if error occurs */ public void onIndexerEvent(final IndexerEvent change) throws Exception; @@ -23,7 +25,7 @@ public interface IndexerListener extends Configurable { * An indexer that generates a IndexerEvent will attempt to deliver the * event at most this many times, if the listener throws an Exception while * processing. - * + * * @return A value of less than one means never attempt to deliver. */ public int getMaxTries(); @@ -31,7 +33,7 @@ public interface IndexerListener extends Configurable { /** * A IndexerListener has this many milliseconds to process an event before * being interrupted. - * + * * @return number of milliseconds before timing out. A value of 0 or less * means never time out. */ diff --git a/src/main/java/gov/usgs/earthquake/indexer/IndexerListenerCallable.java b/src/main/java/gov/usgs/earthquake/indexer/IndexerListenerCallable.java index 1a343e77..4f4d71d2 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/IndexerListenerCallable.java +++ b/src/main/java/gov/usgs/earthquake/indexer/IndexerListenerCallable.java @@ -11,6 +11,7 @@ */ public class IndexerListenerCallable implements Callable { + /** Logger object */ public static final Logger LOGGER = Logger .getLogger(IndexerListenerCallable.class.getName()); @@ -19,7 +20,7 @@ public class IndexerListenerCallable implements Callable { /** * Get a callable object for deferred listener notification. - * + * * @param listener * the listener to notify * @param event diff --git a/src/main/java/gov/usgs/earthquake/indexer/IndexerModule.java b/src/main/java/gov/usgs/earthquake/indexer/IndexerModule.java index c1e305bf..f6fb651e 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/IndexerModule.java +++ b/src/main/java/gov/usgs/earthquake/indexer/IndexerModule.java @@ -21,11 +21,12 @@ public interface IndexerModule { /** * Determine the support level for a given product. - * + * * The Indexer uses this method to determine which module will be used to * summarize a product as it is being processed. Usually, returning one of * the LEVEL_ constants will be sufficient. - * + * + * @param product The product to get the support level at * @return the support level. Should be greater than 0 if a product is * supported, larger values indicate better support. */ @@ -33,11 +34,11 @@ public interface IndexerModule { /** * Summarize a product. - * + * * @param product * the product to summarize * @return the ProductSummary - * @throws Exception + * @throws Exception if error occurs */ public ProductSummary getProductSummary(final Product product) throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/indexer/JDBCProductIndex.java b/src/main/java/gov/usgs/earthquake/indexer/JDBCProductIndex.java index 71a7adff..08406551 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/JDBCProductIndex.java +++ b/src/main/java/gov/usgs/earthquake/indexer/JDBCProductIndex.java @@ -86,6 +86,7 @@ public class JDBCProductIndex extends JDBCConnection implements ProductIndex { private static final String SUMMARY_TABLE = "productSummary"; private static final String SUMMARY_TABLE_ALIAS = "p"; // private static final String SUMMARY_CREATED = "created"; + /** Public var for summary product index IDs */ public static final String SUMMARY_PRODUCT_INDEX_ID = "id"; private static final String SUMMARY_PRODUCT_ID = "productId"; // private static final String SUMMARY_EVENT_ID = "eventId"; @@ -118,7 +119,7 @@ public class JDBCProductIndex extends JDBCConnection implements ProductIndex { /** * Constructor. Sets index_file to the default value JDBC_DEFAULT_FILE * - * @throws Exception + * @throws Exception if error occurs */ public JDBCProductIndex() throws Exception { // Default index file, so calling configure() isn't required @@ -126,6 +127,11 @@ public JDBCProductIndex() throws Exception { setDriver(JDBC_DEFAULT_DRIVER); } + /** + * Constructor. Uses custom index_file + * @param sqliteFileName String for sqlite file name + * @throws Exception if error occurs + */ public JDBCProductIndex(final String sqliteFileName) throws Exception { index_file = sqliteFileName; setDriver(JDBC_DEFAULT_DRIVER); @@ -156,7 +162,7 @@ public void configure(Config config) throws Exception { * Return a connection to the database. * * @return Connection object - * @throws Exception + * @throws Exception if error occurs */ @Override public Connection connect() throws Exception { @@ -417,6 +423,10 @@ public synchronized List getProducts(ProductIndexQuery query) * @param loadDetails * whether to call {@link #loadProductSummaries(List)}, * which loads links and properties with additional queries. + * @return + * A list of loaded product summaries + * @throws Exception + * if error occurs */ public synchronized List getProducts(ProductIndexQuery query, final boolean loadDetails) throws Exception { @@ -480,7 +490,7 @@ public synchronized boolean hasProduct(final ProductId id) throws Exception { * ProductSummary object to store. Must not be null. * @return Copy of the product summary object with the indexId set to the * newly inserted id. - * @throws Exception + * @throws Exception if error occurs */ @Override public synchronized ProductSummary addProductSummary(ProductSummary summary) @@ -606,8 +616,8 @@ public synchronized ProductId removeProductSummary(ProductSummary summary) * assumes that both the event and the product are already stored in their * respective tables. * - * @param event - * @param summary + * @param event Event to add association to + * @param summary ProductSummary to add association to * @return Copy of event with summary added to the event's products list */ @Override @@ -656,8 +666,9 @@ public synchronized Event addAssociation(Event event, ProductSummary summary) * * NOTE: this removes the association between the event and ALL versions of the product summary. * - * @param event - * @param summary + * @param event An event to remove an association with + * @param summary A ProductSummary to remove an association with + * @throws Exception if error occurs */ @Override public synchronized Event removeAssociation(Event event, @@ -748,7 +759,7 @@ public synchronized Event removeAssociation(Event event, * method will return an empty list. It is up to the calling methods to * check if the clause list is empty when they build their WHERE clause. * - * @param query + * @param query ProductIndexQuery * @return list containing clauses in the form: column="value" */ protected List buildProductClauses(ProductIndexQuery query) { @@ -1027,7 +1038,7 @@ protected String buildProductQuery(List clauseList, String orderby) { * {@link #buildProductQuery(List, String)} with an empty * orderby string * - * @param clauseList + * @param clauseList List of clauses for WHERE * @return String containing the full SELECT query */ protected String buildProductQuery(List clauseList) { @@ -1037,8 +1048,8 @@ protected String buildProductQuery(List clauseList) { /** * Populate links and properties for provided product summaries. * - * @param summaries - * @throws Exception + * @param summaries List of ProductSummaries + * @throws Exception if error occurs */ protected synchronized void loadProductSummaries(final List summaries) throws Exception { @@ -1108,9 +1119,9 @@ protected synchronized void loadProductSummaries(final List summ /** * Parse ProductSummary without loading links or properties. * - * @param results + * @param results ResultSet to parse * @return ProductSummary object without links or properties. - * @throws Exception + * @throws Exception if error occurs */ protected ProductSummary parseProductSummary(ResultSet results) throws Exception { @@ -1161,6 +1172,12 @@ protected ProductSummary parseProductSummary(ResultSet results) return p; } + /** + * + * @param summaries List of product summaries to remove + * @return List of ProductIds that were removed + * @throws Exception if error occurs + */ public synchronized List removeProductSummaries( final List summaries) throws Exception { // index by id @@ -1212,9 +1229,9 @@ public synchronized List removeProductSummaries( * Save the properties in the database and associate them to the given * productId * - * @param productId - * @param properties - * @throws SQLException + * @param productId long product ID to associate to + * @param properties Map of properties to save + * @throws SQLException if SQL error occurs */ protected synchronized void addProductProperties(final long productId, final Map properties) throws SQLException { @@ -1248,7 +1265,7 @@ protected synchronized void addProductProperties(final long productId, * Index id of the product to select * @param links * Map of relations to URIs - * @throws SQLException + * @throws SQLException if sql error occurs */ protected synchronized void addProductLinks(long productId, Map> links) throws SQLException { @@ -1278,7 +1295,7 @@ protected synchronized void addProductLinks(long productId, * Convert the given longitude to be between -180 and 180. If the given * value is already in the range, this method just returns the value. * - * @param lon + * @param lon Double longitude * @return double normalized between -180 and 180 */ protected double normalizeLongitude(double lon) { @@ -1308,7 +1325,7 @@ protected double normalizeLongitude(double lon) { /** * Wrapper to normalize BigDecimal longitudes * - * @param lon + * @param lon BigDecimal Longitude * @return Normalized BigDecimal latitude */ protected BigDecimal normalizeLongitude(BigDecimal lon) { diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductArchivePolicy.java b/src/main/java/gov/usgs/earthquake/indexer/ProductArchivePolicy.java index e2e41455..a8b1bd58 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductArchivePolicy.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductArchivePolicy.java @@ -8,7 +8,7 @@ /** * An archive policy for products, instead of events. - * + * * Allows removal of superseded products, preserving latest versions. Also * allows targeting unassociated products. */ @@ -21,33 +21,53 @@ public class ProductArchivePolicy extends ArchivePolicy { // Names of configurable parameters // -------------------------------------------------------------------- + /** Property for archive min product age */ public static final String ARCHIVE_MIN_PRODUCT_AGE_PROPERTY = "minProductAge"; + /** Property for archive max product age */ public static final String ARCHIVE_MAX_PRODUCT_AGE_PROPERTY = "maxProductAge"; + /** Property for archive min product time */ public static final String ARCHIVE_MIN_PRODUCT_TIME_PROPERTY = "minProductTime"; + /** Property for archive max product time */ public static final String ARCHIVE_MAX_PRODUCT_TIME_PROPERTY = "maxProductTime"; + /** Property for archive product type */ public static final String ARCHIVE_TYPE_PROPERTY = "productType"; + /** Property for archive product source */ public static final String ARCHIVE_SOURCE_PROPERTY = "productSource"; + /** Property for archive superseded */ public static final String ARCHIVE_SUPERSEDED_PROPERTY = "onlySuperseded"; + /** Property for archive unassociated */ public static final String ARCHIVE_UNASSOCIATED_PROPERTY = "onlyUnassociated"; + /** Property for archive product status */ public static final String ARCHIVE_STATUS_PROPERTY = "productStatus"; + /** Default state for archive superseded */ public static final String DEFAULT_ARCHIVE_SUPERSEDED = "true"; + /** Default state for archive unassociated */ public static final String DEFAULT_ARCHIVE_UNASSOCIATED = "false"; // -------------------------------------------------------------------- // Configured parameters. // -------------------------------------------------------------------- + /** Configured parameter for min product age */ protected Long minProductAge = null; + /** Configured parameter for max product age */ protected Long maxProductAge = null; + /** Configured parameter for min product time */ protected Long minProductTime = null; + /** Configured parameter for max product time */ protected Long maxProductTime = null; + /** Configured parameter for product type */ protected String productType = null; + /** Configured parameter for product source */ protected String productSource = null; + /** Configured parameter for only superseded */ protected boolean onlySuperseded = true; + /** Configured parameter for only unassociated */ protected boolean onlyUnassociated = false; + /** Configured parameter for product status */ protected String productStatus = null; @SuppressWarnings("deprecation") @@ -97,7 +117,7 @@ public void configure(Config config) throws Exception { "greater than maxProductAge."); ce.fillInStackTrace(); throw ce; - } + } if ((minProductTime != null && maxProductTime != null) && (minProductTime > maxProductTime)) { @@ -107,8 +127,8 @@ public void configure(Config config) throws Exception { "greater than maxProductTime."); ce.fillInStackTrace(); throw ce; - } - + } + productType = config.getProperty(ARCHIVE_TYPE_PROPERTY); productSource = config.getProperty(ARCHIVE_SOURCE_PROPERTY); onlySuperseded = Boolean.valueOf(config.getProperty( @@ -196,74 +216,92 @@ public boolean isValidPolicy() { || productStatus != null); } + /** @return minProductAge */ public Long getMinProductAge() { return minProductAge; } + /** @param minProductAge to set */ public void setMinProductAge(Long minProductAge) { this.minProductAge = minProductAge; } + /** @return maxProductAge */ public Long getMaxProductAge() { return maxProductAge; } + /** @param maxProductAge to set */ public void setMaxProductAge(Long maxProductAge) { this.maxProductAge = maxProductAge; } + /** @return minProductTime */ public Long getMinProductTime() { return minProductTime; } + /** @param minProductTime to set */ public void setMinProductTime(Long minProductTime) { this.minProductTime = minProductTime; } + /** @return maxProductTime */ public Long getMaxProductTime() { return maxProductTime; } + /** @param maxProductTime to set */ public void setMaxProductTime(Long maxProductTime) { this.maxProductTime = maxProductTime; } + /** @return productType */ public String getProductType() { return productType; } + /** @param productType to set */ public void setProductType(String productType) { this.productType = productType; } + /** @return productSource */ public String getProductSource() { return productSource; } + /** @param productSource to set */ public void setProductSource(String productSource) { this.productSource = productSource; } + /** @return onlySuperseded */ public boolean isOnlySuperseded() { return onlySuperseded; } + /** @param onlySuperseded to set */ public void setOnlySuperseded(boolean onlySuperseded) { this.onlySuperseded = onlySuperseded; } + /** @return onlyUnassociated */ public boolean isOnlyUnassociated() { return onlyUnassociated; } + /** @param onlyUnassociated to set */ public void setOnlyUnassociated(boolean onlyUnassociated) { this.onlyUnassociated = onlyUnassociated; } + /** @return productStatus */ public String getProductStatus() { return productStatus; } + /** @param productStatus to set */ public void setProductStatus(String productStatus) { this.productStatus = productStatus; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductDetailQuery.java b/src/main/java/gov/usgs/earthquake/indexer/ProductDetailQuery.java index 23fb22a7..8345a9d9 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductDetailQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductDetailQuery.java @@ -12,6 +12,10 @@ public class ProductDetailQuery extends SearchQuery { private List result; + /** + * Constructor making a SearchQuery object with PRODUCT_DETAIL as the method + * @param query a ProductIndexQuery + */ public ProductDetailQuery(final ProductIndexQuery query) { super(SearchMethod.PRODUCT_DETAIL, query); } @@ -21,6 +25,7 @@ public List getResult() { return result; } + /** @param product list to set */ public void setResult(final List product) { this.result = product; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductIndex.java b/src/main/java/gov/usgs/earthquake/indexer/ProductIndex.java index e4e2b26c..e034fe3b 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductIndex.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductIndex.java @@ -23,7 +23,7 @@ public interface ProductIndex extends Configurable { /** * If the index supports transactions, begin a transaction. * - * @throws Exception + * @throws Exception if error occurs */ public void beginTransaction() throws Exception; @@ -31,7 +31,7 @@ public interface ProductIndex extends Configurable { * If the index supports transactions, and beginTransaction was previously * called, commit the pending transaction. * - * @throws Exception + * @throws Exception if error occurs */ public void commitTransaction() throws Exception; @@ -39,7 +39,7 @@ public interface ProductIndex extends Configurable { * If the index supports transactions, and beginTransaction was previously * called, rollback the pending transaction. * - * @throws Exception + * @throws Exception if error occurs */ public void rollbackTransaction() throws Exception; @@ -49,7 +49,7 @@ public interface ProductIndex extends Configurable { * @param query * a description of which events to retrieve. * @return a list of matching events. - * @throws Exception + * @throws Exception if error occurs */ public List getEvents(ProductIndexQuery query) throws Exception; @@ -59,7 +59,7 @@ public interface ProductIndex extends Configurable { * @param query * a description of which products to retrieve. * @return a list of matching products. - * @throws Exception + * @throws Exception if error occurs */ public List getProducts(ProductIndexQuery query) throws Exception; @@ -68,6 +68,10 @@ public List getProducts(ProductIndexQuery query) * Check whether index has product. * * May be more efficient than {@link #getProducts(ProductIndexQuery)}. + * + * @param id a ProductId + * @return boolean if index has product + * @throws Exception if error occurs */ public boolean hasProduct(ProductId id) throws Exception; @@ -77,7 +81,7 @@ public List getProducts(ProductIndexQuery query) * @param query * a description of which products to retrieve. * @return a list of unassociated products - * @throws Exception + * @throws Exception if error occurs */ public List getUnassociatedProducts(ProductIndexQuery query) throws Exception; @@ -89,7 +93,7 @@ public List getUnassociatedProducts(ProductIndexQuery query) * the event to add. * @return Copy of event with the eventId attribute set to the id in the * database - * @throws Exception + * @throws Exception if error occurs */ public Event addEvent(final Event event) throws Exception; @@ -111,7 +115,7 @@ public List getUnassociatedProducts(ProductIndexQuery query) * the summary to add. * @return Copy of the product summary object with the indexId set to the * newly inserted id. - * @throws Exception + * @throws Exception if error occurs */ public ProductSummary addProductSummary(final ProductSummary summary) throws Exception; @@ -122,7 +126,7 @@ public ProductSummary addProductSummary(final ProductSummary summary) * @param summary * the summary to remove. * @return id of removed summary. - * @throws Exception + * @throws Exception if error occurs */ public ProductId removeProductSummary(final ProductSummary summary) throws Exception; @@ -135,7 +139,7 @@ public ProductId removeProductSummary(final ProductSummary summary) * @param summary * the summary. * @return Copy of event with summary added to the products list - * @throws Exception + * @throws Exception if error occurs */ public Event addAssociation(final Event event, final ProductSummary summary) throws Exception; @@ -148,7 +152,7 @@ public Event addAssociation(final Event event, final ProductSummary summary) * @param summary * the summary. * @return Copy of event with summary removed from the products list - * @throws Exception + * @throws Exception if error occurs */ public Event removeAssociation(final Event event, final ProductSummary summary) throws Exception; @@ -162,7 +166,7 @@ public Event removeAssociation(final Event event, * * @param events * events that may have new preferred attributes. - * @throws Exception + * @throws Exception if error occurs */ public void eventsUpdated(final List events) throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductIndexQuery.java b/src/main/java/gov/usgs/earthquake/indexer/ProductIndexQuery.java index 020819a1..aedd46a0 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductIndexQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductIndexQuery.java @@ -15,19 +15,19 @@ /** * Criteria for finding events. - * + * * All properties are inclusive. When a property is null, it means any value. - * + * * Expected combinations: - * + * * 1) find events based on event parameters event time event latitude event * longitude - * + * * 2) find previously received update of product product source product type * product code - * + * * 3) find related products/events product ids - * + * * 4) find related products/events event ids */ public class ProductIndexQuery implements Comparable { @@ -40,7 +40,7 @@ public class ProductIndexQuery implements Comparable { private static enum EventSearchTypes { /** * Search preferred event attributes. - * + * * NOTE: SEARCH_EVENT_PREFERRED should ONLY be used on event queries. * Using this on product queries will more than likely break. */ @@ -69,11 +69,16 @@ private static enum ResultTypes { RESULT_TYPE_ALL; }; + /** EventSearchType for SEARCH_EVENT_PREFERRED */ public static EventSearchTypes SEARCH_EVENT_PREFERRED = EventSearchTypes.SEARCH_EVENT_PREFERRED; + /** EventSearchType for SEARCH_EVENT_PRODCUTS */ public static EventSearchTypes SEARCH_EVENT_PRODUCTS = EventSearchTypes.SEARCH_EVENT_PRODUCTS; + /** ResultType for RESULT_TYPE_CURRENT */ public static ResultTypes RESULT_TYPE_CURRENT = ResultTypes.RESULT_TYPE_CURRENT; + /** ResultType for RESULT_TYPE_SUPERSEDED */ public static ResultTypes RESULT_TYPE_SUPERSEDED = ResultTypes.RESULT_TYPE_SUPERSEDED; + /** ResultType for RESULT_TYPE_ALL */ public static ResultTypes RESULT_TYPE_ALL = ResultTypes.RESULT_TYPE_ALL; /** Search preferred or all event attributes? */ @@ -157,205 +162,254 @@ private static enum ResultTypes { public ProductIndexQuery() { } + /** @param eventSearchType to set */ public void setEventSearchType(EventSearchTypes eventSearchType) { this.eventSearchType = eventSearchType; } + /** @return eventSearchType */ public EventSearchTypes getEventSearchType() { return eventSearchType; } + /** @param resultType to set */ public void setResultType(ResultTypes resultType) { this.resultType = resultType; } + /** @return resultType */ public ResultTypes getResultType() { return resultType; } + /** @param eventSource to set */ public void setEventSource(String eventSource) { this.eventSource = (eventSource == null ? null : eventSource .toLowerCase()); } - + /** @return eventSource */ public String getEventSource() { return eventSource; } + /** @param eventSourceCode to set */ public void setEventSourceCode(String eventSourceCode) { this.eventSourceCode = (eventSourceCode == null ? null : eventSourceCode.toLowerCase()); } + /** @return eventSourceCode */ public String getEventSourceCode() { return eventSourceCode; } + /** @return minEventTime */ public Date getMinEventTime() { return minEventTime; } + /** @param minEventTime to set */ public void setMinEventTime(Date minEventTime) { this.minEventTime = minEventTime; } + /** @return maxEventTime */ public Date getMaxEventTime() { return maxEventTime; } + /** @param maxEventTime to set */ public void setMaxEventTime(Date maxEventTime) { this.maxEventTime = maxEventTime; } + /** @return minEventLatitude */ public BigDecimal getMinEventLatitude() { return minEventLatitude; } + /** @param minEventLatitude to set */ public void setMinEventLatitude(BigDecimal minEventLatitude) { this.minEventLatitude = minEventLatitude; } + /** @return maxEventLatitude */ public BigDecimal getMaxEventLatitude() { return maxEventLatitude; } + /** @param maxEventLatitude to set */ public void setMaxEventLatitude(BigDecimal maxEventLatitude) { this.maxEventLatitude = maxEventLatitude; } + /** @return minEventLongitude */ public BigDecimal getMinEventLongitude() { return minEventLongitude; } + /** @param minEventLongitude to set */ public void setMinEventLongitude(BigDecimal minEventLongitude) { this.minEventLongitude = minEventLongitude; } + /** @return maxEventLongitude */ public BigDecimal getMaxEventLongitude() { return maxEventLongitude; } + /** @param maxEventLongitude to set */ public void setMaxEventLongitude(BigDecimal maxEventLongitude) { this.maxEventLongitude = maxEventLongitude; } + /** @return minEventDepth */ public BigDecimal getMinEventDepth() { return minEventDepth; } + /** @param minEventDepth to set */ public void setMinEventDepth(BigDecimal minEventDepth) { this.minEventDepth = minEventDepth; } + /** @return maxEventDepth */ public BigDecimal getMaxEventDepth() { return maxEventDepth; } + /** @param maxEventDepth to set */ public void setMaxEventDepth(BigDecimal maxEventDepth) { this.maxEventDepth = maxEventDepth; } + /** @return minEventMagnitude */ public BigDecimal getMinEventMagnitude() { return minEventMagnitude; } + /** @param minEventMagnitude to set */ public void setMinEventMagnitude(BigDecimal minEventMagnitude) { this.minEventMagnitude = minEventMagnitude; } + /** @return maxEventMagnitude */ public BigDecimal getMaxEventMagnitude() { return maxEventMagnitude; } + /** @param maxEventMagnitude to set */ public void setMaxEventMagnitude(BigDecimal maxEventMagnitude) { this.maxEventMagnitude = maxEventMagnitude; } + /** @return list of product Ids */ public List getProductIds() { return productIds; } + /** @param productIds list to set */ public void setProductIds(List productIds) { this.productIds.clear(); this.productIds.addAll(productIds); } + /** @return minProductUpdateTime */ public Date getMinProductUpdateTime() { return minProductUpdateTime; } + /** @param minProductUpdateTime to set */ public void setMinProductUpdateTime(Date minProductUpdateTime) { this.minProductUpdateTime = minProductUpdateTime; } + /** @return maxProductUpdateTime */ public Date getMaxProductUpdateTime() { return maxProductUpdateTime; } + /** @param maxProductUpdateTime to set */ public void setMaxProductUpdateTime(Date maxProductUpdateTime) { this.maxProductUpdateTime = maxProductUpdateTime; } + /** @return productSource */ public String getProductSource() { return productSource; } + /** @param productSource to set */ public void setProductSource(String productSource) { this.productSource = productSource; } + /** @return productType */ public String getProductType() { return productType; } + /** @param productType to set */ public void setProductType(String productType) { this.productType = productType; } + /** @return productCode */ public String getProductCode() { return productCode; } + /** @param productCode to set */ public void setProductCode(String productCode) { this.productCode = productCode; } + /** @param productVersion to set */ public void setProductVersion(String productVersion) { this.productVersion = productVersion; } + /** @return productVersion */ public String getProductVersion() { return productVersion; } + /** @param productStatus to set */ public void setProductStatus(String productStatus) { this.productStatus = productStatus; } + /** @return productStatus */ public String getProductStatus() { return productStatus; } + /** @param minProductIndexId to set */ public void setMinProductIndexId(final Long minProductIndexId) { this.minProductIndexId = minProductIndexId; } + /** @return minProductIndexId */ public Long getMinProductIndexId() { return this.minProductIndexId; } + /** @param limit to set */ public void setLimit(final Integer limit) { this.limit = limit; } + /** @return limit */ public Integer getLimit() { return this.limit; } + /** @param orderBy to set */ public void setOrderBy(final String orderBy) { this.orderBy = orderBy; } + /** @return orderBy */ public String getOrderBy() { return this.orderBy; } @@ -447,6 +501,13 @@ public int compareTo(ProductIndexQuery that) { return 0; } + /** + * Compare function + * @param Type + * @param o1 First item to compare + * @param o2 Second to comoare + * @return 0 if equal, 1 if o1 is null, -1 if o2 null, or the comparison + */ protected > int compare(T o1, T o2) { if (o1 == null && o2 == null) { return 0; @@ -459,6 +520,10 @@ protected > int compare(T o1, T o2) { } } + /** + * Log function + * @param logger logger object + */ public void log(final Logger logger) { if (!logger.isLoggable(Level.FINEST)) { return; diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductSummary.java b/src/main/java/gov/usgs/earthquake/indexer/ProductSummary.java index ffbb62f6..e938c07f 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductSummary.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductSummary.java @@ -19,7 +19,7 @@ /** * A ProductSummary is essentially a product without its contents. - * + * * These are usually created by {@link IndexerModule}s, which may * inspect Product Content to add additional summary properties. */ @@ -78,10 +78,10 @@ public ProductSummary() { /** * Copy constructor for ProductSummary. - * + * * Does a deep copy of properties and links maps. All other attributes are * copied by reference. - * + * * @param copy * product summary to copy. */ @@ -112,10 +112,10 @@ public ProductSummary(final ProductSummary copy) { /** * Create a ProductSummary from a product. - * + * * All attributes are copied from the product, and preferredWeight is set to * 1L. - * + * * @param product * the product to summarize. */ @@ -143,30 +143,37 @@ public ProductSummary(final Product product) { this.setPreferredWeight(1L); } + /** @return indexId */ public Long getIndexId() { return indexId; } + /** @param indexId to set */ public void setIndexId(Long indexId) { this.indexId = indexId; } + /** @return product id */ public ProductId getId() { return id; } + /** @param id to set */ public void setId(ProductId id) { this.id = id; } + /** @return status */ public String getStatus() { return status; } + /** @param status to set */ public void setStatus(String status) { this.status = status; } + /** @return if product is deleted */ public boolean isDeleted() { if (Product.STATUS_DELETE.equalsIgnoreCase(this.status)) { return true; @@ -175,18 +182,22 @@ public boolean isDeleted() { } } + /** @return trackerURL */ public URL getTrackerURL() { return trackerURL; } + /** @param trackerURL to set */ public void setTrackerURL(URL trackerURL) { this.trackerURL = trackerURL; } + /** @return preferredWeight */ public long getPreferredWeight() { return preferredWeight; } + /** @param weight to set */ public void setPreferredWeight(long weight) { this.preferredWeight = weight; } @@ -208,7 +219,7 @@ public void setProperties(final Map properties) { /** * Returns a reference to the links map. - * + * * @return the links */ public Map> getLinks() { @@ -217,7 +228,7 @@ public Map> getLinks() { /** * Copies entries from provided map. - * + * * @param links * the links to set */ @@ -228,7 +239,7 @@ public void setLinks(final Map> links) { /** * Add a link to a product. - * + * * @param relation * how link is related to product. * @param href @@ -243,6 +254,7 @@ public void addLink(final String relation, final URI href) { relationLinks.add(href); } + /** @return null or eventId */ public String getEventId() { if (eventSource == null || eventSourceCode == null) { return null; @@ -250,10 +262,12 @@ public String getEventId() { return (eventSource + eventSourceCode).toLowerCase(); } + /** @return eventSource */ public String getEventSource() { return eventSource; } + /** @param eventSource to set */ public void setEventSource(String eventSource) { this.eventSource = eventSource; @@ -269,10 +283,12 @@ public void setEventSource(String eventSource) { } } + /** @return eventSourceCode */ public String getEventSourceCode() { return eventSourceCode; } + /** @param eventSourceCode to set */ public void setEventSourceCode(String eventSourceCode) { this.eventSourceCode = eventSourceCode; @@ -289,10 +305,12 @@ public void setEventSourceCode(String eventSourceCode) { } } + /** @return eventTime */ public Date getEventTime() { return eventTime; } + /** @param eventTime to set */ public void setEventTime(Date eventTime) { this.eventTime = eventTime; if (eventTime != null) { @@ -304,10 +322,12 @@ public void setEventTime(Date eventTime) { } + /** @return eventLatitude */ public BigDecimal getEventLatitude() { return eventLatitude; } + /** @param eventLatitude to set */ public void setEventLatitude(BigDecimal eventLatitude) { this.eventLatitude = eventLatitude; if (eventLatitude != null) { @@ -318,10 +338,12 @@ public void setEventLatitude(BigDecimal eventLatitude) { } } + /** @return eventLongitude */ public BigDecimal getEventLongitude() { return eventLongitude; } + /** @param eventLongitude to set */ public void setEventLongitude(BigDecimal eventLongitude) { this.eventLongitude = eventLongitude; if (eventLongitude != null) { @@ -332,10 +354,12 @@ public void setEventLongitude(BigDecimal eventLongitude) { } } + /** @return eventDepth */ public BigDecimal getEventDepth() { return eventDepth; } + /** @param eventDepth to set */ public void setEventDepth(BigDecimal eventDepth) { this.eventDepth = eventDepth; if (eventDepth != null) { @@ -345,10 +369,12 @@ public void setEventDepth(BigDecimal eventDepth) { } } + /** @return eventMagnitude */ public BigDecimal getEventMagnitude() { return eventMagnitude; } + /** @param eventMagnitude to set */ public void setEventMagnitude(BigDecimal eventMagnitude) { this.eventMagnitude = eventMagnitude; if (eventMagnitude != null) { @@ -359,10 +385,12 @@ public void setEventMagnitude(BigDecimal eventMagnitude) { } } + /** @return version */ public String getVersion() { return version; } + /** @param version to set */ public void setVersion(String version) { this.version = version; if (version != null) { @@ -372,25 +400,29 @@ public void setVersion(String version) { } } + /** @return type */ public String getType() { return getId().getType(); } + /** @return source */ public String getSource() { return getId().getSource(); } + /** @return code */ public String getCode() { return getId().getCode(); } + /** @return updateTime */ public Date getUpdateTime() { return getId().getUpdateTime(); } /** * Compares two ProductSummaries to determine if they are equal. - * + * * This first implementation just considers the ProductId of each summary. * This is probably not the best way to check for equality. */ diff --git a/src/main/java/gov/usgs/earthquake/indexer/ProductsSummaryQuery.java b/src/main/java/gov/usgs/earthquake/indexer/ProductsSummaryQuery.java index ee6bb740..615ac5d5 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ProductsSummaryQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ProductsSummaryQuery.java @@ -10,6 +10,11 @@ public class ProductsSummaryQuery extends SearchQuery { private List result; + /** + * Constructor + * makes a SearchQuery of type product summary + * @param query ProductIndexQuery + */ public ProductsSummaryQuery(final ProductIndexQuery query) { super(SearchMethod.PRODUCTS_SUMMARY, query); } @@ -19,6 +24,7 @@ public List getResult() { return result; } + /** @param products List of ProductSummaries */ public void setResult(final List products) { this.result = products; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/ReliableIndexerListener.java b/src/main/java/gov/usgs/earthquake/indexer/ReliableIndexerListener.java index 4f1f43e1..44d19699 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/ReliableIndexerListener.java +++ b/src/main/java/gov/usgs/earthquake/indexer/ReliableIndexerListener.java @@ -33,6 +33,7 @@ public class ReliableIndexerListener extends DefaultIndexerListener implements Runnable { + /** Logger object */ protected static final Logger LOGGER = Logger .getLogger(ReliableIndexerListener.class.getName()); @@ -43,6 +44,7 @@ public class ReliableIndexerListener extends DefaultIndexerListener implements R private final Object syncObject = new Object(); private Thread processThread; + /** Product Index */ protected ProductIndex productIndex; /** @@ -183,10 +185,12 @@ public void shutdown() throws Exception { } } + /** @return ProductIndex */ public ProductIndex getProductIndex() { return this.productIndex; } + /** @param productIndex to set */ public void setProductIndex(ProductIndex productIndex) { this.productIndex = productIndex; } @@ -198,6 +202,7 @@ public void setProductIndex(ProductIndex productIndex) { /** * Gets index ID of last processed product + * @return lastIndexId */ public long getLastIndexId() { return lastIndexId; @@ -205,6 +210,7 @@ public long getLastIndexId() { /** * Sets index ID of last processed product + * @param lastIndexId to set */ public void setLastIndexId(final long lastIndexId) { this.lastIndexId = lastIndexId; @@ -244,6 +250,7 @@ protected void onProcessException(ProductSummary product, Exception e) throws Ex /** * Gets the next products using the index provided in Config * + * @return List of product summaries * @throws Exception if we have a database issue */ public List getNextProducts() throws Exception{ @@ -258,6 +265,7 @@ public List getNextProducts() throws Exception{ /** * Does a task with each product * + * @param product ProductSummary to process * @throws Exception available for subclasses */ public void processProduct(final ProductSummary product) throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchCLI.java b/src/main/java/gov/usgs/earthquake/indexer/SearchCLI.java index 1091eeb0..1c81c7fa 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchCLI.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchCLI.java @@ -11,7 +11,7 @@ /** * Command line interface for search socket. - * + * * This class reads arguments from the command line that represent a * ProductIndexQuery. Then it connects to a configured socket, executes the * search, and outputs the response xml. @@ -24,31 +24,55 @@ public class SearchCLI { /** * Command-line argument definitions */ + /** Argument for search method */ public static String SEARCH_METHOD_ARGUMENT = "--searchMethod="; + /** Argument for result type */ public static String RESULT_TYPE_ARGUMENT = "--resultType="; + /** Argument for event Source */ public static String EVENT_SOURCE_ARGUMENT = "--eventSource="; + /** Argument for event Source Code */ public static String EVENT_SOURCE_CODE_ARGUMENT = "--eventSourceCode="; + /** Argument for minimum Event Time */ public static String MIN_EVENT_TIME_ARGUMENT = "--minEventTime="; + /** Argument for maximum event time */ public static String MAX_EVENT_TIME_ARGUMENT = "--maxEventTime="; + /** Argument for minimum event latitude */ public static String MIN_EVENT_LATITUDE_ARGUMENT = "--minEventLatitude="; + /** Argument for minimum event longitude */ public static String MIN_EVENT_LONGITUDE_ARGUMENT = "--minEventLongitude="; + /** Argument for maximum event latitude */ public static String MAX_EVENT_LATITUDE_ARGUMENT = "--maxEventLatitude="; + /** Argument for maximum event longitude */ public static String MAX_EVENT_LONGITUDE_ARGUMENT = "--maxEventLongitude="; + /** Argument for minimum event depth */ public static String MIN_EVENT_DEPTH_ARGUMENT = "--minEventDepth="; + /** Argument for maximum event depth */ public static String MAX_EVENT_DEPTH_ARGUMENT = "--maxEventDepth="; + /** Argument for minimum event magnitude */ public static String MIN_EVENT_MAGNITUDE_ARGUMENT = "--minEventMagnitude="; + /** Argument for maximum event magnitude */ public static String MAX_EVENT_MAGNITUDE_ARGUMENT = "--maxEventMagnitude="; + /** Argument for product ID */ public static String PRODUCT_ID_ARGUMENT = "--productId="; + /** Argument for minimum product update time */ public static String MIN_PRODUCT_UPDATE_TIME_ARGUMENT = "--minProductUpdateTime="; + /** Argument for maximum product update time */ public static String MAX_PRODUCT_UPDATE_TIME_ARGUMENT = "--maxProductUpdateTime="; + /** Argument for product source */ public static String PRODUCT_SOURCE_ARGUMENT = "--productSource="; + /** Argument for product type */ public static String PRODUCT_TYPE_ARGUMENT = "--productType="; + /** Argument for product verion */ public static String PRODUCT_VERSION_ARGUMENT = "--productVersion="; + /** Argument for product status */ public static String PRODUCT_STATUS_ARGUMENT = "--productStatus="; + /** Argument for search host */ public static String SEARCH_HOST_ARGUMENT = "--searchHost="; + /** Argument for search port */ public static String SEARCH_PORT_ARGUMENT = "--searchPort="; + /** Argument for file output */ public static String FILE_OUTPUT_ARGUMENT = "--outputFile="; /** @@ -60,10 +84,10 @@ public SearchCLI() { /** * Entry point into search. Called by Main when the --search argument is * used. - * + * * @param args * command line arguments. - * @throws Exception + * @throws Exception if error occurs */ public static void main(final String[] args) throws Exception { String outputFilePath = null; @@ -167,6 +191,10 @@ public static void main(final String[] args) throws Exception { socket.search(request, stream); } + /** + * CLI Usage + * @return string of usage + */ public static String getUsage() { StringBuffer buf = new StringBuffer(); diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchQuery.java b/src/main/java/gov/usgs/earthquake/indexer/SearchQuery.java index 7c29508b..e95175f0 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchQuery.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchQuery.java @@ -13,13 +13,13 @@ public abstract class SearchQuery implements Comparable { /** The search parameters. */ private final ProductIndexQuery query; - + /** Contains an error returned in a SearchResult if one occurred **/ private String error; /** * Construct a new SearchQuery object. - * + * * @param type * the type of search. * @param query @@ -31,24 +31,26 @@ protected SearchQuery(final SearchMethod type, final ProductIndexQuery query) { this.error = null; } + /** @return type */ public SearchMethod getType() { return this.type; } + /** @return ProductIndexQuery */ public ProductIndexQuery getProductIndexQuery() { return this.query; } /** * Get the result associated with a specific query type. - * + * * @return the result, or null if the search has not yet executed. */ public abstract Object getResult(); /** * Create a SearchQuery object based on a SearchType. - * + * * @param type * the search type to create * @param query diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchRequestParser.java b/src/main/java/gov/usgs/earthquake/indexer/SearchRequestParser.java index 1b1c7348..9907d595 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchRequestParser.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchRequestParser.java @@ -21,9 +21,11 @@ public class SearchRequestParser extends DefaultHandler { /** The query being parsed. */ private SearchQuery searchQuery; + /** Empty constructor */ public SearchRequestParser() { } + /** @return searchRequest */ public SearchRequest getSearchRequest() { return searchRequest; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchResponse.java b/src/main/java/gov/usgs/earthquake/indexer/SearchResponse.java index 1abab78b..8d70e306 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchResponse.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchResponse.java @@ -21,8 +21,8 @@ public SearchResponse() { /** * Add a search result to this response. - * - * @param result + * + * @param result a searchQuery result */ public void addResult(final SearchQuery result) { results.add(result); @@ -70,7 +70,7 @@ public int hashCode() { /** * Get a distinct list of events from EventDetailQuery results. - * + * * @return List of found events. List will be empty if there were no * EventDetailQueries, or no matching events were found. */ diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchResponseParser.java b/src/main/java/gov/usgs/earthquake/indexer/SearchResponseParser.java index 5f1a1252..f4d4896a 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchResponseParser.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchResponseParser.java @@ -36,10 +36,15 @@ public class SearchResponseParser extends DefaultHandler { private FileProductStorage storage; private SearchResponseXmlProductSource productHandler = null; + /** + * Constructor + * @param storage a FileProductStorage + */ public SearchResponseParser(final FileProductStorage storage) { this.storage = storage; } + /** @return SearchResponse */ public SearchResponse getSearchResponse() { return response; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchResponseXmlProductSource.java b/src/main/java/gov/usgs/earthquake/indexer/SearchResponseXmlProductSource.java index ad0d46a5..b2fdb53e 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchResponseXmlProductSource.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchResponseXmlProductSource.java @@ -18,7 +18,7 @@ /** * Used by SearchResponseParser to store products during parsing. - * + * * Creates a "background" storage thread for storing, while this classes * startElement, characters, and endElement methods are called by the * "foreground" xml parsing thread. @@ -53,7 +53,7 @@ public class SearchResponseXmlProductSource extends XmlProductSource { /** * Construct a SearchResponseXmlProductSource. - * + * * @param storage * the storage where the parsed product is stored. */ @@ -64,7 +64,7 @@ public SearchResponseXmlProductSource(final FileProductStorage storage) { /** * Called by the underlying product storage as part os storeProductSource. - * + * * This method notifies the XML parsing thread that parsing may continue, * since the handler is now setup. */ @@ -189,10 +189,12 @@ public void endElement(final String uri, final String localName, } } + /** @param storage FileProductStorage to set */ public void setStorage(FileProductStorage storage) { this.storage = storage; } + /** @return FileProductStorage */ public FileProductStorage getStorage() { return storage; } @@ -206,8 +208,8 @@ public Product getProduct() { /** * Method used by storage to provide the parsed product. - * - * @param product + * + * @param product to set */ protected void setProduct(final Product product) { this.storedProduct = product; diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchServerSocket.java b/src/main/java/gov/usgs/earthquake/indexer/SearchServerSocket.java index a0da59e0..bdb53de7 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchServerSocket.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchServerSocket.java @@ -68,13 +68,13 @@ public SearchServerSocket() { /** * Method to perform search. - * + * * Calls Indexer.search(SearchRequest). Simplifies testing. - * + * * @param request * the search to execute. * @return the search response. - * @throws Exception + * @throws Exception if error occurs */ protected SearchResponse search(final SearchRequest request) throws Exception { @@ -183,26 +183,32 @@ public void startup() throws Exception { acceptor.start(); } + /** @return int port */ public int getPort() { return port; } + /** @param port int to set */ public void setPort(int port) { this.port = port; } + /** @return int threads */ public int getThreads() { return threads; } + /** @param threads into to set */ public void setThreads(int threads) { this.threads = threads; } + /** @return indexer */ public Indexer getIndexer() { return indexer; } + /** @param indexer to set */ public void setIndex(Indexer indexer) { this.indexer = indexer; } diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchSocket.java b/src/main/java/gov/usgs/earthquake/indexer/SearchSocket.java index 5be6f00d..8e6b5a4b 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchSocket.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchSocket.java @@ -27,7 +27,7 @@ public class SearchSocket { /** * Construct a new SearchSocket. - * + * * @param host * the remote host. * @param port @@ -40,13 +40,13 @@ public SearchSocket(final InetAddress host, final int port) { /** * Send a search request, converting the response to a java object. - * + * * @param request * the request to send. * @param storage * where received products are stored. * @return the response. - * @throws Exception + * @throws Exception if error occurs */ public SearchResponse search(final SearchRequest request, final FileProductStorage storage) throws Exception { final PipedInputStream pipedIn = new PipedInputStream(); @@ -72,12 +72,12 @@ public SearchResponse search(final SearchRequest request, final FileProductStora /** * Send a search request, writing the response to an outputstream. - * + * * @param request * the request to send. * @param responseOut * the outputstream to write. - * @throws Exception + * @throws Exception if error occurs */ public void search(final SearchRequest request, final OutputStream responseOut) throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/indexer/SearchXML.java b/src/main/java/gov/usgs/earthquake/indexer/SearchXML.java index a851ff99..d8f687de 100644 --- a/src/main/java/gov/usgs/earthquake/indexer/SearchXML.java +++ b/src/main/java/gov/usgs/earthquake/indexer/SearchXML.java @@ -20,60 +20,102 @@ */ public class SearchXML { + /** Location of Indexer on distribution site */ public static final String INDEXER_XMLNS = "http://earthquake.usgs.gov/distribution/indexer"; + /** Element for searchRequests */ public static final String REQUEST_ELEMENT = "searchrequest"; + /** Element for searchResponses */ public static final String RESPONSE_ELEMENT = "searchresponse"; + /** Element for results */ public static final String RESULT_ELEMENT = "result"; + /** Element for queries */ public static final String QUERY_ELEMENT = "query"; + /** Element for events */ public static final String EVENT_ELEMENT = "event"; + /** Element for errors */ public static final String ERROR_ELEMENT = "error"; + /** Attribute for methods */ public static final String METHOD_ATTRIBUTE = "method"; + /** Attribute for event source */ public static final String EVENT_SOURCE_ATTRIBUTE = "eventSource"; + /** Attribute for event source code */ public static final String EVENT_SOURCE_CODE_ATTRIBUTE = "eventSourceCode"; + /** Attribute for min event time */ public static final String MIN_EVENT_TIME_ATTRIBUTE = "minEventTime"; + /** Attribute for max event time */ public static final String MAX_EVENT_TIME_ATTRIBUTE = "maxEventTime"; + /** Attribute for min event latitude*/ public static final String MIN_EVENT_LATITUDE_ATTRIBUTE = "minEventLatitude"; + /** Attribute for max event latitude */ public static final String MAX_EVENT_LATITUDE_ATTRIBUTE = "maxEventLatitude"; + /** Attribute for min event longitude */ public static final String MIN_EVENT_LONGITUDE_ATTRIBUTE = "minEventLongitude"; + /** Attribute for max event longitude */ public static final String MAX_EVENT_LONGITUDE_ATTRIBUTE = "maxEventLongitude"; + /** Attribute for min event depth */ public static final String MIN_EVENT_DEPTH_ATTRIBUTE = "minEventDepth"; + /** Attribute for max event depth*/ public static final String MAX_EVENT_DEPTH_ATTRIBUTE = "maxEventDepth"; + /** Attribute for min event magnitude */ public static final String MIN_EVENT_MAGNITUDE_ATTRIBUTE = "minEventMagnitude"; + /** Attribute for max event magnitude */ public static final String MAX_EVENT_MAGNITUDE_ATTRIBUTE = "maxEventMagnitude"; + /** Attribute for min product update time */ public static final String MIN_PRODUCT_UPDATE_TIME_ATTRIBUTE = "minProductUpdateTime"; + /** Attribute for max product update time */ public static final String MAX_PRODUCT_UPDATE_TIME_ATTRIBUTE = "maxProductUpdateTime"; + /** Attribute for product source */ public static final String PRODUCT_SOURCE_ATTRIBUTE = "productSource"; + /** Attribute for product type */ public static final String PRODUCT_TYPE_ATTRIBUTE = "productType"; + /** Attribute for product code */ public static final String PRODUCT_CODE_ATTRIBUTE = "productCode"; + /** Attribute for product version */ public static final String PRODUCT_VERSION_ATTRIBUTE = "productVersion"; + /** Attribute for product Status */ public static final String PRODUCT_STATUS_ATTRIBUTE = "productStatus"; + /** Element for event summary */ public static final String EVENT_SUMMARY_ELEMENT = "eventSummary"; + /** Element for product summary */ public static final String PRODUCT_SUMMARY_ELEMENT = "productSummary"; + /** Attribute for id */ public static final String ID_ATTRIBUTE = "id"; + /** Attribute for update time */ public static final String UPDATE_TIME_ATTRIBUTE = "updateTime"; + /** Attribute for status */ public static final String STATUS_ATTRIBUTE = "status"; + /** Attribute for source */ public static final String SOURCE_ATTRIBUTE = "source"; + /** Attribute for source code */ public static final String SOURCE_CODE_ATTRIBUTE = "sourceCode"; + /** Attribute for time */ public static final String TIME_ATTRIBUTE = "time"; + /** Attribute for latitude */ public static final String LATITUDE_ATTRIBUTE = "latitude"; + /** Attribute for longitude */ public static final String LONGITUDE_ATTRIBUTE = "longitude"; + /** Attribute for depth */ public static final String DEPTH_ATTRIBUTE = "depth"; + /** Attribute for magnitude */ public static final String MAGNITUDE_ATTRIBUTE = "magnitude"; + /** Attribute for version */ public static final String VERSION_ATTRIBUTE = "version"; + /** Attribute for preferred weight */ public static final String PREFERRED_WEIGHT_ATTRIBUTE = "preferredWeight"; /** * Parse an input stream with xml to a SearchRequest object. - * + * * @param in * the input stream containing xml. * @return the parsed SearchRequest object. + * @throws Exception if error occurs */ public static SearchRequest parseRequest(final InputStream in) throws Exception { @@ -84,13 +126,13 @@ public static SearchRequest parseRequest(final InputStream in) /** * Parse an input stream with xml to a SearchResponse object. - * + * * @param in * the input stream containing xml. * @param storage * the storage where received products are stored. * @return the parsed SearchResponse object. - * @throws Exception + * @throws Exception if error occurs */ public static SearchResponse parseResponse(final InputStream in, final FileProductStorage storage) throws Exception { @@ -101,12 +143,12 @@ public static SearchResponse parseResponse(final InputStream in, /** * Convert a SearchRequest object to xml. - * + * * @param request * the search request object to convert. * @param out * the output stream where xml is written. - * @throws Exception + * @throws Exception if error occurs */ public static void toXML(final SearchRequest request, final OutputStream out) throws Exception { @@ -127,12 +169,12 @@ public static void toXML(final SearchRequest request, final OutputStream out) /** * Convert a SearchResponse object to xml. - * + * * @param response * the search response object to convert. * @param out * the output stream where xml is written. - * @throws Exception + * @throws Exception if error occurs */ public static void toXML(final SearchResponse response, final OutputStream out) throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/nats/NATSClient.java b/src/main/java/gov/usgs/earthquake/nats/NATSClient.java index db8d23ca..788a566b 100644 --- a/src/main/java/gov/usgs/earthquake/nats/NATSClient.java +++ b/src/main/java/gov/usgs/earthquake/nats/NATSClient.java @@ -19,13 +19,19 @@ */ public class NATSClient implements Configurable { + /** Logger object */ public static Logger LOGGER = Logger .getLogger(NATSClient.class.getName()); + /** Property for server host */ public static String SERVER_HOST_PROPERTY = "serverHost"; + /** Property for server port */ public static String SERVER_PORT_PROPERTY = "serverPort"; + /** Property for cluster id */ public static String CLUSTER_ID_PROPERTY = "clusterId"; + /** Property for client id */ public static String CLIENT_ID_PROPERTY = "clientId"; + /** Property for subject */ public static String SUBJECT_PROPERTY = "subject"; private String serverHost; @@ -36,10 +42,18 @@ public class NATSClient implements Configurable { private StreamingConnection connection; + /** Constructor for testing*/ public NATSClient() { this("localhost","4222","test-cluster",Long.toString(Thread.currentThread().getId())); } + /** + * Custom constructor + * @param serverHost String of host + * @param serverPort String of port + * @param clusterId String of clusterID + * @param clientIdSuffix String of idSuffix + */ public NATSClient(String serverHost, String serverPort, String clusterId, String clientIdSuffix) { // try to generate a unique ID; use suffix only if fail this.serverHost = serverHost; @@ -53,7 +67,7 @@ public NATSClient(String serverHost, String serverPort, String clusterId, String * * @param config * the Config to load. - * @throws Exception + * @throws Exception if error occurs */ @Override public void configure(Config config) throws Exception { @@ -142,42 +156,52 @@ public void setName(String string) { } + /** @return serverHost */ public String getServerHost() { return serverHost; } + /** @param serverHost to set */ public void setServerHost(String serverHost) { this.serverHost = serverHost; } + /** @return serverPort */ public String getServerPort() { return serverPort; } + /** @param serverPort to set */ public void setServerPort(String serverPort) { this.serverPort = serverPort; } + /** @return clusterID */ public String getClusterId() { return clusterId; } + /** @param clusterId to set */ public void setClusterId(String clusterId) { this.clusterId = clusterId; } + /** @return clientID */ public String getClientId() { return clientId; } + /** @param clientId to set */ public void setClientId(String clientId) { this.clientId = clientId; } + /** @return StreamingConnection */ public StreamingConnection getConnection() { return connection; } + /** @param connection StreamingConnection to set */ public void setConnection(StreamingConnection connection) { this.connection = connection; } diff --git a/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationReceiver.java b/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationReceiver.java index edc228d9..1eee54b4 100644 --- a/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationReceiver.java +++ b/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationReceiver.java @@ -30,11 +30,16 @@ public class NATSStreamingNotificationReceiver extends DefaultNotificationReceiv private static final Logger LOGGER = Logger .getLogger(DefaultNotificationReceiver.class.getName()); + /** Property for tracking file name */ public static String TRACKING_FILE_NAME_PROPERTY = "trackingFile"; + /** Property on if update sequence should occur after exception */ public static String UPDATE_SEQUENCE_AFTER_EXCEPTION_PROPERTY = "updateSequenceAfterException"; + /** Property for sequence */ public static String SEQUENCE_PROPERTY = "sequence"; + /** Name of deafult tracking file */ public static String DEFAULT_TRACKING_FILE_NAME_PROPERTY = "data/STANReceiverInfo.json"; + /** Default state of update after exception */ public static String DEFAULT_UPDATE_SEQUENCE_AFTER_EXCEPTION_PROPERTY = "true"; private NATSClient client = new NATSClient(); @@ -74,8 +79,8 @@ public void configure(Config config) throws Exception { * Does initial tracking file management and subscribes to server * With a tracking file, gets the last sequence * - * @throws InterruptedException - * @throws IOException + * @throws InterruptedException if interrupted + * @throws IOException if IO error occurs */ @Override public void startup() throws Exception { @@ -106,9 +111,9 @@ public void startup() throws Exception { * Closes subscription/connection and writes state in tracking file * Wraps each statement in a try/catch to ensure each step still happens * - * @throws IOException - * @throws InterruptedException - * @throws TimeoutException + * @throws IOException if IO error occurs + * @throws InterruptedException if interrupted + * @throws TimeoutException if timeout */ @Override public void shutdown() throws Exception { @@ -129,6 +134,7 @@ public void shutdown() throws Exception { /** * Writes pertinent configuration information to tracking file + * @throws Exception if error occurs */ public void writeTrackingFile() throws Exception { JsonObject json = Json.createObjectBuilder() @@ -150,6 +156,7 @@ public void writeTrackingFile() throws Exception { * Reads contents of tracking file * * @return JsonObject containing tracking file contents, or null if file doesn't exist + * @throws Exception if error occurs */ public JsonObject readTrackingFile() throws Exception { JsonObject json = null; @@ -192,26 +199,32 @@ public void onMessage(Message message) { } } + /** @return trackingFileName */ public String getTrackingFileName() { return trackingFileName; } + /** @param trackingFileName to set */ public void setTrackingFileName(String trackingFileName) { this.trackingFileName = trackingFileName; } + /** @return NATSClient */ public NATSClient getClient() { return client; } + /** @param client NATSClient to set */ public void setClient(NATSClient client) { this.client = client; } + /** @return subject */ public String getSubject() { return subject; } + /** @param subject to set */ public void setSubject(String subject) { this.subject = subject; } diff --git a/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationSender.java b/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationSender.java index 2cd3381a..b3393330 100644 --- a/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationSender.java +++ b/src/main/java/gov/usgs/earthquake/nats/NATSStreamingNotificationSender.java @@ -67,18 +67,22 @@ public void shutdown() throws Exception { super.shutdown(); } + /** @return NATSClient */ public NATSClient getClient() { return client; } + /** @param client NATSClient to set */ public void setClient(NATSClient client) { this.client = client; } + /** @return subject */ public String getSubject() { return subject; } + /** @param subject to set */ public void setSubject(String subject) { this.subject = subject; } diff --git a/src/main/java/gov/usgs/earthquake/origin/OriginIndexerModule.java b/src/main/java/gov/usgs/earthquake/origin/OriginIndexerModule.java index 271824cd..7ccfb35b 100644 --- a/src/main/java/gov/usgs/earthquake/origin/OriginIndexerModule.java +++ b/src/main/java/gov/usgs/earthquake/origin/OriginIndexerModule.java @@ -34,24 +34,38 @@ public class OriginIndexerModule extends DefaultIndexerModule { private GeoserveRegionsService geoserveRegions; + /** Property for places endpoint url */ public static final String PLACES_ENDPOINT_URL_PROPERTY = "placesEndpointUrl"; + /** property for regions endpoint url */ public static final String REGIONS_ENDPOINT_URL_PROPERTY = "regionsEndpointUrl"; + /** property for connectTimeout */ public static final String CONNECT_TIMEOUT_PROPERTY = "connectTimeout"; + /** Properties for readTimeout */ public static final String READ_TIMEOUT_PROPERTY = "readTimeout"; - + /** Property for Geoserve distance threshold */ public static final String GEOSERVE_DISTANCE_THRESHOLD_PROPERTY = "geoserveDistanceThreshold"; - // Distance threshold (in km), determines whether to use fe region - // or nearest place in the event title + /** + * Distance threshold (in km), determines whether to use fe region + * or nearest place in the event title + */ public static final int DEFAULT_GEOSERVE_DISTANCE_THRESHOLD = 300; private int distanceThreshold; + /** + * Empty constructor + * Do nothing, must be configured through bootstrapping before use + */ public OriginIndexerModule() { - // Do nothing, must be configured through bootstrapping before use } + /** + * Constructor + * @param geoservePlaces GeoservePlacesService + * @param geoserveRegions GeoserveRegionsService + */ public OriginIndexerModule( final GeoservePlacesService geoservePlaces, final GeoserveRegionsService geoserveRegions @@ -233,6 +247,8 @@ public void configure(Config config) throws Exception { * @param longitude event longitude in degrees * * @return {String} event name + * + * @throws IOException if IO error occurs */ public String getEventTitle(BigDecimal latitude, BigDecimal longitude) throws IOException { try { @@ -249,6 +265,11 @@ public String getEventTitle(BigDecimal latitude, BigDecimal longitude) throws IO return this.geoserveRegions.getFeRegionName(latitude, longitude); } + /** + * Takes properties from feature and formats them into a string + * @param feature feature to format + * @return string with distance, direction, name, and admin + */ public String formatEventTitle(JsonObject feature) { JsonObject properties = feature.getJsonObject("properties"); diff --git a/src/main/java/gov/usgs/earthquake/product/AbstractContent.java b/src/main/java/gov/usgs/earthquake/product/AbstractContent.java index 8aa2b1c2..039ed32a 100644 --- a/src/main/java/gov/usgs/earthquake/product/AbstractContent.java +++ b/src/main/java/gov/usgs/earthquake/product/AbstractContent.java @@ -123,7 +123,7 @@ public Long getLength() { /** * Set the content length. * - * @param length + * @param length long to set */ public void setLength(final Long length) { if (length == null) { @@ -144,7 +144,8 @@ public String getSha256() throws Exception { * Get or generate the MD5 hash of content. * * @param computeIfMissing Use getInputStream to generate hash if missing. - * @throws Exception + * @return sha256 string + * @throws Exception if error occurs */ public String getSha256(final boolean computeIfMissing) throws Exception { if (sha256 == null && computeIfMissing) { @@ -162,7 +163,7 @@ public String getSha256(final boolean computeIfMissing) throws Exception { /** * Set the sha256 hash of content. * - * @param sha256 + * @param sha256 to set */ public void setSha256(final String sha256) { this.sha256 = sha256; diff --git a/src/main/java/gov/usgs/earthquake/product/Content.java b/src/main/java/gov/usgs/earthquake/product/Content.java index 371da1e7..965a25b2 100644 --- a/src/main/java/gov/usgs/earthquake/product/Content.java +++ b/src/main/java/gov/usgs/earthquake/product/Content.java @@ -47,6 +47,7 @@ public interface Content { * Digest of content. * * @return base64 encoded sha256 of content bytes. + * @throws Exception if error occurs */ public String getSha256() throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/product/FileContent.java b/src/main/java/gov/usgs/earthquake/product/FileContent.java index 213c5b9b..65307bb3 100644 --- a/src/main/java/gov/usgs/earthquake/product/FileContent.java +++ b/src/main/java/gov/usgs/earthquake/product/FileContent.java @@ -53,7 +53,7 @@ public class FileContent extends AbstractContent { /** * Construct a new FileContent that does not use a nested path. same as new * FileContent(file, file.getParentFile()); - * + * * @param file * the source of content. */ @@ -66,10 +66,10 @@ public FileContent(final File file) { /** * Construct a new FileContent from a URLContent for legacy products - * + * * @param urlc * the source of content. - * @throws URISyntaxException + * @throws URISyntaxException if error in URI */ public FileContent(final URLContent urlc) throws URISyntaxException { super(urlc); @@ -78,13 +78,15 @@ public FileContent(final URLContent urlc) throws URISyntaxException { /** * Convert a Content to a file backed content. - * + * * The file written is new File(baseDirectory, content.getPath()). - * + * * @param content * the content that will be converted to a file. * @param toWrite * the file where content is written. + * @throws IOException + * if IO error occurs */ public FileContent(final Content content, final File toWrite) throws IOException { @@ -146,11 +148,11 @@ public File getFile() { /** * Search a directory for files. This is equivalent to * getDirectoryContents(directory, directory). - * + * * @param directory * the directory to search. * @return a map of relative paths to FileContent objects. - * @throws IOException + * @throws IOException if IO error occurs */ public static Map getDirectoryContents( final File directory) throws IOException { @@ -161,13 +163,13 @@ public static Map getDirectoryContents( /** * Search a directory for files. The path to files relative to baseDirectory * is used as a key in the returned map. - * + * * @param directory * the directory to search. * @param baseDirectory * the directory used to compute relative paths. * @return a map of relative paths to FileContent objects. - * @throws IOException + * @throws IOException if IO error occurs */ public static Map getDirectoryContents( final File directory, final File baseDirectory) throws IOException { @@ -195,7 +197,7 @@ public static Map getDirectoryContents( /** * This implementation calls defaultGetMimeType, and exists so subclasses * can override. - * + * * @param file * file to check. * @return corresponding mime type. @@ -207,7 +209,7 @@ public String getMimeType(final File file) { /** * Check a local list of mime types, and fall back to MimetypeFileTypesMap * if not specified. - * + * * @param file * file to check. * @return corresponding mime type. diff --git a/src/main/java/gov/usgs/earthquake/product/InputStreamContent.java b/src/main/java/gov/usgs/earthquake/product/InputStreamContent.java index 3def800a..30eae3b6 100644 --- a/src/main/java/gov/usgs/earthquake/product/InputStreamContent.java +++ b/src/main/java/gov/usgs/earthquake/product/InputStreamContent.java @@ -32,6 +32,8 @@ public InputStreamContent(final InputStream content) { * * @param content * the content to duplicate. + * @throws IOException + * if IO error occurs */ public InputStreamContent(final Content content) throws IOException { super(content); diff --git a/src/main/java/gov/usgs/earthquake/product/InvalidProductException.java b/src/main/java/gov/usgs/earthquake/product/InvalidProductException.java index db7bc022..943ff144 100644 --- a/src/main/java/gov/usgs/earthquake/product/InvalidProductException.java +++ b/src/main/java/gov/usgs/earthquake/product/InvalidProductException.java @@ -4,18 +4,32 @@ public class InvalidProductException extends Exception { private static final long serialVersionUID = 0x2943A1B7; + /** Generic Invalid Product exception constructor */ public InvalidProductException() { super(); } - + + /** + * Exception taking in a message + * @param message Message relating to exception + */ public InvalidProductException(String message) { super(message); } - + + /** + * Exception taking in a message, cause + * @param message Message relating to exception + * @param cause throwable relating to exception + */ public InvalidProductException(String message, Throwable cause) { super(message, cause); } - + + /** + * Exception taking in a cause + * @param cause throwable relating to exception + */ public InvalidProductException(Throwable cause) { } } diff --git a/src/main/java/gov/usgs/earthquake/product/Product.java b/src/main/java/gov/usgs/earthquake/product/Product.java index 782257e6..da00c681 100644 --- a/src/main/java/gov/usgs/earthquake/product/Product.java +++ b/src/main/java/gov/usgs/earthquake/product/Product.java @@ -103,13 +103,21 @@ public class Product { /** The status message when a product is being deleted. */ public static final String STATUS_DELETE = "DELETE"; + /** Property for eventsource */ public static final String EVENTSOURCE_PROPERTY = "eventsource"; + /** Property for eventsourcecode */ public static final String EVENTSOURCECODE_PROPERTY = "eventsourcecode"; + /** Property for eventtime */ public static final String EVENTTIME_PROPERTY = "eventtime"; + /** Property for magnitude */ public static final String MAGNITUDE_PROPERTY = "magnitude"; + /** Property for latitude */ public static final String LATITUDE_PROPERTY = "latitude"; + /** Property for longitude */ public static final String LONGITUDE_PROPERTY = "longitude"; + /** Property for depth */ public static final String DEPTH_PROPERTY = "depth"; + /** Property for version */ public static final String VERSION_PROPERTY = "version"; /** A unique identifier for this product. */ @@ -337,6 +345,8 @@ public void setSignatureVersion(final Version version) { /** * Sign this product using a PrivateKey and signature v1. + * @param privateKey used to sign + * @throws Exception if error occurs */ public void sign(final PrivateKey privateKey) throws Exception { this.sign(privateKey, Version.SIGNATURE_V1); @@ -349,7 +359,7 @@ public void sign(final PrivateKey privateKey) throws Exception { * a DSAPrivateKey or RSAPrivateKey. * @param version * the signature version to use. - * @throws Exception + * @throws Exception if error occurs */ public void sign(final PrivateKey privateKey, final Version version) throws Exception { setSignature(CryptoUtils.sign( @@ -361,6 +371,9 @@ public void sign(final PrivateKey privateKey, final Version version) throws Exce /** * Verify this product's signature using Signature V1. + * @param publicKeys Array of public keys to verify + * @throws Exception if error occurs + * @return true if valid, false otherwise. */ public boolean verifySignature(final PublicKey[] publicKeys) throws Exception { @@ -379,7 +392,7 @@ public boolean verifySignature(final PublicKey[] publicKeys) * @param version * the signature version to use. * @return true if valid, false otherwise. - * @throws Exception + * @throws Exception if error occurs */ public boolean verifySignature(final PublicKey[] publicKeys, final Version version) throws Exception { @@ -388,6 +401,10 @@ public boolean verifySignature(final PublicKey[] publicKeys, final Version versi /** * Try to verify using multiple candidate keys. + * @param publicKeys an array of publicKeys to test + * @param version the signature version to use. + * @return true if valid, false otherwise. + * @throws Exception if error occurs */ public PublicKey verifySignatureKey(final PublicKey[] publicKeys, final Version version) throws Exception { if (signature == null) { diff --git a/src/main/java/gov/usgs/earthquake/product/ProductDigest.java b/src/main/java/gov/usgs/earthquake/product/ProductDigest.java index ec79626e..61e2d9ae 100644 --- a/src/main/java/gov/usgs/earthquake/product/ProductDigest.java +++ b/src/main/java/gov/usgs/earthquake/product/ProductDigest.java @@ -62,7 +62,9 @@ public class ProductDigest implements ProductHandler { private Version version = null; /** - * Construct a new ProductDigest. + * Construct a new ProductDigest. + * @param version signature version + * @throws NoSuchAlgorithmException if not SHA1 or SHA-256 */ protected ProductDigest(final Version version) throws NoSuchAlgorithmException { final String algorithm = version == Version.SIGNATURE_V2 @@ -88,6 +90,13 @@ public static byte[] digestProduct(final Product product) throws Exception { return digestProduct(product, Version.SIGNATURE_V1); } + /** + * + * @param product A product + * @param version What version of product digest + * @return A byte array of the product digest + * @throws Exception if error occurs + */ public static byte[] digestProduct(final Product product, final Version version) throws Exception { Date start = new Date(); @@ -193,6 +202,11 @@ public void close() { } + /** + * CLI access into ProductDigest + * @param args CLI Args + * @throws Exception if error occurs + */ public static void main(final String[] args) throws Exception { if (args.length == 0) { System.err.println("Usage: ProductDigest FILE [FILE ...]"); diff --git a/src/main/java/gov/usgs/earthquake/product/ProductId.java b/src/main/java/gov/usgs/earthquake/product/ProductId.java index baf7910d..915d0e35 100644 --- a/src/main/java/gov/usgs/earthquake/product/ProductId.java +++ b/src/main/java/gov/usgs/earthquake/product/ProductId.java @@ -15,33 +15,33 @@ *
    * The organization sending the product; * not necessarily the author of the product. - * + * * Typically a FDSN network code. *
    - * + * *
    Type
    *
    * The type of product being sent. *
    - * + * *
    Code
    *
    * A unique code assigned by the source and type. * Source and Type are effectively a namespace for codes. - * + * * If the same code is re-used, it indicates a different * version of the same product. *
    - * + * *
    Update Time
    *
    * A timestamp representing when a product was created. - * + * * Update Time is also used as a version. * Products from the same source and type with * the same code are considered different versions of the * same product. - * + * * More recent (newer) updateTimes * supersede less recent (older) updateTimes. *
    @@ -63,8 +63,14 @@ public class ProductId implements Comparable { /** * Create a new ProductId. - * + * * Same as new ProductId(type, code, source, new Date()). + * @param source + * the product source. + * @param type + * the product type. + * @param code + * the product code. */ public ProductId(final String source, final String type, final String code) { this(source, type, code, new Date()); @@ -72,7 +78,7 @@ public ProductId(final String source, final String type, final String code) { /** * Create a new ProductId. - * + * * @param source * the product source. * @param type @@ -153,7 +159,7 @@ public void setUpdateTime(Date updateTime) { /** * Convert this product id to a string. This string does not include the * update time. - * + * * @return a product id string. */ public String toString() { @@ -163,7 +169,7 @@ public String toString() { /** * Parse a product id string. - * + * * @param str * a valid product id string. * @return a ProductId object. @@ -196,7 +202,7 @@ public boolean equals(final Object obj) { /** * Implement the Comparable interface. - * + * * @param that * product id being compared. * @return -1 if this precedes that, 0 if same, and 1 if that precedes this. @@ -224,10 +230,10 @@ public int hashCode() { /** * Whether these are the same product, even if they are different versions. - * + * * It is possible for isSameProduct to return true if equals returns false, * but if equals returns true isSameProduct will also return true. - * + * * @param that * a ProductId to test. * @return true if these are the same product (source,type,code), false @@ -244,7 +250,7 @@ && getCode().equals(that.getCode())) { /** * Escape id parts so they do not interfere with formatting/parsing. - * + * * @param part * part to escape. * @return escaped part. diff --git a/src/main/java/gov/usgs/earthquake/product/URLContent.java b/src/main/java/gov/usgs/earthquake/product/URLContent.java index 065d2b38..a7cd1d12 100644 --- a/src/main/java/gov/usgs/earthquake/product/URLContent.java +++ b/src/main/java/gov/usgs/earthquake/product/URLContent.java @@ -30,7 +30,7 @@ public class URLContent extends AbstractContent { * * @param content * the content available at a URL. - * @throws URISyntaxException + * @throws URISyntaxException on URI error */ public URLContent(final URL content) throws URISyntaxException { this.setContentType(MIME_TYPES.getContentType(content.toURI() @@ -43,6 +43,7 @@ public URLContent(final URL content) throws URISyntaxException { * * @param fc * the file content. + * @throws MalformedURLException if URL error */ public URLContent(final FileContent fc) throws MalformedURLException { super(fc); @@ -51,6 +52,7 @@ public URLContent(final FileContent fc) throws MalformedURLException { /** * @return an InputStream for the wrapped content. + * @throws IOException on IO error */ public InputStream getInputStream() throws IOException { return StreamUtils.getURLInputStream(content); diff --git a/src/main/java/gov/usgs/earthquake/product/io/BinaryIO.java b/src/main/java/gov/usgs/earthquake/product/io/BinaryIO.java index 39b2e59a..1d300b6b 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/BinaryIO.java +++ b/src/main/java/gov/usgs/earthquake/product/io/BinaryIO.java @@ -11,16 +11,34 @@ public class BinaryIO { + /** + * Writes an int to the OutputStream buffer + * @param in an int to write + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeInt(final int in, final OutputStream out) throws IOException { out.write(ByteBuffer.allocate(4).putInt(in).array()); } + /** + * Writes an long to the OutputStream buffer + * @param in an long to write + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeLong(final long in, final OutputStream out) throws IOException { out.write(ByteBuffer.allocate(8).putLong(in).array()); } + /** + * Writes an array of bytes to the OutputStream buffer + * @param toWrite an array of bytes to write + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeBytes(final byte[] toWrite, final OutputStream out) throws IOException { // length of string @@ -29,16 +47,35 @@ public void writeBytes(final byte[] toWrite, final OutputStream out) out.write(toWrite); } + /** + * Writes a string to the OutputStream buffer + * @param toWrite a string to write + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeString(final String toWrite, final OutputStream out) throws IOException { writeBytes(toWrite.getBytes(StandardCharsets.UTF_8), out); } + /** + * Writes a date to the OutputStream buffer + * @param toWrite a date to write + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeDate(final Date toWrite, final OutputStream out) throws IOException { writeLong(toWrite.getTime(), out); } + /** + * Writes a long to the OutputStream buffer + * @param length a long to write + * @param in an input stream + * @param out the OutputStream + * @throws IOException if IO error occurs + */ public void writeStream(final long length, final InputStream in, final OutputStream out) throws IOException { writeLong(length, out); @@ -52,18 +89,36 @@ public void writeStream(final long length, final InputStream in, } } + /** + * Reads 4 bytes from the InputStream + * @param in InputStream + * @return an int + * @throws IOException if IO Error occurs + */ public int readInt(final InputStream in) throws IOException { byte[] buffer = new byte[4]; readFully(buffer, in); return ByteBuffer.wrap(buffer).getInt(); } + /** + * Reads 8 bytes from the InputStream + * @param in InputStream + * @return a long + * @throws IOException if IO Error occurs + */ public long readLong(final InputStream in) throws IOException { byte[] buffer = new byte[8]; readFully(buffer, in); return ByteBuffer.wrap(buffer).getLong(); } + /** + * Reads a byte array from the InputStream + * @param in InputStream + * @return Byte[] + * @throws IOException if IO Error occurs + */ public byte[] readBytes(final InputStream in) throws IOException { int length = readInt(in); byte[] buffer = new byte[length]; @@ -72,10 +127,23 @@ public byte[] readBytes(final InputStream in) throws IOException { } + /** + * Reads string from the InputStream + * @param in InputStream + * @return a string + * @throws IOException if IO Error occurs + */ public String readString(final InputStream in) throws IOException { return this.readString(in, -1); } + /** + * Reads string with a max length from the InputStream + * @param in InputStream + * @param maxLength of string + * @return an string + * @throws IOException if IO Error occurs + */ public String readString(final InputStream in, final int maxLength) throws IOException { int length = readInt(in); if (maxLength > 0 && length > maxLength) { @@ -86,16 +154,36 @@ public String readString(final InputStream in, final int maxLength) throws IOExc return new String(buffer, StandardCharsets.UTF_8); } + /** + * Reads date from the InputStream + * @param in InputStream + * @return a date + * @throws IOException if IO Error occurs + */ public Date readDate(final InputStream in) throws IOException { return new Date(readLong(in)); } + /** + * Reads stream + * @param in InputStream + * @param out OutputStream + * @throws IOException if IO Error occurs + */ public void readStream(final InputStream in, final OutputStream out) throws IOException { long length = readLong(in); readStream(length, in, out); } + /** + * Function called by previous readStream + * Used to read whole stream + * @param length length of inputstream + * @param in input stream + * @param out output stream + * @throws IOException if io error occurs + */ public void readStream(final long length, final InputStream in, final OutputStream out) throws IOException { long remaining = length; @@ -124,6 +212,13 @@ public void readStream(final long length, final InputStream in, } } + /** + * Function used by other read funcs + * Reads from input stream until buffer is full + * @param buffer byte[] + * @param in inputstream + * @throws IOException if IO error occurs + */ protected void readFully(final byte[] buffer, final InputStream in) throws IOException { int length = buffer.length; diff --git a/src/main/java/gov/usgs/earthquake/product/io/BinaryProductHandler.java b/src/main/java/gov/usgs/earthquake/product/io/BinaryProductHandler.java index 619cf6a6..81cea4e7 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/BinaryProductHandler.java +++ b/src/main/java/gov/usgs/earthquake/product/io/BinaryProductHandler.java @@ -96,17 +96,28 @@ */ public class BinaryProductHandler implements ProductHandler { + /** HEADER - BEGINPRODUCT */ public static final String HEADER = "BEGINPRODUCT"; + /** PROPERTY */ public static final String PROPERTY = "PROPERTY"; + /** LINK */ public static final String LINK = "LINK"; + /** CONTENT */ public static final String CONTENT = "CONTENT"; + /** SIGNATURE VERSION */ public static final String SIGNATUREVERSION = "SIGNATUREVERSION"; + /** SIGNATURE */ public static final String SIGNATURE = "SIGNATURE"; + /** ENDPRODUCT */ public static final String FOOTER = "ENDPRODUCT"; private OutputStream out; private BinaryIO io; + /** + * Constructor. Sets up a new BinaryIO + * @param out an OutputStream + */ public BinaryProductHandler(final OutputStream out) { this.out = out; this.io = new BinaryIO(); diff --git a/src/main/java/gov/usgs/earthquake/product/io/BinaryProductSource.java b/src/main/java/gov/usgs/earthquake/product/io/BinaryProductSource.java index 34fca1ee..af5e209b 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/BinaryProductSource.java +++ b/src/main/java/gov/usgs/earthquake/product/io/BinaryProductSource.java @@ -24,6 +24,10 @@ public class BinaryProductSource implements ProductSource { /** binary io utility. */ private BinaryIO io; + /** + * Constructor. Sets up a new BinaryIO + * @param in an InputStream + */ public BinaryProductSource(final InputStream in) { this.in = in; this.io = new BinaryIO(); diff --git a/src/main/java/gov/usgs/earthquake/product/io/BinaryXmlIOComparison.java b/src/main/java/gov/usgs/earthquake/product/io/BinaryXmlIOComparison.java index 6a1f4f2e..18e2886c 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/BinaryXmlIOComparison.java +++ b/src/main/java/gov/usgs/earthquake/product/io/BinaryXmlIOComparison.java @@ -9,12 +9,19 @@ /** * Compare io times of XML and Binary product formats. - * + * * All conversion is done in memory to try to balance the tests. All writes use * a BinaryProductSource to keep the playing field level. */ public class BinaryXmlIOComparison { + /** + * Serializes product by streaming it to a handler + * @param source a productSource + * @param handler a productHandler + * @return Time it took to stream source to handler + * @throws Exception if error occurs + */ public static long timeSerializeProduct(final ProductSource source, final ProductHandler handler) throws Exception { Date start = new Date(); @@ -23,6 +30,11 @@ public static long timeSerializeProduct(final ProductSource source, return end.getTime() - start.getTime(); } + /** + * Testing for class + * @param args CLI args + * @throws Exception if error occurs + */ public static void main(final String[] args) throws Exception { int numRuns = 10; testProductIO( @@ -42,6 +54,12 @@ public static void main(final String[] args) throws Exception { numRuns); } + /** + * Tests product IO + * @param product Produc + * @param numRuns int + * @throws Exception if error occurs + */ public static void testProductIO(final Product product, int numRuns) throws Exception { System.err.println(product.getId().toString()); @@ -52,6 +70,12 @@ public static void testProductIO(final Product product, int numRuns) System.err.println(); } + /** + * Tests XML reading + * @param product a product + * @param numReads int + * @throws Exception if error occurs + */ public static void testXmlReads(final Product product, int numReads) throws Exception { // read product into memory @@ -76,6 +100,12 @@ public static void testXmlReads(final Product product, int numReads) + numReads + ",\tread average=" + ((double) time / numReads)); } + /** + * Tests binary reading + * @param product a product + * @param numReads int + * @throws Exception if error occurs + */ public static void testBinaryReads(final Product product, int numReads) throws Exception { // read product into memory @@ -101,6 +131,12 @@ public static void testBinaryReads(final Product product, int numReads) + numReads + ",\tread average=" + ((double) time / numReads)); } + /** + * Tests binary writes + * @param product a product + * @param numWrites int + * @throws Exception if error occurs + */ public static void testBinaryWrites(final Product product, int numWrites) throws Exception { // read product into memory @@ -128,6 +164,12 @@ public static void testBinaryWrites(final Product product, int numWrites) + ((double) time / numWrites)); } + /** + * tests xml writes + * @param product a product + * @param numWrites int + * @throws Exception if error occurs + */ public static void testXmlWrites(final Product product, int numWrites) throws Exception { // read product into memory diff --git a/src/main/java/gov/usgs/earthquake/product/io/ContentOutputThread.java b/src/main/java/gov/usgs/earthquake/product/io/ContentOutputThread.java index c641324b..adf226b8 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/ContentOutputThread.java +++ b/src/main/java/gov/usgs/earthquake/product/io/ContentOutputThread.java @@ -19,6 +19,13 @@ public class ContentOutputThread extends Thread { private final String path; private final Content content; + /** + * Constructor + * @param handler A product handler + * @param id A product ID + * @param path String path + * @param content Content + */ public ContentOutputThread(final ProductHandler handler, final ProductId id, final String path, final Content content) { this.handler = handler; diff --git a/src/main/java/gov/usgs/earthquake/product/io/IOUtil.java b/src/main/java/gov/usgs/earthquake/product/io/IOUtil.java index 20427bf8..499dfcd8 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/IOUtil.java +++ b/src/main/java/gov/usgs/earthquake/product/io/IOUtil.java @@ -14,17 +14,32 @@ */ public class IOUtil { + /** Argument for input file */ public static final String INFILE_ARGUMENT = "--infile="; + /** Argument for input format */ public static final String INFORMAT_ARGUMENT = "--informat="; + /** Argument for output file */ public static final String OUTFILE_ARGUMENT = "--outfile="; + /** Argument for output format */ public static final String OUTFORMAT_ARGUMENT = "--outformat="; + /** Zip format */ public static final String ZIP_FORMAT = "zip"; + /** XML format */ public static final String XML_FORMAT = "xml"; + /** Directory format */ public static final String DIRECTORY_FORMAT = "directory"; + /** Binary format */ public static final String BINARY_FORMAT = "binary"; + /** + * Returns a ProductHandler based on the output format + * @param outformat Output format + * @param outfile Output file + * @return a Product Handler + * @throws IOException if IO error occurs + */ public static ProductHandler getProductHandler(final String outformat, final File outfile) throws IOException { ProductHandler out = null; @@ -43,6 +58,14 @@ public static ProductHandler getProductHandler(final String outformat, return out; } + /** + * Returns a product source based on input format + * @param informat input file format + * @param infile input file + * @return a Productsource + * @throws IllegalArgumentException if informat argument error + * @throws IOException if error occurs + */ public static ProductSource getProductSource(final String informat, final File infile) throws IllegalArgumentException, IOException { ProductSource in = null; @@ -63,7 +86,7 @@ public static ProductSource getProductSource(final String informat, /** * Auto detect an Xml or Binary product source, that is optionally deflated. - * + * * @param in * input stream containing optionally deflated xml or binary * product stream. @@ -96,7 +119,7 @@ public static ProductSource autoDetectProductSource(final InputStream in) /** * Auto detect an optionally deflated stream. - * + * * @param in * input stream containing optionally deflated xml or binary * product stream. @@ -125,6 +148,13 @@ public static BufferedInputStream autoDetectDeflate(final InputStream in) return bufferedIn; } + /** + * Access into IOUtil + * Takes arguments, gets product source and handler + * Streams source to handler + * @param args CLI args for infile, informat, outfile, outformat + * @throws Exception if error occurs + */ public static void main(final String[] args) throws Exception { File infile = null; File outfile = null; @@ -159,6 +189,7 @@ public static void main(final String[] args) throws Exception { in.streamTo(out); } + /** CLI usage */ public static void printUsage() { System.err .println("IOUtil --infile=FILE --informat=(xml|directory|zip|binary) --outfile=FILE --outformat=(xml|directory|zip|binary)"); diff --git a/src/main/java/gov/usgs/earthquake/product/io/JsonProduct.java b/src/main/java/gov/usgs/earthquake/product/io/JsonProduct.java index 20d3676f..beed5714 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/JsonProduct.java +++ b/src/main/java/gov/usgs/earthquake/product/io/JsonProduct.java @@ -36,9 +36,9 @@ public class JsonProduct { /** * Convert product object to json. * - * @param product - * @return - * @throws Exception + * @param product a product + * @return a json object + * @throws Exception if error occurs */ public JsonObject getJsonObject(final Product product) throws Exception { JsonObjectBuilder json = Json.createObjectBuilder(); @@ -67,6 +67,9 @@ public JsonObject getJsonObject(final Product product) throws Exception { /** * Convert json object to product. + * @param json a json object + * @return a product + * @throws Exception if error occurs */ public Product getProduct(final JsonObject json) throws Exception { Product product = new Product(getId(json.getJsonObject("id"))); @@ -87,9 +90,9 @@ public Product getProduct(final JsonObject json) throws Exception { /** * Convert contents map to json. * - * @param contents - * @return - * @throws Exception + * @param contents contents map + * @return JSOnArrayBuilder + * @throws Exception if error occurs */ public JsonArrayBuilder getContentsJson(final Map contents) throws Exception { final JsonArrayBuilder builder = Json.createArrayBuilder(); @@ -125,9 +128,9 @@ public JsonArrayBuilder getContentsJson(final Map contents) thr /** * Convert contents json to map. * - * @param json - * @return - * @throws Exception + * @param json JsonArray + * @return Contents map + * @throws Exception if error occurs */ public Map getContents(final JsonArray json) throws Exception { Map contents = new HashMap(); @@ -153,9 +156,9 @@ public Map getContents(final JsonArray json) throws Exception { /** * Create json geometry from product properties. * - * @param product - * @return - * @throws Exception + * @param product a product + * @return JSON geometry via JsonObjectBuilder + * @throws Exception if error occurs */ public JsonObjectBuilder getGeometryJson(final Product product) throws Exception { final BigDecimal latitude = product.getLatitude(); @@ -188,9 +191,9 @@ public JsonObjectBuilder getGeometryJson(final Product product) throws Exception /** * Convert json id to ProductId object. * - * @param json - * @return - * @throws Exception + * @param json A JsonObject ID + * @return a productId + * @throws Exception if error occurs */ public ProductId getId(final JsonObject json) throws Exception { final String code = json.getString("code"); @@ -202,9 +205,9 @@ public ProductId getId(final JsonObject json) throws Exception { /** * Convert ProductId to json object. - * @param id - * @return - * @throws Exception + * @param id A ProductId + * @return JsonObjectBuilder + * @throws Exception if error occurs */ public JsonObjectBuilder getIdJson(final ProductId id) throws Exception { return Json.createObjectBuilder() @@ -216,9 +219,9 @@ public JsonObjectBuilder getIdJson(final ProductId id) throws Exception { /** * Convert json links to map. - * @param json - * @return - * @throws Exception + * @param json a Jsonarray + * @return a Map of links + * @throws Exception if error occurs */ public Map> getLinks(final JsonArray json) throws Exception { final Map> links = new HashMap>(); @@ -239,9 +242,9 @@ public Map> getLinks(final JsonArray json) throws Exception { /** * Convert links map to json. * - * @param links - * @return - * @throws Exception + * @param links map + * @return JsonArray of JsonArrayBuilder + * @throws Exception if error occurs */ public JsonArrayBuilder getLinksJson(final Map> links) throws Exception { final JsonArrayBuilder builder = Json.createArrayBuilder(); @@ -257,9 +260,9 @@ public JsonArrayBuilder getLinksJson(final Map> links) throws /** * Convert properties json to map. - * @param json - * @return - * @throws Exception + * @param json JsonObject properties + * @return A map + * @throws Exception if error occurs */ public Map getProperties(final JsonObject json) throws Exception { final Map properties = new HashMap(); @@ -272,9 +275,9 @@ public Map getProperties(final JsonObject json) throws Exception /** * Convert properties map to json. * - * @param properties - * @return - * @throws Exception + * @param properties Map of properties + * @return JsonObjectBuilder + * @throws Exception if error occurs */ public JsonObjectBuilder getPropertiesJson(final Map properties) throws Exception { diff --git a/src/main/java/gov/usgs/earthquake/product/io/ObjectProductHandler.java b/src/main/java/gov/usgs/earthquake/product/io/ObjectProductHandler.java index 07c47d1e..a2167661 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/ObjectProductHandler.java +++ b/src/main/java/gov/usgs/earthquake/product/io/ObjectProductHandler.java @@ -35,11 +35,13 @@ public class ObjectProductHandler implements ProductHandler { /** Whether onEndProduct has been called yet. */ private boolean complete = false; + /** Empty constructor */ public ObjectProductHandler() { } /** * @return the product object that was created. + * @throws Exception if error occurs */ public Product getProduct() throws Exception { if (product == null) { @@ -181,6 +183,7 @@ public void onSignature(final ProductId id, final String signature) * @param in * the ProductInput to read. * @return the Product read, or null if errors occur. + * @throws Exception if error occurs */ public static Product getProduct(final ProductSource in) throws Exception { ObjectProductHandler out = new ObjectProductHandler(); diff --git a/src/main/java/gov/usgs/earthquake/product/io/ObjectProductSource.java b/src/main/java/gov/usgs/earthquake/product/io/ObjectProductSource.java index ea6ef6b8..4ee637d7 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/ObjectProductSource.java +++ b/src/main/java/gov/usgs/earthquake/product/io/ObjectProductSource.java @@ -102,7 +102,9 @@ public void sendProperties(final ProductHandler out) throws Exception { * order by relation name, by URI. * * @param out + * the receiving ProductOutput. * @throws Exception + * if out.onProperty throws an Exception. */ public void sendLinks(final ProductHandler out) throws Exception { ProductId id = product.getId(); diff --git a/src/main/java/gov/usgs/earthquake/product/io/ProductHandler.java b/src/main/java/gov/usgs/earthquake/product/io/ProductHandler.java index bd82dafb..97cb3a61 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/ProductHandler.java +++ b/src/main/java/gov/usgs/earthquake/product/io/ProductHandler.java @@ -41,6 +41,8 @@ public interface ProductHandler { * the product's status. * @param trackerURL * a location to send status updates. + * @throws Exception + * if error occurs */ public void onBeginProduct(final ProductId id, final String status, final URL trackerURL) throws Exception; @@ -54,6 +56,8 @@ public void onBeginProduct(final ProductId id, final String status, * the property name. * @param value * the property value. + * @throws Exception + * if error occurs */ public void onProperty(final ProductId id, final String name, final String value) throws Exception; @@ -67,6 +71,8 @@ public void onProperty(final ProductId id, final String name, * how the URI is related to this product. * @param href * the URI that is related to this product. + * @throws Exception + * if error occurs */ public void onLink(final ProductId id, final String relation, final URI href) throws Exception; @@ -80,12 +86,21 @@ public void onLink(final ProductId id, final String relation, final URI href) * path to content within product. * @param content * the product content. + * @throws Exception + * if error occurs */ public void onContent(final ProductId id, final String path, final Content content) throws Exception; /** * Product signature version. + * + * @param id + * which product. + * @param version + * product version + * @throws Exception + * if error occurs */ public void onSignatureVersion(final ProductId id, final Version version) throws Exception; @@ -99,6 +114,8 @@ public void onSignatureVersion(final ProductId id, final Version version) * @param signature * the product signature, which can be verified using the * ProductSigner class. + * @throws Exception + * if error occurs */ public void onSignature(final ProductId id, final String signature) throws Exception; @@ -110,6 +127,8 @@ public void onSignature(final ProductId id, final String signature) * * @param id * which product. + * @throws Exception + * if error occurs */ public void onEndProduct(final ProductId id) throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/product/io/ProductSource.java b/src/main/java/gov/usgs/earthquake/product/io/ProductSource.java index 195db098..ea74801e 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/ProductSource.java +++ b/src/main/java/gov/usgs/earthquake/product/io/ProductSource.java @@ -5,11 +5,11 @@ /** * A Source of Product events. - * + * * ProductSources are used to read Products from other formats like XML. * ProductSources send a stream of events to ProductOutputs and provide stream * like processing for Products. - * + * * ProductSources should strive to call ProductOutput methods in the following * order: *
      @@ -25,9 +25,10 @@ public interface ProductSource { /** * Send a product to the ProductOutput. - * + * * @param out * the output that will receive the product. + * @throws Exception if error occurs */ public void streamTo(final ProductHandler out) throws Exception; diff --git a/src/main/java/gov/usgs/earthquake/product/io/XmlProductHandler.java b/src/main/java/gov/usgs/earthquake/product/io/XmlProductHandler.java index 17ba8248..edaed279 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/XmlProductHandler.java +++ b/src/main/java/gov/usgs/earthquake/product/io/XmlProductHandler.java @@ -22,33 +22,54 @@ */ public class XmlProductHandler implements ProductHandler { + /** Declaration for XML and version */ public static final String XML_DECLARATION = "\n"; + /** Namespace for XML product */ public static final String PRODUCT_XML_NAMESPACE = "http://earthquake.usgs.gov/distribution/product"; + /** Element for product */ public static final String PRODUCT_ELEMENT = "product"; + /** Product Attribute for id */ public static final String PRODUCT_ATTRIBUTE_ID = "id"; + /** Product Attribute for updateTime */ public static final String PRODUCT_ATTRIBUTE_UPDATED = "updateTime"; + /** Product Attribute for status */ public static final String PRODUCT_ATTRIBUTE_STATUS = "status"; + /** Product Attribute for trackerURL */ public static final String PRODUCT_ATTRIBUTE_TRACKER_URL = "trackerURL"; + /** Element for property */ public static final String PROPERTY_ELEMENT = "property"; + /** Property attribute for name */ public static final String PROPERTY_ATTRIBUTE_NAME = "name"; + /** Property attribute for value */ public static final String PROPERTY_ATTRIBUTE_VALUE = "value"; + /** Element for link */ public static final String LINK_ELEMENT = "link"; + /** Link attribute for relation */ public static final String LINK_ATTRIBUTE_RELATION = "rel"; + /** Link attribute for href */ public static final String LINK_ATTRIBUTE_HREF = "href"; + /** Element for content */ public static final String CONTENT_ELEMENT = "content"; + /** Content attribute for path */ public static final String CONTENT_ATTRIBUTE_PATH = "path"; + /** Content attribute for type */ public static final String CONTENT_ATTRIBUTE_TYPE = "type"; + /** Content attribute for length */ public static final String CONTENT_ATTRIBUTE_LENGTH = "length"; + /** Content attribute for modified */ public static final String CONTENT_ATTRIBUTE_MODIFIED = "modified"; /** Used with URLContent. */ public static final String CONTENT_ATTRIBUTE_HREF = "href"; + /** Content attribute for encoded */ public static final String CONTENT_ATTRIBUTE_ENCODED = "encoded"; + /** Element for signature */ public static final String SIGNATURE_ELEMENT = "signature"; + /** Signature attribute for version */ public static final String SIGNATURE_ATTRIBUTE_VERSION = "version"; /** The OutputStream where xml is written. */ diff --git a/src/main/java/gov/usgs/earthquake/product/io/XmlProductSource.java b/src/main/java/gov/usgs/earthquake/product/io/XmlProductSource.java index b03f5f23..80fb3051 100644 --- a/src/main/java/gov/usgs/earthquake/product/io/XmlProductSource.java +++ b/src/main/java/gov/usgs/earthquake/product/io/XmlProductSource.java @@ -304,10 +304,12 @@ public synchronized void characters(final char[] ch, final int start, } } + /** @return ProductHandler */ protected synchronized ProductHandler getHandler() { return out; } + /** @param out ProductHandler to set */ protected synchronized void setHandler(ProductHandler out) { this.out = out; } @@ -337,6 +339,10 @@ public void close() { * will close the connection in {@link #closeContent()}. If * errors occur, the objects handling the product source object * call closeContent to ensure the resource is closed. + * + * @param encoded if it needs to decode base 64 content + * @return a input stream of the Piped output stream + * @throws IOException if io error occurs */ @SuppressWarnings("resource") public InputStream openContentStream(boolean encoded) throws IOException { @@ -357,6 +363,9 @@ public InputStream openContentStream(boolean encoded) throws IOException { return contentInputStream; } + /** + * Closes an open output stream + */ public void closeContent() { StreamUtils.closeStream(contentOutputStream); contentOutputStream = null; diff --git a/src/main/java/gov/usgs/earthquake/qdm/Point.java b/src/main/java/gov/usgs/earthquake/qdm/Point.java index 31b5fba1..56e3b70d 100644 --- a/src/main/java/gov/usgs/earthquake/qdm/Point.java +++ b/src/main/java/gov/usgs/earthquake/qdm/Point.java @@ -7,9 +7,16 @@ */ public class Point { + /** A double for x position */ public double x; + /** A double for y position */ public double y; + /** + * Constructor + * @param x double x pos + * @param y double y pos + */ public Point(double x, double y) { this.x = x; this.y = y; diff --git a/src/main/java/gov/usgs/earthquake/qdm/Region.java b/src/main/java/gov/usgs/earthquake/qdm/Region.java index e9f1a412..2e1aa985 100644 --- a/src/main/java/gov/usgs/earthquake/qdm/Region.java +++ b/src/main/java/gov/usgs/earthquake/qdm/Region.java @@ -4,17 +4,25 @@ /** * A polygon without holes. - * + * * Points are assumed to use x=longitude, y=latitude. * A "default" region has no boundary points, and contains all points. */ public class Region { + /** String for net id */ public String netid; + /** String for region id */ public String regionid; + /** Arraylist of points */ public ArrayList points; + /** + * Region constructor + * @param netid string + * @param regionid string + */ public Region(String netid, String regionid) { this.netid = netid; this.regionid = regionid; @@ -25,6 +33,9 @@ public Region(String netid, String regionid) { * Method to determine if this lat-lon in this region? In or out algorithm taken * from an algorithm by Edwards and Coleman of Oak Ridge Lab, version for BNL by * Benkovitz translated to C by Andy Michael and into Java by Alan Jones. + * + * @param xy point + * @return bool if point is in region */ public boolean inpoly(Point xy) { int in; diff --git a/src/main/java/gov/usgs/earthquake/qdm/Regions.java b/src/main/java/gov/usgs/earthquake/qdm/Regions.java index 8fbc4cd0..c27eabf1 100644 --- a/src/main/java/gov/usgs/earthquake/qdm/Regions.java +++ b/src/main/java/gov/usgs/earthquake/qdm/Regions.java @@ -18,9 +18,12 @@ */ public class Regions { - public String defaultNetid; // Default network - public ArrayList netids; // Array of network ids, e.g. nc, us, etc. - public ArrayList regions; // Array of regions + /** Default network */ + public String defaultNetid; + /** Array of network ids, e.g. nc, us, etc. */ + public ArrayList netids; + /** Array of regions */ + public ArrayList regions; /** * Create a new set of regions. @@ -34,6 +37,9 @@ public Regions() { /** * Is this netid in the set of regions? The default net covers the whole world * so it is always valid since it has no finite boundaries. + * + * @param netid A netid (nc, us, etc.) + * @return boolean if netid is valid */ public boolean isValidnetID(final String netid) { for (String i : this.netids) { diff --git a/src/main/java/gov/usgs/earthquake/qdm/RegionsHandler.java b/src/main/java/gov/usgs/earthquake/qdm/RegionsHandler.java index 001bb1af..b6325035 100644 --- a/src/main/java/gov/usgs/earthquake/qdm/RegionsHandler.java +++ b/src/main/java/gov/usgs/earthquake/qdm/RegionsHandler.java @@ -12,7 +12,7 @@ /** * XML SAX Handler for ANSS "regions.xml". - * + * * See the resource file etc/config/regions.xml * * Example: @@ -29,20 +29,21 @@ */ public class RegionsHandler extends SAXAdapter { + /** Logger object */ public static final Logger LOGGER = Logger.getLogger(RegionsHandler.class.getName()); - // the regions that have been parsed + /** the regions that have been parsed */ public Regions regions = new Regions(); - // update timestamp + /** update timestamp */ public Date updated = null; - // reported format version (no version-specific logic implemented) + /** reported format version (no version-specific logic implemented) */ public String formatVersion = null; - + // variables for tracking state private boolean inRegions = false; private String netid = null; private Region region = null; - + /** * Start Element handler. * @@ -94,7 +95,7 @@ public void onStartElement(final String uri, final String localName, /** * End element handler. - * + * * Adds built region objects to regions object. * * @param uri namespace of element. diff --git a/src/main/java/gov/usgs/earthquake/shakemap/GridXMLHandler.java b/src/main/java/gov/usgs/earthquake/shakemap/GridXMLHandler.java index 8d84b3e7..f671decf 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/GridXMLHandler.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/GridXMLHandler.java @@ -10,68 +10,113 @@ /** * Parser for ShakeMap grid.xml metadata. - * + * * Accepts a ShakeMap object and updates the properties of that product based on * the product's grid.xml file. */ public class GridXMLHandler extends DefaultHandler { - + // ShakeMap grid parameters + /** Element for shakemap grid */ public static final String SHAKEMAPGRID_ELEMENT = "shakemap_grid"; + /** Shakemap grid id */ public static final String SHAKEMAPGRID_ID = "shakemap_id"; + /** Shakemap grid originator */ public static final String SHAKEMAPGRID_ORIGINATOR = "shakemap_originator"; + /** Shakemap grid process timestamp */ public static final String SHAKEMAPGRID_TIMESTAMP = "process_timestamp"; + /** Shakemap grid version */ public static final String SHAKEMAPGRID_VERSION = "shakemap_version"; + /** Shakemap grid event type */ public static final String SHAKEMAPGRID_EVENT_TYPE = "shakemap_event_type"; + /** Shakemap grid event/map status */ public static final String SHAKEMAPGRID_EVENT_STATUS = "map_status"; // ShakeMap event parameters + /** Element for event */ public static final String EVENT_ELEMENT = "event"; + /** Event latitude */ public static final String EVENT_LATITUDE = "lat"; + /** Event longitude */ public static final String EVENT_LONGITUDE = "lon"; + /** Event magnitude */ public static final String EVENT_MAGNITUDE = "magnitude"; + /** Event timestamp */ public static final String EVENT_TIMESTAMP = "event_timestamp"; + /** Event description */ public static final String EVENT_DESCRIPTION = "event_description"; + /** Event depth */ public static final String EVENT_DEPTH = "depth"; + // These are new parameters used by GSM when it is contributing to a // different // network as a backup + /** GSM Parameter when using a different network as a backup */ public static final String EVENT_NETWORK = "event_network"; + /** GSM Parameter when using a different network as a backup */ public static final String EVENT_ID = "event_id"; - + // ShakeMap gridspec parameters + /** Element for grid specification */ public static final String GRIDSPEC_ELEMENT = "grid_specification"; + /** gridspec longitude min */ public static final String GRIDSPEC_LONMIN = "lon_min"; + /** gridspec longitude max */ public static final String GRIDSPEC_LONMAX = "lon_max"; + /** gridspec latitude min */ public static final String GRIDSPEC_LATMIN = "lat_min"; + /** gridspec latitude max */ public static final String GRIDSPEC_LATMAX = "lat_max"; - + + /** XML for SHAKEMAPGRID_ELEMENT */ public static final String SHAKEMAPGRID_ELEMENT_XML = SHAKEMAPGRID_ELEMENT; + /** XML for SHAKEMAPGRID_ID */ public static final String SHAKEMAPGRID_ID_XML = SHAKEMAPGRID_ELEMENT+ "[" + SHAKEMAPGRID_ID + "]"; + /** XML for SHAKEMAPGRID_ORIGINATOR */ public static final String SHAKEMAPGRID_ORIGINATOR_XML = SHAKEMAPGRID_ELEMENT + "[" + SHAKEMAPGRID_ORIGINATOR + "]"; + /** XML for SHAKEMAPGRID_TIMESTAMP */ public static final String SHAKEMAPGRID_TIMESTAMP_XML = SHAKEMAPGRID_ELEMENT + "[" + SHAKEMAPGRID_TIMESTAMP + "]"; + /** XML for SHAKEMAPGRID_VERSION */ public static final String SHAKEMAPGRID_VERSION_XML = SHAKEMAPGRID_ELEMENT+ "[" + SHAKEMAPGRID_VERSION + "]"; + /** XML for SHAKEMAPGRID_EVENT_TYPE */ public static final String SHAKEMAPGRID_EVENT_TYPE_XML = SHAKEMAPGRID_ELEMENT+ "[" + SHAKEMAPGRID_EVENT_TYPE + "]"; + /** XML for SHAKEMAPGRID_EVENT_STATUS */ public static final String SHAKEMAPGRID_EVENT_STATUS_XML = SHAKEMAPGRID_ELEMENT+ "[" + SHAKEMAPGRID_EVENT_STATUS + "]"; + /** XML for EVENT_ELEMENT */ public static final String EVENT_ELEMENT_XML = EVENT_ELEMENT; + /** XML for EVENT_LATITUDE */ public static final String EVENT_LATITUDE_XML = EVENT_ELEMENT + "[" + EVENT_LATITUDE + "]"; + /** XML for EVENT_LONGITUDE */ public static final String EVENT_LONGITUDE_XML = EVENT_ELEMENT+ "[" + EVENT_LONGITUDE + "]"; + /** XML for EVENT_MAGNITUDE */ public static final String EVENT_MAGNITUDE_XML = EVENT_ELEMENT+ "[" + EVENT_MAGNITUDE + "]"; + /** XML for EVENT_TIMESTAMP */ public static final String EVENT_TIMESTAMP_XML = EVENT_ELEMENT+ "[" + EVENT_TIMESTAMP + "]"; + /** XML for EVENT_DESCRIPTION */ public static final String EVENT_DESCRIPTION_XML = EVENT_ELEMENT+ "[" + EVENT_DESCRIPTION + "]"; + /** XML for EVENT_DEPTH */ public static final String EVENT_DEPTH_XML = EVENT_ELEMENT+ "[" + EVENT_DEPTH + "]"; + /** XML for EVENT_NETWORK */ public static final String EVENT_NETWORK_XML = EVENT_ELEMENT + "[" + EVENT_NETWORK + "]"; + /** XML for EVENT_ID */ public static final String EVENT_ID_XML = EVENT_ELEMENT + "[" + EVENT_ID + "]"; - + + /** XML for GRIDSPEC_ELEMENT */ public static final String GRIDSPEC_ELEMENT_XML = GRIDSPEC_ELEMENT; + /** XML for GRIDSPEC_LONMIN */ public static final String GRIDSPEC_LONMIN_XML = GRIDSPEC_ELEMENT+ "[" + GRIDSPEC_LONMIN + "]"; + /** XML for GRIDSPEC_LONMAX */ public static final String GRIDSPEC_LONMAX_XML = GRIDSPEC_ELEMENT+ "[" + GRIDSPEC_LONMAX + "]"; + /** XML for GRIDSPEC_LATMIN */ public static final String GRIDSPEC_LATMIN_XML = GRIDSPEC_ELEMENT+ "[" + GRIDSPEC_LATMIN + "]"; + /** XML for GRIDSPEC_LATMAX */ public static final String GRIDSPEC_LATMAX_XML = GRIDSPEC_ELEMENT+ "[" + GRIDSPEC_LATMAX + "]"; - + // ShakeMap griddata parameters + /** Element for Shakemap griddata */ public static final String GRIDDATA_ELEMENT = "grid_data"; + /** Shakemap griddata parameter to stop parsing before */ public static final String STOP_PARSING_BEFORE_GRIDDATA = "Stop parsing before grid data."; @@ -86,7 +131,7 @@ public GridXMLHandler() {} * @param in * - the file or stream to parse * @return the ShakeMap associated with this XML handler - * @throws Exception + * @throws Exception if error occurs */ public HashMap parse(final Object in) throws Exception { try { diff --git a/src/main/java/gov/usgs/earthquake/shakemap/GridXYZHandler.java b/src/main/java/gov/usgs/earthquake/shakemap/GridXYZHandler.java index 663e3e9c..d48d882e 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/GridXYZHandler.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/GridXYZHandler.java @@ -26,21 +26,29 @@ */ public class GridXYZHandler { + /** Format for event times */ public static final SimpleDateFormat EVENT_TIMESTAMP_FORMAT = new SimpleDateFormat( "MMM dd yyyy HH:mm:ss zzz"); + /** Format for process times */ public static final SimpleDateFormat PROCESS_TIMESTAMP_FORMAT = new SimpleDateFormat( "'(Process time: 'EEE MMM dd HH:mm:ss yyyy')'"); private ShakeMap shakemap; + /** + * Constructor + * @param shakemap a shakemap + */ public GridXYZHandler(ShakeMap shakemap) { this.shakemap = shakemap; } + /** @return shakemap */ public ShakeMap getShakemap() { return shakemap; } + /** @param shakemap to set */ public void setShakemap(ShakeMap shakemap) { this.shakemap = shakemap; } @@ -49,6 +57,7 @@ public void setShakemap(ShakeMap shakemap) { * Read first line of grid.xyz file and set properties on ShakeMap object. * * @param in the grid.xyz input stream. + * @throws Exception if error occurs */ public void parse(final InputStream in) throws Exception { try { @@ -99,6 +108,12 @@ public void parse(final InputStream in) throws Exception { } } + /** + * Appends a string array of parts with a delimeter inbetween + * @param delimeter to add between parts + * @param parts string array to combine + * @return A string of delimited parts + */ protected String join(final String delimeter, final String[] parts) { StringBuffer buf = new StringBuffer(); if (parts == null) { diff --git a/src/main/java/gov/usgs/earthquake/shakemap/InfoXMLHandler.java b/src/main/java/gov/usgs/earthquake/shakemap/InfoXMLHandler.java index 57929c9a..f570bfe8 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/InfoXMLHandler.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/InfoXMLHandler.java @@ -27,7 +27,7 @@ public InfoXMLHandler() { * @param in * - the file or stream to parse * @return the ShakeMap associated with this XML handler - * @throws Exception + * @throws Exception if error occurs */ public HashMap parse(final Object in) throws Exception { XmlUtils.parse(in, this); diff --git a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMap.java b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMap.java index 5277ea5f..5dd82935 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMap.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMap.java @@ -21,20 +21,29 @@ */ public class ShakeMap extends Product { + /** Property for event description */ public static final String EVENT_DESCRIPTION_PROPERTY = "event-description"; + /** Property for event type */ public static final String EVENT_TYPE_PROPERTY = "event-type"; + /** Property for map status */ public static final String MAP_STATUS_PROPERTY = "map-status"; + /** Property for max latitude */ public static final String MAXIMUM_LATITUDE_PROPERTY = "maximum-latitude"; + /** Property for max longitude */ public static final String MAXIMUM_LONGITUDE_PROPERTY = "maximum-longitude"; + /** Property for min latitude */ public static final String MINIMUM_LATITUDE_PROPERTY = "minimum-latitude"; + /** Property for min longitude */ public static final String MINIMUM_LONGITUDE_PROPERTY = "minimum-longitude"; + /** Property for process timestamp */ public static final String PROCESS_TIMESTAMP_PROPERTY = "process-timestamp"; private static final Logger LOGGER = Logger.getLogger(ShakeMap.class .getName()); - // References to file content in the Product + /** References to file content in the Product */ public static final String GRID_XML_ATTACHMENT = "download/grid.xml"; + /** References to file content in the Product */ public static final String INFO_XML_ATTACHMENT = "download/info.xml"; // The files below have been decided to be unsupported at this time to @@ -43,18 +52,23 @@ public class ShakeMap extends Product { // public static final String GRID_XYZ_ATTACHMENT = "download/grid.xyz.zip"; // public static final String STATIONLIST_XML_ATTACHMENT = // "download/stationlist.xml"; + /** Invisible attachment */ public static final String INVISIBLE_ATTACHMENT = ".invisible"; - // A suffix added to all event codes for scenarios + /** A suffix added to all event codes for scenarios */ public static final String SCENARIO_ID_SUFFIX = "_se"; // Map types + /** Map type - actual */ public static final String ACTUAL = "ACTUAL"; + /** Map type - scenario */ public static final String SCENARIO = "SCENARIO"; + /** Map type - test */ public static final String TEST = "TEST"; - // key in info.xml for maximum mmi + /** key in info.xml for maximum mmi */ public static final String MAXIMUM_MMI_INFO_KEY = "mi_max"; + /** Property for max MMI */ public static final String MAXIMUM_MMI_PROPERTY = "maxmmi"; /** @@ -408,6 +422,8 @@ public void setMaximumLatitude(BigDecimal maximumLatitude) { /** * Returns String value as BigDecimal + * @param value to return as BigDecimal + * @return a BigDecimal */ protected BigDecimal getBigDecimal (String value) { if (value == null) { @@ -418,6 +434,8 @@ protected BigDecimal getBigDecimal (String value) { /** * Returns BigDecimal value as String + * @param value a BigDecimal + * @return a string */ protected String getString (BigDecimal value) { if (value == null) { diff --git a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerModule.java b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerModule.java index 30359a73..8ae58670 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerModule.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerModule.java @@ -30,19 +30,26 @@ public class ShakeMapIndexerModule extends DefaultIndexerModule { private static final Logger LOGGER = Logger .getLogger(ShakeMapIndexerModule.class.getName()); + /** Path to overlay img */ public static final String OVERLAY_IMAGE_PATH = "download/ii_overlay.png"; + /** Property for overlay width */ public static final String OVERLAY_WIDTH_PROPERTY = "overlayWidth"; + /** Property for overlay height */ public static final String OVERLAY_HEIGHT_PROPERTY = "overlayHeight"; + /** CONTAINS_EPICENTER_WEIGHT */ public static final int CONTAINS_EPICENTER_WEIGHT = 50; + /** CENTERED_ON_EPICENTER_WEIGHT */ public static final int CENTERED_ON_EPICENTER_WEIGHT = 25; - // Number of degrees at which no additional weight will be - // assigned based on the proximity of the map center to the - // epicenter. + /** Number of degrees at which no additional weight will be + * assigned based on the proximity of the map center to the + * epicenter. + */ public static final double MAX_DELTA_DEGREES = 2.0; - // ShakeMap atlas is the most preferred ShakeMap contributor + /** ShakeMap atlas is the most preferred ShakeMap contributor */ public static final String SHAKEMAP_ATLAS_SOURCE = "atlas"; + /** Atlas weight */ public static final int SHAKEMAP_ATLAS_WEIGHT = 200; @Override diff --git a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerWedge.java b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerWedge.java index e4092542..6dc6bbad 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerWedge.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/ShakeMapIndexerWedge.java @@ -25,10 +25,10 @@ /** * Legacy interface to trigger pre-Indexer ShakeMap processing. - * + * * The Old ShakeMap Indexer is no longer used, * and this class is deprecated. - * + * * When a shakemap product arrives, it is only processed if one of these is * true: *
        @@ -36,7 +36,7 @@ *
      • from preferred source (product source = eventsource)
      • *
      • from same source as before
      • *
      - * + * * When processing a shakemap: *
        *
      1. remove previous version
      2. @@ -44,17 +44,17 @@ *
      3. trigger legacy indexer
      4. *
      5. send tracker update
      6. *
      - * + * * Configurable properties: *
      *
      indexerCommand
      *
      The shakemap indexer command to run. Defaults to * /home/www/vhosts/earthquake/cron/shakemap_indexer.php .
      - * + * *
      shakemapDirectory
      *
      The shakemap event directory. Defaults to * /home/www/vhosts/earthquake/htdocs/earthquakes/shakemap .
      - * + * *
      timeout
      *
      How long in milliseconds the indexer is allowed to run before being * terminated.
      @@ -105,7 +105,7 @@ public class ShakeMapIndexerWedge extends DefaultNotificationListener { /** * Create a new ShakeMapIndexerWedge. - * + * * Sets up the includeTypes list to contain "shakemap". */ public ShakeMapIndexerWedge() { @@ -114,7 +114,7 @@ public ShakeMapIndexerWedge() { /** * Receive a ShakeMap from Product Distribution. - * + * * @param product * a shakemap type product. */ @@ -206,9 +206,9 @@ public void onProduct(final Product product) throws Exception { /** * Run the shakemap indexer. - * + * * If network and code are omitted, all events are updated. - * + * * @param network * the network to update. * @param code @@ -217,7 +217,7 @@ public void onProduct(final Product product) throws Exception { * whether indexer is handling a delete (true) or update (false). * @return -1 if indexer does not complete within max(1, getAttemptCount()) * times, or exit code if indexer completes. - * @throws IOException + * @throws IOException if IO error occurs */ public int runIndexer(final String network, final String code, final boolean delete) throws Exception { @@ -255,10 +255,11 @@ public int runIndexer(final String network, final String code, /** * Get the directory for a particular shakemap. - * + * * @param shakemap * the shakemap to find a directory for. * @return the shakemap directory. + * @throws Exception if error occurs */ public File getEventDirectory(final ShakeMap shakemap) throws Exception { String source = translateShakeMapSource(shakemap.getEventSource()); @@ -269,9 +270,9 @@ public File getEventDirectory(final ShakeMap shakemap) throws Exception { /** * Translate from an event source to the old style shakemap source. - * + * * Driven by the SOURCE_TRANSLATION_MAP. - * + * * @param eventSource * the event network. * @return the shakemap network. diff --git a/src/main/java/gov/usgs/earthquake/shakemap/StationlistXMLHandler.java b/src/main/java/gov/usgs/earthquake/shakemap/StationlistXMLHandler.java index 8ac9d4fc..9afad986 100644 --- a/src/main/java/gov/usgs/earthquake/shakemap/StationlistXMLHandler.java +++ b/src/main/java/gov/usgs/earthquake/shakemap/StationlistXMLHandler.java @@ -21,40 +21,69 @@ */ public class StationlistXMLHandler extends DefaultHandler { + /** Element for Shakemap data */ public static final String SHAKEMAPDATA_ELEMENT = "shakemap-data"; + /** Shakemap data version */ public static final String SHAKEMAPDATA_VERSION = "map_version"; + /** Element for earthquake */ public static final String EARTHQUAKE_ELEMENT = "earthquake"; + /** String for earthquake id */ public static final String EARTHQUAKE_ID = "id"; + /** String for earthquake latitiude */ public static final String EARTHQUAKE_LAT = "lat"; + /** String for earthquake longitude */ public static final String EARTHQUAKE_LON = "lon"; + /** String for earthquake magnitude */ public static final String EARTHQUAKE_MAG = "mag"; + /** String for earthquake year */ public static final String EARTHQUAKE_YEAR = "year"; + /** String for earthquake month */ public static final String EARTHQUAKE_MONTH = "month"; + /** String for earthquake day */ public static final String EARTHQUAKE_DAY = "day"; + /** String for earthquake hour */ public static final String EARTHQUAKE_HOUR = "hour"; + /** String for earthquake minute */ public static final String EARTHQUAKE_MINUTE = "minute"; + /** String for earthquake second */ public static final String EARTHQUAKE_SECOND = "second"; + /** String for earthquake timezone */ public static final String EARTHQUAKE_TIMEZONE = "timezone"; + /** String for earthquake depth */ public static final String EARTHQUAKE_DEPTH = "depth"; + /** String for earthquake locstring */ public static final String EARTHQUAKE_LOCSTRING = "locstring"; + /** String for earthquake created */ public static final String EARTHQUAKE_CREATED = "created"; /** The ShakeMap object parsed by this handler. */ private ShakeMap shakemap; + /** + * Constructor + * @param shakemap a shakemap object parsed by handler + */ public StationlistXMLHandler(ShakeMap shakemap) { this.shakemap = shakemap; } + /** @return shakemap */ public ShakeMap getShakemap() { return shakemap; } + /** @param shakemap to set */ public void setShakemap(ShakeMap shakemap) { this.shakemap = shakemap; } + /** + * Takes in an XML object and parses it + * @param in an object + * @return A shakemap + * @throws Exception if error occurs + */ public ShakeMap parse(final Object in) throws Exception { XmlUtils.parse(in, this); return getShakemap(); @@ -62,11 +91,12 @@ public ShakeMap parse(final Object in) throws Exception { /** * Parse element attributes. - * + * * @param uri element namespace. * @param localName element name. * @param qName qualified element name. * @param attributes element attributes. + * @throws SAXException if error occurs */ public final void startElement(final String uri, final String localName, final String qName, final Attributes attributes) diff --git a/src/main/java/gov/usgs/earthquake/tectonicsummary/TectonicSummaryIndexerModule.java b/src/main/java/gov/usgs/earthquake/tectonicsummary/TectonicSummaryIndexerModule.java index 3bb0c78d..863e737b 100644 --- a/src/main/java/gov/usgs/earthquake/tectonicsummary/TectonicSummaryIndexerModule.java +++ b/src/main/java/gov/usgs/earthquake/tectonicsummary/TectonicSummaryIndexerModule.java @@ -15,6 +15,7 @@ @Deprecated() public class TectonicSummaryIndexerModule extends DefaultIndexerModule { + /** Summary weight */ public static final int REVIEWED_TECTONIC_SUMMARY_WEIGHT = 200; @Override diff --git a/src/main/java/gov/usgs/earthquake/util/CompareUtil.java b/src/main/java/gov/usgs/earthquake/util/CompareUtil.java index e22db1f2..f0643fbf 100644 --- a/src/main/java/gov/usgs/earthquake/util/CompareUtil.java +++ b/src/main/java/gov/usgs/earthquake/util/CompareUtil.java @@ -8,13 +8,15 @@ public class CompareUtil { /** * A method to simplify comparison of two values, either of which may be * null. - * + * * For purposes of this comparison, null values are > non-null values. - * + * * @param a * value to compare * @param b * value to compare + * @param + * type * @return -1, if a is not null and b is null; 0, if a is null and b is * null; 1, if a is null and b is not null; otherwise, * a.compareTo(b). diff --git a/src/main/java/gov/usgs/earthquake/util/JDBCConnection.java b/src/main/java/gov/usgs/earthquake/util/JDBCConnection.java index fe8b7f9d..6ded6483 100644 --- a/src/main/java/gov/usgs/earthquake/util/JDBCConnection.java +++ b/src/main/java/gov/usgs/earthquake/util/JDBCConnection.java @@ -41,6 +41,11 @@ public JDBCConnection() { this.connection = null; } + /** + * Create a new JDBCConnection object with specific driver and URL + * @param driver String of driver + * @param url String of URL + */ public JDBCConnection(final String driver, final String url) { this.driver = driver; this.url = url; @@ -51,7 +56,7 @@ public JDBCConnection(final String driver, final String url) { * * Calls {@link #shutdown()}. * - * @throws Exception + * @throws Exception Exception */ @Override public void close() throws Exception { @@ -60,6 +65,8 @@ public void close() throws Exception { /** * Implement Configurable + * @param config Config to set driver and URL in + * @throws Exception Exception */ @Override public void configure(final Config config) throws Exception { @@ -87,6 +94,7 @@ protected Connection connect() throws Exception { * Initialize the database connection. * * Sub-classes should call super.startup(), before preparing any statements. + * @throws Exception if error occurs */ @Override public void startup() throws Exception { @@ -99,6 +107,7 @@ public void startup() throws Exception { * Sub-classes should close any prepared statements (catching any * exceptions), and then call super.shutdown() to close the database * connection. + * @throws Exception if error occurs */ @Override public void shutdown() throws Exception { @@ -116,6 +125,7 @@ public void shutdown() throws Exception { /** * Open a transaction on the database connection + * @throws Exception if error occurs */ public synchronized void beginTransaction() throws Exception { Connection conn = this.verifyConnection(); @@ -125,6 +135,7 @@ public synchronized void beginTransaction() throws Exception { /** * Finalize the transaction by committing all the changes and closing the * transaction. + * @throws Exception if error occurs */ public synchronized void commitTransaction() throws Exception { getConnection().setAutoCommit(true); @@ -132,6 +143,7 @@ public synchronized void commitTransaction() throws Exception { /** * Undo all of the changes made during the current transaction + * @throws Exception if error occurs */ public synchronized void rollbackTransaction() throws Exception { getConnection().rollback(); @@ -210,10 +222,14 @@ public synchronized Connection verifyConnection() throws Exception { return this.connection; } + /** @return driver */ public String getDriver() { return this.driver; } + /** @param driver Driver to set */ public void setDriver(final String driver) { this.driver = driver; } + /** @return URL */ public String getUrl() { return this.url; } + /** @param url URL to set */ public void setUrl(final String url) { this.url = url; } } diff --git a/src/main/java/gov/usgs/earthquake/util/RoundRobinBlockingQueue.java b/src/main/java/gov/usgs/earthquake/util/RoundRobinBlockingQueue.java index 6c72d364..96a3305c 100644 --- a/src/main/java/gov/usgs/earthquake/util/RoundRobinBlockingQueue.java +++ b/src/main/java/gov/usgs/earthquake/util/RoundRobinBlockingQueue.java @@ -8,10 +8,10 @@ /** * Round Robin Blocking Queue. - * + * * {@link #put(Object)} and {@link #take()} are recommended, as other methods * internally call these methods. - * + * * @param queue item type. */ public class RoundRobinBlockingQueue extends RoundRobinQueue implements @@ -20,6 +20,7 @@ public class RoundRobinBlockingQueue extends RoundRobinQueue implements private final ReentrantLock changeLock; private final Condition notEmptyCondition; + /** Constructor */ public RoundRobinBlockingQueue() { changeLock = new ReentrantLock(); notEmptyCondition = changeLock.newCondition(); @@ -63,7 +64,7 @@ public boolean contains(Object e) { /** * Offer an item to the queue. - * + * * Calls {@link #add(Object)}, but returns false if any exceptions thrown. */ @Override @@ -77,7 +78,7 @@ public boolean offer(T e) { /** * Offer an item to the queue. - * + * * Same as {@link #offer(Object)}, this is an unbounded queue. */ @Override @@ -116,7 +117,7 @@ public T poll(long timeout, TimeUnit unit) throws InterruptedException { /** * Put an item in the queue. - * + * * @throws InterruptedException * if interrupted while acquiring lock. */ @@ -138,7 +139,7 @@ public void put(T e) throws InterruptedException { /** * Unbounded queues return Integer.MAX_VALUE. - * + * * @return Integer.MAX_VALUE; */ @Override diff --git a/src/main/java/gov/usgs/earthquake/util/RoundRobinQueue.java b/src/main/java/gov/usgs/earthquake/util/RoundRobinQueue.java index a2532995..5ec8b0a0 100644 --- a/src/main/java/gov/usgs/earthquake/util/RoundRobinQueue.java +++ b/src/main/java/gov/usgs/earthquake/util/RoundRobinQueue.java @@ -11,10 +11,10 @@ /** * An abstract base class for round-robin queueing. - * + * * Sub classes should implement the {@link #getQueueId(Object)} to control how * objects are added to queues. - * + * * @param * type of object being queued. */ @@ -37,7 +37,7 @@ public RoundRobinQueue() { /** * This method determines which queue an object uses. - * + * * @param object * the object being added. * @return id of the queue where object should be added. @@ -50,7 +50,7 @@ protected String getQueueId(T object) { /** * Add an item to the queue. - * + * * @param e * item to add * @return true if added. @@ -72,7 +72,7 @@ public boolean add(T e) { /** * Add an item to the queue, if possible. - * + * * @param e * item to add * @return true if added, false otherwise. @@ -89,7 +89,7 @@ public boolean offer(T e) { /** * Retrieves and removes the head of this queue. - * + * * @return first element in queue. * @throws NoSuchElementException * if queue is empty. @@ -121,7 +121,7 @@ public T remove() { * Retrieves, but does not remove, the head of this queue. This method * differs from the {@link #peek()} method only in that it throws an * exception if this queue is empty. - * + * * @return the head of this queue. * @throws NoSuchElementException * if this queue is empty. @@ -137,7 +137,7 @@ public T element() { /** * Retrieves and removes the head of this queue. - * + * * @return the head of this queue, or null if this queue is empty. */ @Override @@ -152,7 +152,7 @@ public T poll() { /** * Retrieves, but does not remove, the head of this queue, returning null if * this queue is empty. - * + * * @return the head of this queue, or null if this queue is empty. */ @Override @@ -251,13 +251,13 @@ public boolean remove(Object o) { /** * Deep copy of another RoundRobinQueue. - * + * * This method is used for semi-destructive iteration methods. - * + * * NOTE: this assumes {@link #getQueueId(Object)} behaves the same for this * and that. - * - * @param that + * + * @param that a RoundRobinQueue to make a deep copy of */ public RoundRobinQueue(final RoundRobinQueue that) { Iterator> iter = that.queueList.iterator(); @@ -274,10 +274,10 @@ public RoundRobinQueue(final RoundRobinQueue that) { /** * Flatten queue to a list. - * + * * Creates a copy (see {@link #RoundRobinQueue(RoundRobinQueue)}, then * builds list by polling until it is empty. - * + * * @return list of all items currently in queue. */ public List toList() { diff --git a/src/main/java/gov/usgs/earthquake/util/SizeLimitInputStream.java b/src/main/java/gov/usgs/earthquake/util/SizeLimitInputStream.java index e8a723f6..53332fff 100644 --- a/src/main/java/gov/usgs/earthquake/util/SizeLimitInputStream.java +++ b/src/main/java/gov/usgs/earthquake/util/SizeLimitInputStream.java @@ -32,6 +32,7 @@ public SizeLimitInputStream(InputStream in, final long limit) { /** * Return number of bytes read. + * @return bytes read */ public long getRead() { return this.read; diff --git a/src/main/java/gov/usgs/util/CryptoUtils.java b/src/main/java/gov/usgs/util/CryptoUtils.java index 0034bb90..48ff25ef 100644 --- a/src/main/java/gov/usgs/util/CryptoUtils.java +++ b/src/main/java/gov/usgs/util/CryptoUtils.java @@ -81,7 +81,9 @@ public class CryptoUtils { /** Signature versions. */ public enum Version { + /** Signature enum for v1 */ SIGNATURE_V1("v1"), + /** Signature enum for v2 */ SIGNATURE_V2("v2"); private String value; @@ -95,6 +97,8 @@ public String toString() { } /** + * @param value to get a signature from + * @return a version * @throws IllegalArgumentException if unknown version. */ public static Version fromString(final String value) { @@ -126,10 +130,10 @@ public static Version fromString(final String value) { * the data to encrypt. * @param out * where encrypted data is written. - * @throws NoSuchAlgorithmException - * @throws NoSuchPaddingException - * @throws InvalidKeyException - * @throws IOException + * @throws NoSuchAlgorithmException if invalid encrypt/decrypt algorithm + * @throws NoSuchPaddingException on padding error + * @throws InvalidKeyException if key is not RSA or DSA. + * @throws IOException if IO error occurs */ public static void processCipherStream(final Cipher cipher, final InputStream in, final OutputStream out) @@ -146,9 +150,9 @@ public static void processCipherStream(final Cipher cipher, * @param key * the key used to encrypt. * @return a cipher used to encrypt. - * @throws NoSuchAlgorithmException - * @throws NoSuchPaddingException - * @throws InvalidKeyException + * @throws NoSuchAlgorithmException on invalid algorithm + * @throws NoSuchPaddingException on invalid padding + * @throws InvalidKeyException if key is not RSA or DSA. */ public static Cipher getEncryptCipher(final Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, @@ -165,9 +169,9 @@ public static Cipher getEncryptCipher(final Key key) * @param key * the key used to decrypt. * @return a cipher used to decrypt. - * @throws NoSuchAlgorithmException - * @throws NoSuchPaddingException - * @throws InvalidKeyException + * @throws NoSuchAlgorithmException on invalid algorithm + * @throws NoSuchPaddingException on invalid padding + * @throws InvalidKeyException if key is not RSA or DSA. */ public static Cipher getDecryptCipher(final Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, @@ -189,7 +193,9 @@ public static Cipher getDecryptCipher(final Key key) * @throws InvalidKeyException * if key is not RSA or DSA. * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws SignatureException + * on signature error */ public static Signature getSignature(final Key key, final Version version) throws InvalidKeyException, NoSuchAlgorithmException, @@ -216,6 +222,14 @@ public static Signature getSignature(final Key key, final Version version) return signature; } + /** + * + * @param key Key used to sign/verify. + * @param version SIGNATURE_V1 or SIGNATURE_V2 + * @param signature A signature + * @throws InvalidAlgorithmParameterException + * on invalid or inappropriate algorithm parameters + */ public static void configureSignature(final Key key, final Version version, final Signature signature) throws InvalidAlgorithmParameterException { if (version == Version.SIGNATURE_V2 @@ -239,7 +253,18 @@ public static void configureSignature(final Key key, final Version version, /** * A convenience method that chooses a signature algorithm based on the key * type. Works with DSA and RSA keys. + * + * @param privateKey a private key + * @param data data to sign + * @return signature as hex encoded string * @throws InvalidAlgorithmParameterException + * on invalid or inappropriate algorithm parameters + * @throws InvalidKeyException + * if key is not RSA or DSA. + * @throws NoSuchAlgorithmException + * on invalid algorithm + * @throws SignatureException + * on signature error */ public static String sign(final PrivateKey privateKey, final byte[] data) throws InvalidAlgorithmParameterException, InvalidKeyException, @@ -259,9 +284,14 @@ public static String sign(final PrivateKey privateKey, final byte[] data) * @param version * the signature version. * @return signature as hex encoded string. + * @throws InvalidAlgorithmParameterException + * on invalid or inappropriate algorithm parameters * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws InvalidKeyException + * if key is not RSA or DSA. * @throws SignatureException + * on signature error */ public static String sign(final PrivateKey privateKey, final byte[] data, final Version version) throws InvalidAlgorithmParameterException, @@ -276,6 +306,23 @@ public static String sign(final PrivateKey privateKey, final byte[] data, /** * A convenience method that chooses a signature algorithm based on the key * type. Works with DSA and RSA keys. + * + * @param publicKey + * public key corresponding to private key that generated + * signature. + * @param data + * data/hash to verify + * @param allegedSignature + * to try and verify with + * @return boolean + * @throws InvalidAlgorithmParameterException + * on invalid or inappropriate algorithm parameters + * @throws InvalidKeyException + * if key is not RSA or DSA. + * @throws NoSuchAlgorithmException + * on invalid algorithm + * @throws SignatureException + * on signature error */ public static boolean verify(final PublicKey publicKey, final byte[] data, final String allegedSignature) @@ -297,9 +344,14 @@ public static boolean verify(final PublicKey publicKey, final byte[] data, * @param version * signature version. * @return true if computed signature matches allegedSignature. + * @throws InvalidAlgorithmParameterException + * on invalid or inappropriate algorithm parameters * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws InvalidKeyException + * if key is not RSA or DSA. * @throws SignatureException + * on signature error */ public static boolean verify(final PublicKey publicKey, final byte[] data, final String allegedSignature, final Version version) @@ -321,10 +373,15 @@ public static boolean verify(final PublicKey publicKey, final byte[] data, * the data to encrypt. * @return encrypted byte array. * @throws InvalidKeyException + * if key is not RSA or DSA. * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws NoSuchPaddingException + * on invalid padding * @throws IllegalArgumentException + * on illegal args passed to function * @throws IOException + * on IO error */ public static byte[] encrypt(final Key key, final byte[] toEncrypt) throws InvalidKeyException, NoSuchAlgorithmException, @@ -344,10 +401,15 @@ public static byte[] encrypt(final Key key, final byte[] toEncrypt) * the data to decrypt. * @return decrypted byte array. * @throws InvalidKeyException + * if key is not RSA or DSA. * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws NoSuchPaddingException + * on invalid padding * @throws IllegalArgumentException + * on illegal args passed to function * @throws IOException + * on IO error */ public static byte[] decrypt(final Key key, final byte[] toDecrypt) throws InvalidKeyException, NoSuchAlgorithmException, @@ -365,6 +427,7 @@ public static byte[] decrypt(final Key key, final byte[] toDecrypt) * how many bits. This should be AES_128 or AES256. * @return generated AES key. * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static Key generateAESKey(final int bits) throws NoSuchAlgorithmException { @@ -380,6 +443,7 @@ public static Key generateAESKey(final int bits) * how many bits. Must be a valid RSA size. * @return generated RSA key pair. * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static KeyPair generateRSAKeyPair(final int bits) throws NoSuchAlgorithmException { @@ -395,6 +459,7 @@ public static KeyPair generateRSAKeyPair(final int bits) * how many bits. Must be a valid DSA size. * @return generated DSA key pair. * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static KeyPair generateDSAKeyPair(final int bits) throws NoSuchAlgorithmException { @@ -410,7 +475,9 @@ public static KeyPair generateDSAKeyPair(final int bits) * the certificate data as a byte array. * @return parsed certificate. * @throws CertificateException + * on certificate issue * @throws IOException + * on IO error */ public static Certificate readCertificate(final byte[] bytes) throws CertificateException, IOException { @@ -430,7 +497,9 @@ public static Certificate readCertificate(final byte[] bytes) * the key data as a byte array. * @return parsed public key. * @throws IOException + * on IO error * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static PublicKey readPublicKey(final byte[] bytes) throws IOException, NoSuchAlgorithmException { @@ -462,7 +531,9 @@ public static PublicKey readPublicKey(final byte[] bytes) * the key data as a byte array. * @return parsed private key. * @throws IOException + * on IO error * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static PrivateKey readPrivateKey(final byte[] bytes) throws IOException, NoSuchAlgorithmException { @@ -496,8 +567,11 @@ public static PrivateKey readPrivateKey(final byte[] bytes) * password if the key is encrypted. * @return decoded PrivateKey. * @throws IOException + * on IO error * @throws InvalidKeySpecException + * when key has invalid specifications * @throws NoSuchAlgorithmException + * on invalid algorithm */ public static PrivateKey readOpenSSHPrivateKey(final byte[] bytes, final String password) throws IOException, @@ -531,9 +605,13 @@ public static PrivateKey readOpenSSHPrivateKey(final byte[] bytes, * * @param bytes * bytes to read. + * @return a publicKey * @throws IOException + * on IO error * @throws NoSuchAlgorithmException + * on invalid algorithm * @throws InvalidKeySpecException + * when key has invalid specifications */ public static PublicKey readOpenSSHPublicKey(final byte[] bytes) throws IOException, InvalidKeySpecException, @@ -605,6 +683,7 @@ public static byte[] readDERString(ByteBuffer buf) { * string containing PEM formatted data. * @return DER formatted data. * @throws IOException + * on IO error */ public static byte[] convertPEMToDER(final String string) throws IOException { diff --git a/src/main/java/gov/usgs/util/DirectoryPoller.java b/src/main/java/gov/usgs/util/DirectoryPoller.java index 0dea28f4..8ccb1c7c 100644 --- a/src/main/java/gov/usgs/util/DirectoryPoller.java +++ b/src/main/java/gov/usgs/util/DirectoryPoller.java @@ -55,18 +55,22 @@ public DirectoryPoller(final File pollDirectory, final File storageDirectory) { this.storageDirectory = storageDirectory; } + /** @return pollDirectory file */ public File getPollDirectory() { return this.pollDirectory; } + /** @return storageDirectory file */ public File getStorageDirectory() { return this.storageDirectory; } + /** @param listener FileListenerInterface to add */ public void addFileListener(final FileListenerInterface listener) { listeners.add(listener); } + /** @param listener FileListenerInterface to remove */ public void removeFileListener(final FileListenerInterface listener) { listeners.remove(listener); } @@ -124,7 +128,7 @@ public void run() { /** * Notify all listeners that files exist and need to be processed. * - * @param file + * @param file that needs to be processed */ public void notifyListeners(final File file) { Iterator iter = new LinkedList( diff --git a/src/main/java/gov/usgs/util/ExecutorTask.java b/src/main/java/gov/usgs/util/ExecutorTask.java index 7a03dd5f..e2a948f6 100644 --- a/src/main/java/gov/usgs/util/ExecutorTask.java +++ b/src/main/java/gov/usgs/util/ExecutorTask.java @@ -81,6 +81,7 @@ public class ExecutorTask implements Future, Runnable { /** Name for this task. */ protected String name = null; + /** A synchronized object */ protected final Object syncObject = new Object(); /** @@ -106,6 +107,16 @@ public ExecutorTask(ExecutorService service, int maxTries, long timeout, /** * Wraps a runnable and result using the CallableRunnable class. + * @param service + * ExecutorService that this task will be submitted to. + * @param maxTries + * maximum number of tries callable can throw an exception or + * timeout before giving up. < 1 means never run. + * @param timeout + * number of milliseconds to allow callable to run before it is + * interrupted. <= 0 means never timeout. + * @param runnable a runnable + * @param result the result * * @see java.util.concurrent.Executors#callable(Runnable, Object) */ @@ -344,10 +355,12 @@ public Callable getCallable() { return callable; } + /** @return name */ public String getName() { return this.name; } + /** @param name to set */ public void setName(final String name) { this.name = name; } diff --git a/src/main/java/gov/usgs/util/FileUtils.java b/src/main/java/gov/usgs/util/FileUtils.java index f20d9af4..95878e89 100644 --- a/src/main/java/gov/usgs/util/FileUtils.java +++ b/src/main/java/gov/usgs/util/FileUtils.java @@ -33,7 +33,7 @@ public class FileUtils { * * Calls getContentType(file.getName()). * - * @param file + * @param file a file to get type from * @return String mime type. */ public static String getContentType(final File file) { @@ -73,6 +73,8 @@ public static byte[] readFile(final File file) throws IOException { * file to write. * @param content * content to write to file. + * @throws IOException + * if any errors occur */ public static void writeFile(final File file, final byte[] content) throws IOException { diff --git a/src/main/java/gov/usgs/util/FutureExecutorTask.java b/src/main/java/gov/usgs/util/FutureExecutorTask.java index c4342f03..bac8ced5 100644 --- a/src/main/java/gov/usgs/util/FutureExecutorTask.java +++ b/src/main/java/gov/usgs/util/FutureExecutorTask.java @@ -36,6 +36,8 @@ public class FutureExecutorTask extends ExecutorTask { /** * Construct a new ExecutorTask * + * @param backgroundService + * ExecutorService used to execute callableÍ * @param service * ExecutorService that this task will be submitted to. * @param maxTries @@ -58,6 +60,19 @@ public FutureExecutorTask(ExecutorService backgroundService, ExecutorService ser /** * Wraps a runnable and result using the CallableRunnable class. * + * @param backgroundService + * ExecutorService used to execute callable + * @param service + * ExecutorService that this task will be submitted to. + * @param maxTries + * maximum number of tries callable can throw an exception or + * timeout before giving up. < 1 means never run. + * @param timeout + * number of milliseconds to allow callable to run before it is + * interrupted. <= 0 means never timeout. + * @param runnable a runnable + * @param result the result passed to Executors callable + * * @see java.util.concurrent.Executors#callable(Runnable, Object) */ public FutureExecutorTask(ExecutorService backgroundService, ExecutorService service, @@ -69,6 +84,8 @@ public FutureExecutorTask(ExecutorService backgroundService, ExecutorService ser /** * Construct a new FutureExecutorTask * + * @param backgroundService + * ExecutorService used to execute callable * @param service * ExecutorService that this task will be submitted to. * @param maxTries @@ -85,7 +102,7 @@ public FutureExecutorTask(ExecutorService backgroundService, ExecutorService ser * @param retryDelay * the number of milliseconds to wait before retrying after an * exception. - * @see InterruptedException + * @see InterruptedException on interrupted */ public FutureExecutorTask(ExecutorService backgroundService, ExecutorService service, int maxTries, long timeout, Callable callable, Timer retryTimer, diff --git a/src/main/java/gov/usgs/util/Ini.java b/src/main/java/gov/usgs/util/Ini.java index 0a3cf673..0ee6f284 100644 --- a/src/main/java/gov/usgs/util/Ini.java +++ b/src/main/java/gov/usgs/util/Ini.java @@ -54,11 +54,16 @@ public class Ini extends Properties { /** Section names map to Section properties. */ private HashMap sections = new HashMap(); + /** String for representing a comment start */ public static final String COMMENT_START = ";"; + /** String for representing an alternate comment start */ public static final String ALTERNATE_COMMENT_START = "#"; + /** String to represent a section start */ public static final String SECTION_START = "["; + /** String to represent a section end */ public static final String SECTION_END = "]"; + /** String to delimit properties */ public static final String PROPERTY_DELIMITER = "="; /** diff --git a/src/main/java/gov/usgs/util/JDBCUtils.java b/src/main/java/gov/usgs/util/JDBCUtils.java index c6f8e094..9499a622 100644 --- a/src/main/java/gov/usgs/util/JDBCUtils.java +++ b/src/main/java/gov/usgs/util/JDBCUtils.java @@ -16,9 +16,9 @@ /** * JDBC Connection and Statement utility functions. - * + * * @author jmfee - * + * */ public class JDBCUtils { @@ -30,7 +30,7 @@ public class JDBCUtils { /** * Create a new JDBC Connection. - * + * * @param driver * driver class name. * @param url @@ -42,6 +42,10 @@ public class JDBCUtils { * if driver empty constructor is not public. * @throws InstantiationException * if an exception occurs while instantiating driver. + * @throws InvocationTargetException + * if an exception occurs with invoked method + * @throws NoSuchMethodException + * if method cannot be found * @throws SQLException * if an error occurs while making connection. */ @@ -58,10 +62,10 @@ public static Connection getConnection(final String driver, final String url) /** * Set a JDBC prepared statement parameter. - * + * * Either calls statement.setNull if object is null, or sets the appropriate * type based on the object. If the object is not null, type is ignored. - * + * * @param statement * statement with parameters to set. * @param index @@ -71,6 +75,7 @@ public static Connection getConnection(final String driver, final String url) * @param type * java.sql.Types constant for column type. * @throws SQLException + * if an error occurs while making connection. */ public static void setParameter(final PreparedStatement statement, final int index, final Object object, final int type) @@ -106,12 +111,24 @@ public static void setParameter(final PreparedStatement statement, /** * Get a mysql connection from a URL. - * + * * Calls getConnection(MYSQL_DRIVER_CLASSNAME, url). - * + * * @param url * a Mysql URL. * @return a Connection to a Mysql database. + * @throws SQLException + * if an error occurs while making connection. + * @throws ClassNotFoundException + * if driver class is not found. + * @throws IllegalAccessException + * if driver empty constructor is not public. + * @throws InstantiationException + * if an exception occurs while instantiating driver. + * @throws InvocationTargetException + * if an exception occurs with invoked method + * @throws NoSuchMethodException + * if method cannot be found */ public static Connection getMysqlConnection(final String url) throws SQLException, ClassNotFoundException, @@ -122,12 +139,24 @@ public static Connection getMysqlConnection(final String url) /** * Get a sqlite connection from a file. - * + * * Builds a sqlite file url and calls getSqliteConnection(url). - * + * * @param file * sqlite database file. * @return connection to sqlite database file. + * @throws SQLException + * if an error occurs while making connection. + * @throws ClassNotFoundException + * if driver class is not found. + * @throws IllegalAccessException + * if driver empty constructor is not public. + * @throws InstantiationException + * if an exception occurs while instantiating driver. + * @throws InvocationTargetException + * if an exception occurs with invoked method + * @throws NoSuchMethodException + * if method cannot be found */ public static Connection getSqliteConnection(final File file) throws SQLException, ClassNotFoundException, @@ -139,12 +168,24 @@ public static Connection getSqliteConnection(final File file) /** * Get a sqlite connection from a URL. - * + * * Calls getConnection(SQLITE_DRIVER_CLASSNAME, url). - * + * * @param url * sqlite database URL. * @return a Connection to a sqlite database. + * @throws SQLException + * if an error occurs while making connection. + * @throws ClassNotFoundException + * if driver class is not found. + * @throws IllegalAccessException + * if driver empty constructor is not public. + * @throws InstantiationException + * if an exception occurs while instantiating driver. + * @throws InvocationTargetException + * if an exception occurs with invoked method + * @throws NoSuchMethodException + * if method cannot be found */ public static Connection getSqliteConnection(final String url) throws SQLException, ClassNotFoundException, diff --git a/src/main/java/gov/usgs/util/ObjectLock.java b/src/main/java/gov/usgs/util/ObjectLock.java index 4c416c3e..043666e8 100644 --- a/src/main/java/gov/usgs/util/ObjectLock.java +++ b/src/main/java/gov/usgs/util/ObjectLock.java @@ -110,7 +110,7 @@ private void decrementThreadCount(final T object) { * * @param object * the object to lock for reading. - * @throws InterruptedException + * @throws InterruptedException if thread is interrupted */ public void acquireReadLock(final T object) throws InterruptedException { ReentrantReadWriteLock lock = null; @@ -161,7 +161,7 @@ public void releaseReadLock(final T object) { * * @param object * the object to lock for writing. - * @throws InterruptedException + * @throws InterruptedException if thread is interrupted */ public void acquireWriteLock(final T object) throws InterruptedException { ReentrantReadWriteLock lock = null; @@ -195,7 +195,7 @@ public void releaseWriteLock(final T object) { * * @param object * the object to lock. - * @throws InterruptedException + * @throws InterruptedException if thread is interrupted */ public void acquireLock(final T object) throws InterruptedException { acquireWriteLock(object); diff --git a/src/main/java/gov/usgs/util/ProcessTimeoutException.java b/src/main/java/gov/usgs/util/ProcessTimeoutException.java index e44fdae5..6c94addf 100644 --- a/src/main/java/gov/usgs/util/ProcessTimeoutException.java +++ b/src/main/java/gov/usgs/util/ProcessTimeoutException.java @@ -1,6 +1,6 @@ /* * ProcessTimeoutException - * + * * $Id$ * $URL$ */ @@ -12,6 +12,9 @@ public class ProcessTimeoutException extends Exception { private static final long serialVersionUID = 0x52AF13AL; + /** + * @param message relating to exception + */ public ProcessTimeoutException(String message) { super(message); } diff --git a/src/main/java/gov/usgs/util/StreamUtils.java b/src/main/java/gov/usgs/util/StreamUtils.java index 88112f22..e4e77510 100644 --- a/src/main/java/gov/usgs/util/StreamUtils.java +++ b/src/main/java/gov/usgs/util/StreamUtils.java @@ -208,6 +208,7 @@ public static byte[] readStream(final Object from) throws IOException { * @param to * streamable target. * @throws IOException + * if IO error occurs */ public static void transferStream(final Object from, final Object to) throws IOException { @@ -222,6 +223,8 @@ public static void transferStream(final Object from, final Object to) * streamable source. * @param to * streamable target. + * @param bufferSize + * size of buffer * @throws IOException * if thrown by calls to read/write on streams. */ diff --git a/src/main/java/gov/usgs/util/StringUtils.java b/src/main/java/gov/usgs/util/StringUtils.java index c2e5fd5d..434c9aa5 100644 --- a/src/main/java/gov/usgs/util/StringUtils.java +++ b/src/main/java/gov/usgs/util/StringUtils.java @@ -17,6 +17,11 @@ */ public class StringUtils { + /** + * @param value value to encode + * @return Utf8 encoded string + * @throws UnsupportedEncodingException if character encoding is not supported + */ public static String encodeAsUtf8(final String value) throws UnsupportedEncodingException { byte[] utf8Bytes = value.getBytes(StandardCharsets.UTF_8); @@ -26,7 +31,7 @@ public static String encodeAsUtf8(final String value) /** * No Exception Double parsing method. * - * @param value + * @param value string to get double from * @return null on error, otherwise Double value. */ public static Double getDouble(final String value) { @@ -42,7 +47,7 @@ public static Double getDouble(final String value) { /** * No Exception Float parsing method. * - * @param value + * @param value string to get float from * @return null on error, otherwise Float value. */ public static Float getFloat(final String value) { @@ -58,7 +63,7 @@ public static Float getFloat(final String value) { /** * No Exception Integer parsing method. * - * @param value + * @param value string to get integer from * @return null on error, otherwise Integer value. */ public static Integer getInteger(final String value) { @@ -74,7 +79,7 @@ public static Integer getInteger(final String value) { /** * No Exception Long parsing method. * - * @param value + * @param value string to get long from * @return null on error, otherwise Integer value. */ public static Long getLong(final String value) { diff --git a/src/main/java/gov/usgs/util/TimeoutProcess.java b/src/main/java/gov/usgs/util/TimeoutProcess.java index 2dd2b39b..4304eaa4 100644 --- a/src/main/java/gov/usgs/util/TimeoutProcess.java +++ b/src/main/java/gov/usgs/util/TimeoutProcess.java @@ -45,26 +45,32 @@ protected TimeoutProcess(Process process) { this.process = process; } + /** Destroys a process */ public void destroy() { process.destroy(); } + /** @return errorOutput byte array */ public byte[] errorOutput() { return errorOutput; } + /** @return exit value */ public int exitValue() { return process.exitValue(); } + /** @return InputStream of error stream */ public InputStream getErrorStream() { return process.getErrorStream(); } + /** @return InputStream */ public InputStream getInputStream() { return process.getInputStream(); } + /** @return OutputStream */ public OutputStream getOutputStream() { return process.getOutputStream(); } @@ -75,6 +81,9 @@ public OutputStream getOutputStream() { * * @return exitStatus. * @throws InterruptedException + * if thread interruption occurs + * @throws IOException + * if IO error occurs * @throws ProcessTimeoutException * if the process timed out before exiting. */ @@ -105,14 +114,17 @@ public int waitFor() throws InterruptedException, IOException, ProcessTimeoutExc return status; } + /** @param timeoutElapsed to set */ protected void setTimeoutElapsed(boolean timeoutElapsed) { this.timeoutElapsed = timeoutElapsed; } + /** @return timeoutElapsed boolean */ protected boolean timeoutElapsed() { return timeoutElapsed; } + /** @param timer to set */ protected void setTimer(final Timer timer) { this.timer = timer; } diff --git a/src/main/java/gov/usgs/util/TimeoutProcessBuilder.java b/src/main/java/gov/usgs/util/TimeoutProcessBuilder.java index c38a6f1b..c885b83f 100644 --- a/src/main/java/gov/usgs/util/TimeoutProcessBuilder.java +++ b/src/main/java/gov/usgs/util/TimeoutProcessBuilder.java @@ -1,6 +1,6 @@ /* * TimeoutProcessBuilder - * + * * $Id$ * $URL$ */ @@ -16,10 +16,10 @@ /** * The TimeoutProcessBuilder wraps a ProcessBuilder, adding support for a * command time out. - * + * * This class does not support a full command String complete with arguments. * You can use the StringUtils.split method to get around this. - * + * * @see java.lang.ProcessBuilder * @see TimeoutProcess */ @@ -33,7 +33,7 @@ public class TimeoutProcessBuilder { /** * Create a new TimeoutProcessBuilder with a timeout and an array of * strings. - * + * * @param timeout * timeout in milliseconds for process, or <= 0 for no timeout. * @param command @@ -48,7 +48,7 @@ public TimeoutProcessBuilder(long timeout, String... command) { /** * Create a new TimeoutProcessBuilder with a timeout and an array of * strings. - * + * * @param timeout * timeout in milliseconds for process, or <= 0 for no timeout. * @param command @@ -63,48 +63,76 @@ public TimeoutProcessBuilder(long timeout, List command) { /** * This signature is preserved, but calls the alternate constructor with * argument order swapped. + * @param command + * list of strings that represent command. + * @param timeout + * timeout in milliseconds for process, or <= 0 for no timeout. */ @Deprecated public TimeoutProcessBuilder(List command, long timeout) { this(timeout, command); } + /** @return list of builder commands */ public List command() { return builder.command(); } + /** + * @param command give builder a list of commands + * @return TimeoutProcessBuilder + */ public TimeoutProcessBuilder command(List command) { builder.command(command); return this; } + /** + * @param command give builder a single command + * @return TimeoutProcessBuilder + */ public TimeoutProcessBuilder command(String command) { builder.command(command); return this; } + /** @return builder directory */ public File directory() { return builder.directory(); } + /** + * @param directory to set + * @return TimeoutProcessBuilder + */ public TimeoutProcessBuilder directory(File directory) { builder.directory(directory); return this; } + /** @return builder environment */ public Map environment() { return builder.environment(); } + /** @return boolean redirectErrorStream */ public boolean redirectErrorStream() { return builder.redirectErrorStream(); } + /** + * @param redirectErrorStream to set + * @return TimeoutProcessBuilder + */ public TimeoutProcessBuilder redirectErrorStream(boolean redirectErrorStream) { builder.redirectErrorStream(redirectErrorStream); return this; } + /** + * @return a TimeoutProcess + * @throws IOException if IO error occurs + */ public TimeoutProcess start() throws IOException { final TimeoutProcess process = new TimeoutProcess(builder.start()); @@ -124,10 +152,12 @@ public void run() { return process; } + /** @return timeout */ public long getTimeout() { return this.timeout; } + /** @param timeout to set */ public void setTimeout(final long timeout) { this.timeout = timeout; } diff --git a/src/main/java/gov/usgs/util/XmlUtils.java b/src/main/java/gov/usgs/util/XmlUtils.java index 8adbbffd..d1c714e0 100644 --- a/src/main/java/gov/usgs/util/XmlUtils.java +++ b/src/main/java/gov/usgs/util/XmlUtils.java @@ -38,6 +38,7 @@ */ public class XmlUtils { + /** Hashmap of ESCAPES */ public static final Map ESCAPES = new HashMap(); static { // xml diff --git a/src/main/java/gov/usgs/util/logging/SimpleLogFileHandler.java b/src/main/java/gov/usgs/util/logging/SimpleLogFileHandler.java index 165c946b..9f0fb023 100644 --- a/src/main/java/gov/usgs/util/logging/SimpleLogFileHandler.java +++ b/src/main/java/gov/usgs/util/logging/SimpleLogFileHandler.java @@ -33,10 +33,10 @@ public class SimpleLogFileHandler extends Handler { /** * Create a default SimpleLogHandler. - * + * * Uses the system locale to roll log files once a day, and default filename * format "log_YYYYMMDD.log". - * + * * @param logDirectory * the directory to write log files. */ @@ -46,7 +46,7 @@ public SimpleLogFileHandler(final File logDirectory) { /** * Create a SimpleLogHandler with a custom filename format. - * + * * @param logDirectory * the directory to write log files. * @param filenameFormat @@ -96,7 +96,7 @@ public void flush() { /** * Retrieve the outputstream for the current log file. - * + * * @param date * the date of the message about to be logged. * @return and OutputStream where the log message may be written. @@ -146,7 +146,12 @@ public void publish(LogRecord record) { private static final Logger LOGGER = Logger .getLogger(SimpleLogFileHandler.class.getName()); - public static void main(final String[] args) throws Exception { + /** + * Testing for handler + * @param args CLI args + * @throws Exception if error occurs + */ + public static void main(final String[] args) throws Exception { SimpleDateFormat ridiculouslyShortLogs = new SimpleDateFormat( "'log_'yyyyMMddHHmmss'.log'"); File logDirectory = new File("log"); diff --git a/src/main/java/gov/usgs/util/protocolhandlers/data/DataURLConnection.java b/src/main/java/gov/usgs/util/protocolhandlers/data/DataURLConnection.java index 32f9ff8c..06c867d4 100644 --- a/src/main/java/gov/usgs/util/protocolhandlers/data/DataURLConnection.java +++ b/src/main/java/gov/usgs/util/protocolhandlers/data/DataURLConnection.java @@ -15,6 +15,10 @@ public class DataURLConnection extends URLConnection { private byte[] data; private String type; + /** + * @param url URL + * @throws Exception if error occurs + */ public DataURLConnection(final URL url) throws Exception { super(url); diff --git a/src/main/java/gov/usgs/util/protocolhandlers/data/Handler.java b/src/main/java/gov/usgs/util/protocolhandlers/data/Handler.java index a815d0a9..ed61dd42 100644 --- a/src/main/java/gov/usgs/util/protocolhandlers/data/Handler.java +++ b/src/main/java/gov/usgs/util/protocolhandlers/data/Handler.java @@ -12,6 +12,7 @@ */ public class Handler extends URLStreamHandler { + /** property for protocol handlers */ public static final String PROTOCOL_HANDLERS_PROPERTY = "java.protocol.handler.pkgs"; /**