Merge "Issue #1453 Fix the handling of subscription active period dates." into development

Former-commit-id: dc57c5a282 [formerly fd4d8f2407] [formerly dc57c5a282 [formerly fd4d8f2407] [formerly dcbda78944 [formerly f8edc8238c8e2e115cd776b294c66e572bf00cc6]]]
Former-commit-id: dcbda78944
Former-commit-id: fdc4ebb5b5 [formerly 605c8dfe77]
Former-commit-id: 13ff9f1cb1
This commit is contained in:
Richard Peter 2013-01-08 16:44:56 -06:00 committed by Gerrit Code Review
commit d9f19bfc7b
159 changed files with 20930 additions and 54 deletions

View file

@ -27,7 +27,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@ -91,6 +90,7 @@ import com.raytheon.uf.viz.datadelivery.utils.DataDeliveryUtils;
* ------------ ---------- ----------- --------------------------
* Nov 6, 2012 1269 lvenable Initial creation.
* Dec 13, 2012 1269 lvenable Fixes and updates.
* Jan 07, 2013 1451 djohnson Use TimeUtil.newGmtCalendar().
*
* </pre>
*
@ -159,7 +159,7 @@ public class BandwidthCanvasComp extends Composite implements IDialogClosed,
private int previousMinute;
/** Graph data utility */
private GraphDataUtil graphDataUtil;
private final GraphDataUtil graphDataUtil;
/** Counts the minutes until the next full update. */
private int fullUpdateMinuteCount = 0;
@ -193,7 +193,7 @@ public class BandwidthCanvasComp extends Composite implements IDialogClosed,
this.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
generateCanvasSettings();
currentTime = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
currentTime = TimeUtil.newGmtCalendar();
imageMgr = new BandwidthImageMgr(parentComp, canvasSettingsMap, bgd,
currentTime.getTimeInMillis());

View file

@ -49,6 +49,7 @@ import com.raytheon.uf.viz.datadelivery.utils.DataDeliveryGUIUtils.SubscriptionP
* ------------ ---------- ----------- --------------------------
* Nov 28, 2012 1269 lvenable Initial creation.
* Dec 13, 2012 1269 lvenable Fixes and updates.
* Jan 07, 2013 1451 djohnson Use TimeUtil.newGmtCalendar().
*
* </pre>
*
@ -269,7 +270,7 @@ public class GraphImage extends AbstractCanvasImage {
* Graphics Context
*/
private void drawTimeLines(GC gc) {
Calendar cal = TimeUtil.newCalendar(timeZone);
Calendar cal = TimeUtil.newGmtCalendar();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long currentTimeMillis = cal.getTimeInMillis();

View file

@ -25,7 +25,6 @@ import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
@ -45,6 +44,7 @@ import com.raytheon.uf.common.datadelivery.registry.InitialPendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSet;
import com.raytheon.uf.common.datadelivery.registry.PendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.datadelivery.registry.Utils.SubscriptionStatus;
import com.raytheon.uf.common.datadelivery.registry.handlers.IPendingSubscriptionHandler;
import com.raytheon.uf.common.datadelivery.registry.handlers.ISubscriptionHandler;
import com.raytheon.uf.common.datadelivery.request.DataDeliveryAuthRequest;
@ -55,6 +55,7 @@ import com.raytheon.uf.common.registry.handler.RegistryObjectHandlers;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.viz.core.IGuiThreadTaskExecutor;
import com.raytheon.uf.viz.core.auth.UserController;
import com.raytheon.uf.viz.core.exception.VizException;
@ -310,12 +311,32 @@ public class CreateSubscriptionDlgPresenter {
view.setEndDateBtnEnabled(false);
}
Date saDate = subscription.getActivePeriodStart();
Date eaDate = subscription.getActivePeriodEnd();
Date activePeriodStartDate = subscription.getActivePeriodStart();
Date activePeriodEndDate = subscription.getActivePeriodEnd();
if (saDate != null || eaDate != null) {
view.setActiveStartDate(saDate);
view.setActiveEndDate(eaDate);
if (activePeriodStartDate != null && activePeriodEndDate != null) {
final Calendar now = TimeUtil.newGmtCalendar();
int calendarYearToUse = now.get(Calendar.YEAR);
// If currently in the window, assume starting from last year for
// the start date
if (subscription.getStatus().equals(
SubscriptionStatus.ACTIVE.toString())) {
calendarYearToUse--;
}
activePeriodStartDate = calculateNextOccurenceOfMonthAndDay(
activePeriodStartDate, calendarYearToUse, now);
Calendar activePeriodStartCal = TimeUtil.newGmtCalendar();
activePeriodStartCal.setTime(activePeriodStartDate);
activePeriodEndDate = calculateNextOccurenceOfMonthAndDay(
activePeriodEndDate,
activePeriodStartCal.get(Calendar.YEAR), now);
view.setActiveStartDate(activePeriodStartDate);
view.setActiveEndDate(activePeriodEndDate);
view.setAlwaysActive(false);
} else {
view.setAlwaysActive(true);
@ -346,6 +367,31 @@ public class CreateSubscriptionDlgPresenter {
}
}
/**
* Calculate the next occurrence of the month and day on the specified date
* object.
*
* @param dateWithMonthAndDay
* the date to retrieve the month and day from
* @param yearToStartAt
* the year to start moving forward from, checking for the date
* to not before the current time
* @param now
* the current calendar
*
* @return the date object of the next occurrence
*/
private static Date calculateNextOccurenceOfMonthAndDay(
Date dateWithMonthAndDay, int yearToStartAt, Calendar now) {
final Calendar cal = TimeUtil.newCalendar();
cal.setTime(dateWithMonthAndDay);
cal.set(Calendar.YEAR, yearToStartAt);
if (cal.before(now)) {
cal.add(Calendar.YEAR, 1);
}
return cal.getTime();
}
/**
* The group name selection event
*/
@ -380,7 +426,7 @@ public class CreateSubscriptionDlgPresenter {
}
if (view.isNoExpirationDate()) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newGmtCalendar();
subscription.setSubscriptionStart(cal.getTime());
subscription.setSubscriptionEnd(null);
} else {
@ -421,15 +467,8 @@ public class CreateSubscriptionDlgPresenter {
.parse(endText);
subscription.setActivePeriodEnd(endPeriodDate);
}
Calendar cal = Calendar
.getInstance(TimeZone.getTimeZone("GMT"));
if (subscription.getActivePeriodStart().before(cal.getTime())
&& subscription.getActivePeriodEnd().after(
cal.getTime())) {
subscription.setActive(true);
} else {
subscription.setActive(false);
}
subscription.setActive(true);
} catch (ParseException e) {
statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(),
e);
@ -717,7 +756,6 @@ public class CreateSubscriptionDlgPresenter {
boolean valid = false;
boolean datesValid = false;
boolean activeDatesValid = false;
boolean nameValid = false;
boolean groupDeliverValid = false;
boolean groupDurValid = false;
boolean groupActiveValid = false;
@ -892,12 +930,24 @@ public class CreateSubscriptionDlgPresenter {
}
// Set the Active Period info
Date saDate = groupDefinition.getActivePeriodStart();
Date eaDate = groupDefinition.getActivePeriodEnd();
Date activePeriodStartDate = groupDefinition.getActivePeriodStart();
Date activePeriodEndDate = groupDefinition.getActivePeriodEnd();
if (saDate != null || eaDate != null) {
view.setStartDate(saDate);
view.setActiveEndDate(eaDate);
if (activePeriodStartDate != null || activePeriodEndDate != null) {
final Calendar now = TimeUtil.newGmtCalendar();
activePeriodStartDate = calculateNextOccurenceOfMonthAndDay(
activePeriodStartDate, now.get(Calendar.YEAR), now);
Calendar activePeriodStartCal = TimeUtil.newGmtCalendar();
activePeriodStartCal.setTime(activePeriodStartDate);
activePeriodEndDate = calculateNextOccurenceOfMonthAndDay(
activePeriodEndDate,
activePeriodStartCal.get(Calendar.YEAR), now);
view.setStartDate(activePeriodStartDate);
view.setActiveEndDate(activePeriodEndDate);
view.setAlwaysActive(false);
} else {
view.setAlwaysActive(true);

View file

@ -41,6 +41,7 @@ import com.raytheon.uf.common.time.util.TimeUtil;
* ------------ ---------- ----------- --------------------------
* Nov 25, 2012 1269 lvenable Initial creation.
* Dec 06, 2012 1397 djohnson Add dynamic serialize class annotation.
* Jan 07, 2013 1451 djohnson Use TimeUtil.newGmtCalendar().
*
* </pre>
*
@ -209,7 +210,7 @@ public class TimeWindowData implements Comparable<TimeWindowData> {
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newGmtCalendar();
cal.setTimeInMillis(this.timeWindowStartTime);
StringBuilder sb = new StringBuilder();

View file

@ -20,7 +20,6 @@
package com.raytheon.uf.common.datadelivery.bandwidth.request;
import java.util.Calendar;
import java.util.TimeZone;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
@ -29,17 +28,18 @@ import com.raytheon.uf.common.time.util.TimeUtil;
/**
* Request object to retrieve data for the Bandwidth manager graphs
*
*
* <pre>
*
*
* SOFTWARE HISTORY
*
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Nov 25, 2012 1269 mpduff Initial creation.
*
* Jan 07, 2013 1451 djohnson Use TimeUtil.newGmtCalendar().
*
* </pre>
*
*
* @author mpduff
* @version 1.0
*/
@ -58,7 +58,7 @@ public class GraphDataRequest implements IServerRequest {
*/
public GraphDataRequest() {
// For IOC0 start time is current time in minutes
Calendar cal = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newGmtCalendar();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
startTime = cal.getTimeInMillis();

View file

@ -33,6 +33,7 @@ import com.raytheon.uf.common.time.util.TimeUtil;
* ------------ ---------- ----------- --------------------------
* 12 Sept, 2012 1038 dhladky Initial creation
* Nov 19, 2012 1166 djohnson Clean up JAXB representation of registry objects.
* Jan 07, 2013 1451 djohnson Use TimeUtil.newGmtCalendar().
*
* </pre>
*
@ -427,13 +428,11 @@ public class Collection implements ISerializableObject {
// take care of latest date
Date lastDate = sdf.parse(getLastDate());
Calendar cal = TimeUtil
.newCalendar(TimeZone.getTimeZone("UTC"));
Calendar cal = TimeUtil.newGmtCalendar();
cal.setTimeInMillis(lastDate.getTime());
int lastRoll = cal.get(periodInt);
Calendar curCal = TimeUtil.newCalendar(TimeZone
.getTimeZone("UTC"));
Calendar curCal = TimeUtil.newGmtCalendar();
curCal.setTimeInMillis(currentDate.getTime());
int currRoll = curCal.get(periodInt);
int diff = Math.abs(currRoll - lastRoll);
@ -444,8 +443,7 @@ public class Collection implements ISerializableObject {
setLastDate(sdf.format(currentDate));
Date firstDate = sdf.parse(getFirstDate());
Calendar calf = TimeUtil.newCalendar(TimeZone
.getTimeZone("UTC"));
Calendar calf = TimeUtil.newGmtCalendar();
calf.setTimeInMillis(firstDate.getTime());
calf.add(periodInt, diff);

View file

@ -25,6 +25,7 @@ import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.serialization.ISerializableObject;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
import com.raytheon.uf.common.time.util.TimeUtil;
/**
* Subscription XML
@ -840,7 +841,7 @@ public class Subscription implements ISerializableObject, Serializable {
} else if (!isActive()) {
status = SubscriptionStatus.INACTIVE;
} else {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newGmtCalendar();
Date today = cal.getTime();
status = (inWindow(today)) ? SubscriptionStatus.ACTIVE : SubscriptionStatus.INACTIVE;
@ -859,10 +860,24 @@ public class Subscription implements ISerializableObject, Serializable {
if (activePeriodStart == null && activePeriodEnd == null) {
return true;
} else if (activePeriodStart != null && activePeriodEnd != null) {
Calendar startCal = TimeUtil.newGmtCalendar();
startCal.setTime(activePeriodStart);
startCal = TimeUtil.minCalendarFields(startCal,
Calendar.HOUR_OF_DAY,
Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);
activePeriodStart = startCal.getTime();
Calendar endCal = TimeUtil.newGmtCalendar();
endCal.setTime(activePeriodEnd);
endCal = TimeUtil.maxCalendarFields(endCal, Calendar.HOUR_OF_DAY,
Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);
activePeriodEnd = endCal.getTime();
// Only concerned with month and day, need to set the years equal
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar c = TimeUtil.newGmtCalendar();
c.setTime(checkDate);
c.set(Calendar.YEAR, 1970);
c.set(Calendar.YEAR, startCal.get(Calendar.YEAR));
Date date = c.getTime();
return (activePeriodStart.before(date) && activePeriodEnd

View file

@ -41,6 +41,7 @@ import com.raytheon.uf.common.time.SimulatedTime;
* Sep 11, 2012 1154 djohnson Add MILLIS constants and isNewerDay().
* Nov 09, 2012 1322 djohnson Add SECONDS_PER_MINUTE.
* Nov 21, 2012 728 mpduff Added MILLIS_PER_MONTH.
* Jan 07, 2013 1451 djohnson Add newGmtCalendar() and time constants.
*
* </pre>
*
@ -84,23 +85,37 @@ public class TimeUtil {
public static final String DATE_STRING = "(\\d{4})-(\\d{2})-(\\d{2})[ _](\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{1,3})";
public static final int SECONDS_PER_MINUTE = 60;
public static final int MINUTES_PER_HOUR = 60;
public static final int HOURS_PER_DAY = 24;
private static final int DAYS_PER_WEEK = 7;
// Util.java has a few of these constants, but that is located in an EDEX
// plugin and this is a more appropriate place for them anyways
public static final long MILLIS_PER_SECOND = 1000;
public static final long MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60;
public static final long MILLIS_PER_MINUTE = MILLIS_PER_SECOND
* SECONDS_PER_MINUTE;
public static final long MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60;
public static final long MILLIS_PER_HOUR = MILLIS_PER_MINUTE
* MINUTES_PER_HOUR;
public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24;
public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * HOURS_PER_DAY;
public static final long MILLIS_PER_WEEK = MILLIS_PER_DAY * 7;
public static final long MILLIS_PER_WEEK = MILLIS_PER_DAY * DAYS_PER_WEEK;
/**
* Note: This constant assumes a month of 30 days.
*/
public static final long MILLIS_PER_MONTH = MILLIS_PER_DAY * 30;
public static final long MILLIS_PER_YEAR = 3600 * 24 * 1000 * 365;
public static final int SECONDS_PER_MINUTE = 60;
/**
* Note: This constant does not take into account leap years.
*/
public static final long MILLIS_PER_YEAR = MILLIS_PER_DAY * 365;
private static ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
@ -297,6 +312,18 @@ public class TimeUtil {
return cal;
}
/**
* Return a new {@link Calendar} instance for the GMT {@link TimeZone} .
* This method delegates to the {@link SimulatedTime} class to determine the
* currently configured system time.
*
* @see {@link SimulatedTime}
* @return the calendar
*/
public static Calendar newGmtCalendar() {
return TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
}
/**
* Return a new {@link Date} instance. This method delegates to the
* {@link SimulatedTime} class to determine the currently configured system
@ -320,4 +347,34 @@ public class TimeUtil {
public static ImmutableDate newImmutableDate() {
return new ImmutableDate(SimulatedTime.getSystemTime().getMillis());
}
/**
* Sets each of the fields in the list to their min value in the calendar.
*
* @param calendar
* the calendar
* @param fields
* @return the calendar with those fields zeroed
*/
public static Calendar minCalendarFields(Calendar calendar, int... fields) {
for (int field : fields) {
calendar.set(field, calendar.getActualMinimum(field));
}
return calendar;
}
/**
* Sets each of the fields in the list to their max value in the calendar.
*
* @param calendar
* the calendar
* @param fields
* @return the calendar with those fields maxed
*/
public static Calendar maxCalendarFields(Calendar calendar, int... fields) {
for (int field : fields) {
calendar.set(field, calendar.getActualMaximum(field));
}
return calendar;
}
}

View file

@ -60,6 +60,7 @@ import com.raytheon.uf.edex.stats.util.ConfigLoader;
* Aug 21, 2012 jsanchez Stored the aggregate buckets in the db.
* Nov 07, 2012 1317 mpduff Updated Configuration Files.
* Nov 28, 2012 1350 rjpeter Simplied aggregation and added aggregation with current db aggregate records.
* Jan 07, 2013 1451 djohnson Use newGmtCalendar().
* </pre>
*
* @author jsanchez
@ -93,10 +94,10 @@ public class AggregateManager {
*/
private void aggregate(AggregateRecordDao dao, StatisticsEvent statsEvent,
TimeRange timeRange, Multimap<String, Event> groupedEvents) {
Calendar start = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
Calendar start = TimeUtil.newGmtCalendar();
start.setTime(timeRange.getStart());
Calendar end = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
Calendar end = TimeUtil.newGmtCalendar();
end.setTime(timeRange.getEnd());
// perform aggregate functions on the grouped data

View file

@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
@ -51,6 +50,7 @@ import com.raytheon.uf.edex.stats.util.ConfigLoader;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 11, 2012 728 mpduff Initial creation
* Jan 07, 2013 1451 djohnson Use newGmtCalendar().
*
* </pre>
*
@ -175,7 +175,7 @@ public class GraphDataHandler implements IRequestHandler<GraphDataRequest> {
* @return Calendar object
*/
private Calendar convertToCalendar(Date date) {
Calendar cal = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT"));
Calendar cal = TimeUtil.newGmtCalendar();
cal.setTimeInMillis(date.getTime());
return cal;

70
tests/.classpath Normal file
View file

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="unit"/>
<classpathentry kind="src" path="deploy"/>
<classpathentry kind="src" path="resources"/>
<classpathentry kind="src" path="integration"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.junit"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.apache.commons.codec"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.slf4j"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.util"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.comm"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.apache.http"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datadelivery.registry"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.viz.datadelivery"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.serialization"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.registry.schemas.ebxml"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.datadelivery.harvester"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.localization"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.edex.common"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.apache.log4j"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.datadelivery.bandwidth"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.datadelivery.retrieval"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.apache.commons.lang"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.geotools"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.dataplugin.grib"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.dataplugin"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.geospatial"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.hibernate"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.springframework"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.serialization.comm"/>
<classpathentry combineaccessrules="false" kind="src" path="/edu.uci.ics.crawler4j"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datadelivery.retrieval"/>
<classpathentry combineaccessrules="false" kind="src" path="/net.dods"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.google.guava"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.time"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.status"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.viz.core"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.auth"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.plugin.nwsauth"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.auth"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.registry.ebxml"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.registry.ebxml"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.esb.camel"/>
<classpathentry combineaccessrules="false" kind="src" path="/javax.persistence"/>
<classpathentry combineaccessrules="false" kind="src" path="/net.sf.ehcache"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.dataquery"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.core"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.database"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.mchange"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.ebxml"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.apache.commons.management"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.facebook.thrift"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datastorage"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.event"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datadelivery.event"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.event"/>
<classpathentry combineaccessrules="false" kind="src" path="/javax.measure"/>
<classpathentry combineaccessrules="false" kind="src" path="/javax.vecmath"/>
<classpathentry kind="lib" path="lib/hsqldb.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.gridcoverage"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.datadelivery.service"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.viz.ui"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datadelivery.bandwidth"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.registry.event"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.datadelivery.request"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.common.stats"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.raytheon.uf.edex.stats"/>
<classpathentry kind="output" path="bin"/>
</classpath>

1
tests/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
tmp/

17
tests/.project Normal file
View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>tests</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

18
tests/build.properties Normal file
View file

@ -0,0 +1,18 @@
# Comma-separated list of testTypes to compile/run, e.g.:
# unit,integration,deploy
testTypes=unit,integration
# Deploy tests must be run with a booted EDEX, so they will require special setup
#testTypes=unit,integration,deploy
TEST.INCLUSION.PATTERN=**/*Test.java
# Important directories
WORKING.DIR=${basedir}/tmp
UNZIP.DIR=${WORKING.DIR}/unzip
TEST.COMPILE.DIR=${WORKING.DIR}/test-classes
TEST.REPORTS.DIR=${WORKING.DIR}/test-reports
# Location of the ant-contrib jar
ANT.CONTRIB.JAR=${BUILD.EDEX.DIR}/lib/ant/ant-contrib-1.0b3.jar
BUILD.EDEX.PROPERTIES=${BUILD.EDEX.DIR}/edex/build.properties

122
tests/build.xml Normal file
View file

@ -0,0 +1,122 @@
<project name="tests" basedir="." default="run-tests">
<target name="env-check">
<available file="${basedir}/../javax.mail" property="jenkins.build" />
</target>
<target name="env-developer" depends="env-check" unless="jenkins.build">
<property name="build.properties.file" value="developer-build.properties" />
</target>
<target name="env-jenkins" depends="env-check" if="jenkins.build">
<property name="build.properties.file" value="jenkins-build.properties" />
</target>
<target name="env-setup" description="Sets up the environment" depends="env-check, env-developer, env-jenkins">
<property file="${build.properties.file}" />
<property file="build.properties" />
<property file="${BUILD.EDEX.PROPERTIES}" />
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<fileset file="${ANT.CONTRIB.JAR}" />
</classpath>
</taskdef>
<delete dir="${WORKING.DIR}" />
</target>
<target name="classpath-setup-developer" depends="env-setup" unless="jenkins.build">
<path id="test.compile.classpath">
<dirset dir="${AWIPS2_BASELINE}" includes="**/bin" />
<fileset dir="${AWIPS2_BASELINE}/cots" includes="**/*.jar" excludes="**/ant-*.jar" />
<fileset dir="${AWIPS2_BASELINE}/cots/org.junit" includes="**/*.jar" />
<fileset dir="${PROJECTS.DIR}/cots" includes="**/*.jar" />
<dirset dir="${PROJECTS.DIR}" includes="**/bin" />
<fileset dir="${basedir}/lib" includes="**/*.jar" />
</path>
<path id="test.run.classpath">
<!-- Currently nothing else required here -->
</path>
</target>
<target name="classpath-setup-jenkins" depends="env-setup" if="jenkins.build">
<mkdir dir="${UNZIP.DIR}" />
<for param="zipFile">
<path>
<fileset dir="${BUILD.EDEX.DIST.DIR}" includes="*.zip" />
</path>
<sequential>
<unzip dest="${UNZIP.DIR}" src="@{zipFile}" />
</sequential>
</for>
<path id="test.compile.classpath">
<fileset dir="${UNZIP.DIR}" includes="**/*.jar" excludes="**/ant-*.jar" />
<fileset dir="${PROJECTS.DIR}/org.junit" includes="**/*.jar" />
<fileset dir="${basedir}/lib" includes="**/*.jar" />
</path>
<!-- Include resource files provided by projects -->
<path id="test.run.classpath">
<dirset dir="${PROJECTS.DIR}" includes="*/resources"/>
</path>
</target>
<target name="classpath-setup" depends="classpath-setup-developer, classpath-setup-jenkins" />
<target name="compile-tests" depends="classpath-setup" description="Compiles all tests">
<delete dir="${TEST.COMPILE.DIR}" />
<mkdir dir="${TEST.COMPILE.DIR}" />
<forEachTestType>
<javac srcdir="${basedir}/@{testType}" excludes="${TEST.EXCLUSION.PATTERN}" destdir="${TEST.COMPILE.DIR}" classpathref="test.compile.classpath" debug="on" source="${javacSource}" target="${javacTarget}" />
</forEachTestType>
</target>
<target name="run-tests" depends="compile-tests" description="Runs all tests">
<delete dir="${TEST.REPORTS.DIR}" />
<mkdir dir="${TEST.REPORTS.DIR}" />
<forEachTestType>
<var name="testTypeSourceDir" value="${basedir}/@{testType}" />
<junit printsummary="yes" haltonfailure="yes">
<jvmarg value="-Duser.dir=${testTypeSourceDir}" />
<classpath>
<!-- Any resources for tests -->
<pathelement location="${testTypeSourceDir}" />
<pathelement location="${basedir}/resources" />
<!-- Referenced jar files -->
<path refid="test.compile.classpath" />
<path refid="test.run.classpath" />
<!-- Compiled tests -->
<pathelement location="${TEST.COMPILE.DIR}" />
</classpath>
<formatter type="plain" />
<batchtest fork="no" todir="${TEST.REPORTS.DIR}">
<fileset dir="${basedir}/@{testType}">
<include name="${TEST.INCLUSION.PATTERN}" />
<exclude name="${TEST.EXCLUSION.PATTERN}"/>
</fileset>
</batchtest>
</junit>
</forEachTestType>
</target>
<macrodef name="forEachTestType" description="Loops over all requested test types, and performs the passed in action">
<element name="action" implicit="true" />
<sequential>
<for list="${testTypes}" param="testType">
<sequential>
<action />
</sequential>
</for>
</sequential>
</macrodef>
</project>

View file

@ -0,0 +1,120 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Configuration for deploy tests.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 14, 2012 1169 djohnson Initial creation
* Dec 06, 2012 1397 djohnson Also set the request server.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public final class DeployTestProperties {
private static volatile DeployTestProperties INSTANCE;
private final String dataDeliveryServer;
private final String userId;
private final String requestServer;
/**
* Private constructor.
*
* @param properties
*/
private DeployTestProperties(Properties properties) {
this.dataDeliveryServer = properties
.getProperty("datadelivery.server");
this.requestServer = properties.getProperty("request.server");
this.userId = properties.getProperty("user.id");
}
/**
* @return the dataDeliveryServer
*/
public String getDataDeliveryServer() {
return dataDeliveryServer;
}
/**
* @return
*/
public String getRequestServer() {
return requestServer;
}
/**
* @return the user id
*/
public String getUserId() {
return userId;
}
/**
* Return the singleton instance.
*
* @param dataDeliveryServer
* the url
* @see http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
*/
public static DeployTestProperties getInstance() {
DeployTestProperties result = INSTANCE;
if (result == null) {
synchronized (DeployTestProperties.class) {
result = INSTANCE;
if (result == null) {
// If the configuration grows beyond several properties,
// should probably change to use Spring and a custom
// properties object
byte[] file = TestUtil.readResource(
DeployTestProperties.class,
"deploy-test.properties");
Properties properties;
try {
properties = PropertiesUtil
.read(new ByteArrayInputStream(file));
} catch (IOException e) {
throw new IllegalStateException(
"Unable to read the deploy test configuration file!",
e);
}
INSTANCE = result = new DeployTestProperties(properties);
}
}
}
return result;
}
}

View file

@ -0,0 +1,5 @@
# The url used to access the test EDEX instance providing data delivery thrift services
datadelivery.server=http://localhost:9588/services
request.server=http://localhost:9581/services
# The userId that should be used for deploy tests
user.id=DeployTest

View file

@ -0,0 +1,112 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.service.services;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import org.junit.BeforeClass;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.PendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.PendingSubscriptionFixture;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.datadelivery.registry.SubscriptionDeleteRequest;
import com.raytheon.uf.common.datadelivery.registry.SubscriptionFixture;
import com.raytheon.uf.common.datadelivery.registry.handlers.DataDeliveryHandlers;
import com.raytheon.uf.common.datadelivery.registry.handlers.IPendingSubscriptionHandler;
import com.raytheon.uf.common.datadelivery.registry.handlers.ISubscriptionHandler;
import com.raytheon.uf.common.datadelivery.request.DataDeliveryConstants;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.registry.handler.RegistryObjectHandlersUtil;
import com.raytheon.uf.common.serialization.comm.RequestRouter;
import com.raytheon.uf.common.util.DeployTestProperties;
import com.raytheon.uf.edex.ebxml.registry.RegistryManagerDeployTest;
/**
* Test SubscriptionDeleteHandler.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 27, 2012 1187 djohnson Initial creation
* Oct 17, 2012 0726 djohnson Use {@link RegistryManagerDeployTest#setDeployInstance()}.
* Nov 15, 2012 1286 djohnson Use RequestRouter.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SubscriptionDeleteHandlerDeployTest {
@BeforeClass
public static void staticSetUp() {
RegistryObjectHandlersUtil.init();
RegistryManagerDeployTest.setDeployInstance();
}
@Test
public void testDeletingSubscriptionDeletesPendingAlso() throws Exception {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
PendingSubscription pending = PendingSubscriptionFixture.INSTANCE.get();
ISubscriptionHandler subHandler = DataDeliveryHandlers
.getSubscriptionHandler();
IPendingSubscriptionHandler pendingHandler = DataDeliveryHandlers
.getPendingSubscriptionHandler();
try {
subHandler.store(subscription);
pendingHandler.store(pending);
assertNotNull(
"The pending subscription should have been retrievable!",
pendingHandler.getBySubscription(subscription));
SubscriptionDeleteRequest request = new SubscriptionDeleteRequest(
Arrays.asList(RegistryUtil
.getRegistryObjectKey(subscription)),
ISubscriptionHandler.class, DeployTestProperties
.getInstance()
.getUserId());
RequestRouter.route(request,
DataDeliveryConstants.DATA_DELIVERY_SERVER);
assertNull(
"The pending subscription should have been deleted when deleting the subscription!",
pendingHandler.getBySubscription(subscription));
} finally {
try {
subHandler.delete(subscription);
} finally {
pendingHandler.delete(pending);
}
}
}
}

View file

@ -0,0 +1,128 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.ebxml.registry;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import com.raytheon.uf.common.auth.RequestConstants;
import com.raytheon.uf.common.datadelivery.registry.Provider;
import com.raytheon.uf.common.datadelivery.registry.ProviderFixture;
import com.raytheon.uf.common.datadelivery.request.DataDeliveryConstants;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryConstants;
import com.raytheon.uf.common.registry.RegistryManager;
import com.raytheon.uf.common.registry.RegistryManagerTest;
import com.raytheon.uf.common.registry.RegistryResponse;
import com.raytheon.uf.common.registry.ebxml.ThriftRegistryHandler;
import com.raytheon.uf.common.serialization.comm.RequestRouterTest;
import com.raytheon.uf.common.util.DeployTestProperties;
import com.raytheon.uf.common.util.registry.RegistryException;
import com.raytheon.uf.edex.auth.RemoteServerRequestRouter;
/**
* Deploy test for {@link RegistryManager}. Deploy tests must execute against a
* running EDEX instance.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 13, 2012 1169 djohnson Initial creation
* Oct 17, 2012 0726 djohnson Add {@link #setDeployInstance()}.
* Nov 15, 2012 1286 djohnson Use RequestRouter.
* Dec 06, 2012 1397 djohnson Also set the request router.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class RegistryManagerDeployTest {
private static final Provider provider = ProviderFixture.INSTANCE.get();
/**
* Sets the deploy test thrift registry handler instance.
*/
public static void setDeployInstance() {
// this allows the configuration wiring to be checked for validity
// first, otherwise any exceptions would be hidden in registry response
// objects
DeployTestProperties.getInstance();
final ThriftRegistryHandler handler = new ThriftRegistryHandler();
RegistryManagerTest.setInstance(handler);
try {
RequestRouterTest.clearRegistry();
final RemoteServerRequestRouter requestRouter = new RemoteServerRequestRouter(
DeployTestProperties.getInstance().getRequestServer());
final RemoteServerRequestRouter dataDeliveryRouter = new RemoteServerRequestRouter(DeployTestProperties
.getInstance().getDataDeliveryServer());
RequestRouterTest.register(
DataDeliveryConstants.DATA_DELIVERY_SERVER, dataDeliveryRouter);
RequestRouterTest.register(
RegistryConstants.EBXML_REGISTRY_SERVICE, dataDeliveryRouter);
RequestRouterTest.register(RequestConstants.REQUEST_SERVER,
requestRouter);
} catch (RegistryException e) {
throw new RuntimeException(e);
}
}
@BeforeClass
public static void staticSetUp() {
setDeployInstance();
}
@After
public void cleanUp() {
RegistryManager.removeRegistyObjects(Arrays.asList(provider));
}
@Test
public void testUnableToStoreAlreadyStoredRegistryObject() {
RegistryResponse<Provider> response = RegistryManager
.storeRegistryObject(provider);
assertEquals("First store should have succeeded!",
OperationStatus.SUCCESS, response.getStatus());
response = RegistryManager.storeRegistryObject(provider);
assertEquals("Second store should have failed!",
OperationStatus.FAILED, response.getStatus());
}
@Test
public void testAbleToStoreAlreadyStoredRegistryObjectWithStoreOrReplace() {
RegistryResponse<Provider> response = RegistryManager
.storeRegistryObject(provider);
assertEquals("First store should have succeeded!",
OperationStatus.SUCCESS, response.getStatus());
response = RegistryManager.storeOrReplaceRegistryObject(provider);
assertEquals("Second store should have succeeded!",
OperationStatus.SUCCESS, response.getStatus());
}
}

View file

@ -0,0 +1,6 @@
PROJECTS.DIR=${basedir}/..
AWIPS2_BASELINE=${PROJECTS.DIR}/../AWIPS2_baseline
BUILD.EDEX.DIR=${AWIPS2_BASELINE}/edexOsgi/build.edex
# Currently can't run viz plugin based tests after build
TEST.EXCLUSION.PATTERN=**/uf/viz/**

View file

@ -0,0 +1,191 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.raytheon.uf.common.datadelivery.registry.Network;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.datadelivery.registry.SubscriptionFixture;
import com.raytheon.uf.common.localization.PathManagerFactoryTest;
import com.raytheon.uf.common.serialization.SerializationUtilTest;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.time.util.TimeUtilTest;
import com.raytheon.uf.common.util.PropertiesUtil;
import com.raytheon.uf.edex.database.dao.DatabaseUtil;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDao;
import com.raytheon.uf.edex.datadelivery.bandwidth.notification.BandwidthEventBusTest;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalManager;
import com.raytheon.uf.edex.datadelivery.bandwidth.util.BandwidthUtil;
/**
* Provides setup functionality for a base {@link BandwidthManager} integration
* test.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 22, 2012 1286 djohnson Initial creation
* Dec 11, 2012 1286 djohnson Use a synchronous event bus for tests.
* Dec 11, 2012 1403 djohnson No longer valid to run without bandwidth management.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
@Ignore
public abstract class AbstractBandwidthManagerIntTest {
protected ApplicationContext context;
protected BandwidthManager bandwidthManager;
protected RetrievalManager retrievalManager;
protected IBandwidthDao bandwidthDao;
/**
* Keeps track of which integers have already been used as seeds for a
* subscription.
*/
private int subscriptionSeed = 1;
/**
* The size of a bucket in bytes.
*/
private long fullBucketSize;
/**
* The size of half of a bucket in bytes.
*/
private long halfBucketSize;
/**
* The size of a third of a bucket in bytes.
*/
private long thirdBucketSizeInBytes;
@BeforeClass
public static void staticSetup() throws IOException {
Properties properties = PropertiesUtil
.read(AbstractBandwidthManagerIntTest.class
.getResourceAsStream("/com.raytheon.uf.edex.datadelivery.bandwidth.properties"));
System.getProperties().putAll(properties);
SerializationUtilTest.initSerializationUtil();
TimeUtilTest.freezeTime(TimeUtil.MILLIS_PER_DAY * 2);
BandwidthEventBusTest.initSynchronous();
}
@AfterClass
public static void staticTearDown() {
TimeUtilTest.resumeTime();
}
@Before
public void setUp() {
PathManagerFactoryTest.initLocalization();
DatabaseUtil.start();
context = new ClassPathXmlApplicationContext(
IntegrationTestBandwidthManager.INTEGRATION_TEST_SPRING_FILES,
BandwidthManagerIntTest.class);
bandwidthDao = (IBandwidthDao) context.getBean("bandwidthDao",
IBandwidthDao.class);
bandwidthManager = (BandwidthManager) context.getBean(
"bandwidthManager",
BandwidthManager.class);
retrievalManager = bandwidthManager.retrievalManager;
fullBucketSize = retrievalManager.getPlan(Network.OPSNET)
.getBucket(TimeUtil.currentTimeMillis()).getBucketSize();
halfBucketSize = fullBucketSize / 2;
thirdBucketSizeInBytes = fullBucketSize / 3;
}
@After
public void tearDown() {
try {
bandwidthManager.shutdown();
} catch (IllegalArgumentException iae) {
// ignore any exceptions occurring about not being a registered
// event bus handler
iae.printStackTrace();
}
DatabaseUtil.shutdown();
}
/**
* Create a subscription the fills up an entire bandwidth bucket.
*
* @return the subscription
*/
protected Subscription createSubscriptionThatFillsUpABucket() {
return createSubscriptionWithDataSetSizeInBytes(fullBucketSize);
}
/**
* Create a subscription the fills up half of a bandwidth bucket.
*
* @return the subscription
*/
protected Subscription createSubscriptionThatFillsHalfABucket() {
return createSubscriptionWithDataSetSizeInBytes(halfBucketSize);
}
/**
* Create a subscription the fills up a third of a bandwidth bucket.
*
* @return the subscription
*/
protected Subscription createSubscriptionThatFillsAThirdOfABucket() {
return createSubscriptionWithDataSetSizeInBytes(thirdBucketSizeInBytes);
}
/**
* Create a subscription the fills up two bandwidth buckets.
*
* @return the subscription
*/
protected Subscription createSubscriptionThatFillsUpTwoBuckets() {
return createSubscriptionWithDataSetSizeInBytes(fullBucketSize * 2);
}
protected Subscription createSubscriptionWithDataSetSizeInBytes(long bytes) {
Subscription subscription = SubscriptionFixture.INSTANCE
.get(subscriptionSeed++);
subscription.setDataSetSize(BandwidthUtil
.convertBytesToKilobytes(bytes));
return subscription;
}
}

View file

@ -0,0 +1,799 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.DataDeliveryRegistryObjectTypes;
import com.raytheon.uf.common.datadelivery.registry.GriddedDataSetMetaData;
import com.raytheon.uf.common.datadelivery.registry.Network;
import com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSetMetaData;
import com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSetMetaDataFixture;
import com.raytheon.uf.common.datadelivery.registry.ParameterFixture;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.datadelivery.registry.SubscriptionFixture;
import com.raytheon.uf.common.datadelivery.registry.Time;
import com.raytheon.uf.common.datadelivery.registry.handlers.DataDeliveryHandlers;
import com.raytheon.uf.common.registry.event.RemoveRegistryEvent;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
import com.raytheon.uf.common.registry.handler.RegistryObjectHandlersUtil;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.time.util.ImmutableDate;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.time.util.TimeUtilTest;
import com.raytheon.uf.common.util.TestUtil;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.BandwidthAllocation;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionDao;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionRetrieval;
import com.raytheon.uf.edex.datadelivery.bandwidth.notification.BandwidthEventBus;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.BandwidthMap;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalPlan;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalPlan.BandwidthBucket;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalPlanTest;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalStatus;
import com.raytheon.uf.edex.datadelivery.retrieval.RetrievalManagerNotifyEvent;
/**
* Integration tests for {@link BandwidthManager}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 12, 2012 0726 djohnson Initial creation
* Oct 23, 2012 1286 djohnson Create reusable abstract int test.
* Dec 11, 2012 1286 djohnson Add test verifying fulfilled retrievals won't cause NPEs when the subscription is updated.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BandwidthManagerIntTest extends AbstractBandwidthManagerIntTest {
@Test
public void testAddingSubscriptionAllocatesOncePerPlanDayForOneCycle()
throws SerializationException {
testSubscriptionCyclesAreAllocatedOncePerCyclePerPlanDay(Arrays
.asList(1));
}
@Test
public void testAddingSubscriptionAllocatesOncePerPlanPerCycle()
throws SerializationException {
testSubscriptionCyclesAreAllocatedOncePerCyclePerPlanDay(Arrays.asList(
1, 2, 3));
}
@Test
public void testDataSetMetaDataUpdateSetsSubscriptionRetrievalsToReady()
throws SerializationException, ParseException {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
bandwidthManager.subscriptionUpdated(subscription);
OpenDapGriddedDataSetMetaData metadata = OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get();
bandwidthManager.updateDataSetMetaData(metadata);
Calendar cal = TimeUtil.newCalendar();
cal.setTime(metadata.getDate());
List<SubscriptionRetrieval> bandwidthAllocations = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName(), cal);
assertEquals("Didn't find the subscription retrieval as expected!", 1,
bandwidthAllocations.size());
assertEquals(RetrievalStatus.READY, bandwidthAllocations.iterator()
.next().getStatus());
}
@Test
public void testDataSetMetaDataUpdateSetsCorrectTimeOnSubscription()
throws SerializationException, ParseException {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
bandwidthManager.subscriptionUpdated(subscription);
OpenDapGriddedDataSetMetaData metadata = OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get();
// Make the metadata for one day later than the subscription
ImmutableDate oneDayLater = new ImmutableDate(metadata.getTime()
.getStartDate().getTime()
+ TimeUtil.MILLIS_PER_DAY);
metadata.getTime().setStartDate(oneDayLater);
metadata.setDate(oneDayLater);
// Send in the update
bandwidthManager.updateDataSetMetaData(metadata);
Calendar cal = TimeUtil.newCalendar();
cal.setTime(metadata.getDate());
List<SubscriptionRetrieval> bandwidthAllocations = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName(), cal);
assertEquals("Didn't find the subscription retrieval as expected!", 1,
bandwidthAllocations.size());
assertEquals(
"Didn't find the metadata date on the retrieval's subscription!",
metadata.getDate(), bandwidthAllocations.iterator().next()
.getSubscription().getTime().getStartDate());
}
@Test
public void testDailyProductSubscriptionReceivesTimeAndUrlFromUpdate()
throws RegistryHandlerException, ParseException,
SerializationException {
RegistryObjectHandlersUtil.initMemory();
// Store the original subscription
Subscription subscription = SubscriptionFixture.INSTANCE.get();
DataDeliveryHandlers.getSubscriptionHandler().store(subscription);
// The dataset metadata update
OpenDapGriddedDataSetMetaData update = OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get();
update.setUrl("http://testDailyProductSubscriptionReceivesTimeAndUrlFromUpdate");
update.setCycle(GriddedDataSetMetaData.NO_CYCLE);
Time dsmdTime = update.getTime();
dsmdTime.setStartDate(new Date(dsmdTime.getStartDate().getTime()
+ TimeUtil.MILLIS_PER_DAY));
bandwidthManager.updateDataSetMetaData(update);
List<SubscriptionRetrieval> retrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
assertEquals("Incorrect number of subscription retrievals generated!",
1, retrievals.size());
SubscriptionRetrieval retrieval = retrievals.iterator().next();
Subscription retrievalSub = retrieval.getSubscription();
assertEquals(
"The update's url doesn't seem to have been persisted to the retrieval!",
update.getUrl(), retrievalSub.getUrl());
assertEquals(
"The update's time doesn't seem to have been persisted to the retrieval!",
dsmdTime.getStartDate(), retrievalSub.getTime().getStartDate());
}
@Test
public void testDailyProductSubscriptionIsSetToReadyStatus()
throws RegistryHandlerException, ParseException {
RegistryObjectHandlersUtil.initMemory();
// Store the original subscription
Subscription subscription = SubscriptionFixture.INSTANCE.get();
subscription.getTime().setCycleTimes(Collections.<Integer> emptyList());
DataDeliveryHandlers.getSubscriptionHandler().store(subscription);
// The dataset metadata update
OpenDapGriddedDataSetMetaData update = OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get();
update.setUrl("http://testDailyProductSubscriptionReceivesTimeAndUrlFromUpdate");
update.setCycle(GriddedDataSetMetaData.NO_CYCLE);
RetrievalPlan plan = retrievalManager.getPlan(subscription.getRoute());
// Remove any buckets that are before or equal to the time of the
// update, as if they were removed by the maintenance task
RetrievalPlanTest.resizePlan(plan, TimeUtil.currentTimeMillis(), plan
.getPlanEnd().getTimeInMillis());
bandwidthManager.updateDataSetMetaData(update);
List<SubscriptionRetrieval> retrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
assertEquals("Incorrect number of subscription retrievals generated!",
1, retrievals.size());
SubscriptionRetrieval retrieval = retrievals.iterator().next();
assertEquals(RetrievalStatus.READY, retrieval.getStatus());
}
@Test
public void testSubscriptionLatencyIsPlacedOnSubscriptionDao()
throws RegistryHandlerException, ParseException {
RegistryObjectHandlersUtil.initMemory();
// Store the original subscription
Subscription subscription = SubscriptionFixture.INSTANCE.get();
subscription.setLatencyInMinutes(5);
DataDeliveryHandlers.getSubscriptionHandler().store(subscription);
// The dataset metadata update
OpenDapGriddedDataSetMetaData update = OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get();
update.setUrl("http://testDailyProductSubscriptionReceivesTimeAndUrlFromUpdate");
update.setCycle(GriddedDataSetMetaData.NO_CYCLE);
RetrievalPlan plan = retrievalManager.getPlan(subscription.getRoute());
// Remove any buckets that are before or equal to the time of the
// update, as if they were removed by the maintenance task
RetrievalPlanTest.resizePlan(plan, TimeUtil.currentTimeMillis(), plan
.getPlanEnd().getTimeInMillis());
bandwidthManager.updateDataSetMetaData(update);
List<SubscriptionRetrieval> retrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
assertEquals("Incorrect number of subscription retrievals generated!",
1, retrievals.size());
SubscriptionRetrieval retrieval = retrievals.iterator().next();
assertEquals(RetrievalStatus.READY, retrieval.getStatus());
}
@Test
public void testScheduleSubscriptionUnableToFitReturnsAllocationsUnscheduled() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
List<BandwidthAllocation> unscheduled = bandwidthManager
.schedule(subscription);
Collections.sort(unscheduled, new Comparator<BandwidthAllocation>() {
@Override
public int compare(BandwidthAllocation o1, BandwidthAllocation o2) {
return o1.getStartTime().compareTo(o2.getStartTime());
}
});
assertTrue(
"Should have been able to schedule all cycles for the first subscription!",
unscheduled.isEmpty());
unscheduled = bandwidthManager.schedule(subscription2);
assertEquals(
"Should have not been able to subscribe for one shared cycle hour for two plan days!",
2, unscheduled.size());
Iterator<BandwidthAllocation> iter = unscheduled.iterator();
BandwidthAllocation hour = iter.next();
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.add(Calendar.DAY_OF_MONTH, 1);
TestUtil.assertCalEquals(
"The 8 hour cycle should not have been schedulable!", cal,
hour.getStartTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
hour = iter.next();
TestUtil.assertCalEquals(
"The 8 hour cycle should not have been schedulable!", cal,
hour.getStartTime());
}
@Test
public void testScheduleSubscriptionWithHigherPriorityUnschedulesOther() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will have higher priority
subscription2.setPriority(subscription.getPriority() + 1);
// they conflict for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
List<BandwidthAllocation> unscheduled = bandwidthManager
.schedule(subscription);
assertTrue(
"Should have been able to schedule all cycles for the first subscription!",
unscheduled.isEmpty());
unscheduled = bandwidthManager.schedule(subscription2);
assertEquals(
"Should have not been able to subscribe for one shared cycle hour for two plan days!",
2, unscheduled.size());
Iterator<BandwidthAllocation> iter = unscheduled.iterator();
BandwidthAllocation unscheduledAllocation = iter.next();
assertEquals(
"The first subscription with lower priority should have been the one unscheduled.",
subscription.getPriority().intValue(),
unscheduledAllocation.getPriority(), 0.0);
unscheduledAllocation = iter.next();
assertEquals(
"The first subscription with lower priority should have been the one unscheduled.",
subscription.getPriority().intValue(),
unscheduledAllocation.getPriority(), 0.0);
}
@Test
public void testScheduleSubscriptionWithHigherPrioritySetsOtherAllocationsToUnscheduled() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will have higher priority
subscription2.setPriority(subscription.getPriority() + 1);
// they conflict for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
List<BandwidthAllocation> unscheduled = bandwidthManager
.schedule(subscription);
assertTrue(
"Should have been able to schedule all cycles for the first subscription!",
unscheduled.isEmpty());
unscheduled = bandwidthManager.schedule(subscription2);
assertEquals(
"Should have not been able to subscribe for one shared cycle hour for two plan days!",
2, unscheduled.size());
Iterator<BandwidthAllocation> iter = unscheduled.iterator();
BandwidthAllocation unscheduledAllocation = iter.next();
assertEquals(
"The first subscription should be set to unscheduled status.",
RetrievalStatus.UNSCHEDULED, unscheduledAllocation.getStatus());
unscheduledAllocation = iter.next();
assertEquals(
"The first subscription should be set to unscheduled status.",
RetrievalStatus.UNSCHEDULED, unscheduledAllocation.getStatus());
}
@Test
public void testScheduleSubscriptionWithHigherPrioritySetsNewAllocationsToScheduled() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will have higher priority
subscription2.setPriority(subscription.getPriority() + 1);
// they conflict for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
bandwidthManager.schedule(subscription);
bandwidthManager.schedule(subscription2);
List<SubscriptionRetrieval> retrievals = bandwidthDao
.getSubscriptionRetrievals(subscription2.getProvider(),
subscription2.getDataSetName());
assertEquals("Incorrect number of subscription retrievals found.", 4,
retrievals.size());
for (SubscriptionRetrieval retrieval : retrievals) {
assertEquals(
"Expected the retrieval to be in the scheduled status!",
RetrievalStatus.SCHEDULED, retrieval.getStatus());
}
}
@Test
public void testTooBigSubscriptionEditedToBeSmallerIsScheduled()
throws SerializationException {
// Subscription starts out too big
Subscription subscription = createSubscriptionThatFillsUpTwoBuckets();
// they conflict for cycle hour 8
subscription.getTime().setCycleTimes(Arrays.asList(Integer.valueOf(6)));
List<BandwidthAllocation> unscheduled = bandwidthManager
.subscriptionUpdated(subscription);
assertFalse(
"Shouldn't have been able to schedule such a large subscription",
unscheduled.isEmpty());
// Hey look, this subscription will fit now!
subscription.setDataSetSize(subscription.getDataSetSize() / 2);
unscheduled = bandwidthManager.subscriptionUpdated(subscription);
assertTrue("Should have been able to schedule the subscription",
unscheduled.isEmpty());
List<SubscriptionRetrieval> retrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
// One per plan day
assertEquals("Incorrect number of subscription retrievals found.", 2,
retrievals.size());
for (SubscriptionRetrieval retrieval : retrievals) {
assertEquals(
"Expected the retrieval to be in the scheduled status!",
RetrievalStatus.SCHEDULED, retrieval.getStatus());
}
}
@Test
public void testDetermineRequiredLatencyReturnsNecessaryLatency()
throws SerializationException {
// Subscription starts out too big
Subscription subscription = createSubscriptionThatFillsUpTwoBuckets();
subscription.getTime().setCycleTimes(Arrays.asList(Integer.valueOf(0)));
subscription.setLatencyInMinutes(0);
int requiredLatency = bandwidthManager
.determineRequiredLatency(subscription);
assertEquals("The required latency was calculated incorrectly", 6,
requiredLatency);
}
/**
* Fulfilled retrievals were causing NPE's when a subscription was updated,
* because the {@link RetrievalPlan} didn't have a {@link BandwidthBucket}
* to remove them from (and it shouldn't have). This test prevents that
* regression.
*
* @throws SerializationException
* better not
*/
@Test
public void fullfilledSubscriptionDoesNotThrowNullPointerOnUpdate()
throws SerializationException {
// Subscription starts out too big
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.getTime().setCycleTimes(Arrays.asList(Integer.valueOf(0)));
subscription.setLatencyInMinutes(0);
bandwidthManager.subscriptionUpdated(subscription);
final List<SubscriptionRetrieval> subscriptionRetrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
for (SubscriptionRetrieval retrieval : subscriptionRetrievals) {
RetrievalManagerNotifyEvent event = new RetrievalManagerNotifyEvent();
event.setId(String.valueOf(retrieval.getId()));
retrievalManager.retrievalCompleted(event);
}
// Now let's go forward a couple days in time, and let the old buckets
// get removed
TimeUtilTest.freezeTime(TimeUtil.currentTimeMillis()
+ (TimeUtil.MILLIS_PER_DAY * 4));
// Technically this would be performed by the bandwidth manager
// maintenance task... is this too much in-depth knowledge of how the
// system is tied together? How can it be abstracted out, maybe move the
// maintenance logic into a bandwidth manager method proper?
retrievalManager.getPlan(subscription.getRoute()).resize();
subscription.setLatencyInMinutes(1);
bandwidthManager.subscriptionUpdated(subscription);
}
/**
* Long-running in-memory bandwidth manager proposed schedule operations
* were causing {@link ConcurrentModificationException}s to occur when
* receiving events from the {@link BandwidthEventBus}.
*
* @throws Exception
* on test failure
*/
@Test
public void testInMemoryBandwidthManagerCanReceiveDataSetMetaDataUpdates()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.getTime().setCycleTimes(Arrays.asList(Integer.valueOf(0)));
bandwidthManager.schedule(subscription);
final BandwidthManager proposed = bandwidthManager
.startProposedBandwidthManager(BandwidthMap
.load(EdexBandwidthContextFactory
.getBandwidthMapConfig()));
final BlockingQueue<Exception> queue = new ArrayBlockingQueue<Exception>(
1);
final int invocationCount = 10;
final CountDownLatch waitForAllThreadsReadyLatch = new CountDownLatch(
invocationCount * 2);
final CountDownLatch doneLatch = new CountDownLatch(invocationCount * 2);
for (int i = 0; i < invocationCount; i++) {
final int current = i;
Thread thread = new Thread() {
@Override
public void run() {
try {
// Wait for all threads to check in, then they all start
// working at once
waitForAllThreadsReadyLatch.countDown();
waitForAllThreadsReadyLatch.await();
proposed.updateDataSetMetaData(OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get(current));
} catch (Exception e) {
queue.offer(e);
}
doneLatch.countDown();
}
};
thread.start();
}
for (int i = 0; i < invocationCount; i++) {
final int current = i;
Thread thread = new Thread() {
@Override
public void run() {
try {
final Subscription subscription2 = SubscriptionFixture.INSTANCE
.get(current);
subscription2.addParameter(ParameterFixture.INSTANCE
.get(1));
subscription2.addParameter(ParameterFixture.INSTANCE
.get(2));
subscription2.addParameter(ParameterFixture.INSTANCE
.get(3));
subscription2.getTime().setCycleTimes(
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17));
subscription2.setLatencyInMinutes(current);
// Wait for all threads to check in, then they all start
// working at once
waitForAllThreadsReadyLatch.countDown();
waitForAllThreadsReadyLatch.await();
proposed.schedule(subscription2);
} catch (Exception e) {
queue.offer(e);
}
doneLatch.countDown();
}
};
thread.start();
}
// Wait for all threads to finish
doneLatch.await();
final Exception exception = queue.poll();
if (exception != null) {
throw exception;
}
}
/**
* Subscriptions that are deleted should have all of their bandwidth
* allocations removed deleted.
*/
@Test
public void testDeletedSubscriptionsHaveAllocationsDeletedFromDatabase()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.getTime().setCycleTimes(Arrays.asList(0, 12));
bandwidthManager.schedule(subscription);
final List<BandwidthAllocation> bandwidthAllocations = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals("Incorrect number of allocations found.", 4,
bandwidthAllocations.size());
sendDeletedSubscriptionEvent(subscription);
final List<BandwidthAllocation> allocationsAfterDelete = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals(
"Expected all bandwidth allocations to have been deleted.", 0,
allocationsAfterDelete.size());
}
/**
* Subscriptions that are deleted should have their SubscriptionDaos
* removed.
*/
@Test
public void testDeletedSubscriptionsHaveSubscriptionDaosDeletedFromDatabase()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.getTime().setCycleTimes(Arrays.asList(0, 12));
bandwidthManager.schedule(subscription);
final List<SubscriptionDao> subscriptionDaos = bandwidthDao
.getSubscriptionDao(subscription);
assertEquals("Incorrect number of subscription daos found.", 4,
subscriptionDaos.size());
sendDeletedSubscriptionEvent(subscription);
final List<BandwidthAllocation> subscriptionDaosAfterDelete = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals("Expected all subscription daos to have been deleted.", 0,
subscriptionDaosAfterDelete.size());
}
/**
* Subscriptions that are deleted should have all of their bandwidth
* allocations removed deleted.
*/
@Test
public void testDeletedSubscriptionsHaveAllocationsDeletedFromRetrievalManager()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.getTime().setCycleTimes(Arrays.asList(0, 12));
bandwidthManager.schedule(subscription);
final Network network = subscription.getRoute();
final List<BandwidthAllocation> bandwidthAllocations = getRetrievalManagerAllocationsForNetwork(network);
assertEquals("Incorrect number of allocations found.", 4,
bandwidthAllocations.size());
System.out.println("allocs: " + bandwidthAllocations);
sendDeletedSubscriptionEvent(subscription);
final List<BandwidthAllocation> allocationsAfterDelete = getRetrievalManagerAllocationsForNetwork(network);
System.out.println("allocs: " + allocationsAfterDelete);
assertEquals(
"Expected all bandwidth allocations to have been deleted.", 0,
allocationsAfterDelete.size());
}
/**
* Subscriptions that are deleted should have all of their bandwidth
* allocations removed deleted.
*/
@Test
public void testDeletedPartiallyScheduledSubscriptionsHaveAllocationsDeleted()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpTwoBuckets();
subscription.getTime().setCycleTimes(Arrays.asList(0, 12));
subscription.setLatencyInMinutes(0);
final List<BandwidthAllocation> unableToSchedule = bandwidthManager
.schedule(subscription);
assertFalse("Shouldn't have been able to fully schedule.",
unableToSchedule.isEmpty());
final List<BandwidthAllocation> bandwidthAllocations = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals("Incorrect number of allocations found.", 4,
bandwidthAllocations.size());
sendDeletedSubscriptionEvent(subscription);
final List<BandwidthAllocation> allocationsAfterDelete = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals(
"Expected all bandwidth allocations to have been deleted.", 0,
allocationsAfterDelete.size());
}
/**
* Subscriptions that are deleted should have their SubscriptionDaos
* removed.
*/
@Test
public void testDeletedPartiallyScheduledSubscriptionsHaveSubscriptionDaosDeleted()
throws Exception {
Subscription subscription = createSubscriptionThatFillsUpTwoBuckets();
subscription.getTime().setCycleTimes(Arrays.asList(0, 12));
subscription.setLatencyInMinutes(0);
final List<BandwidthAllocation> unableToSchedule = bandwidthManager
.schedule(subscription);
assertFalse("Shouldn't have been able to fully schedule.",
unableToSchedule.isEmpty());
final List<SubscriptionDao> subscriptionDaos = bandwidthDao
.getSubscriptionDao(subscription);
assertEquals("Incorrect number of subscription daos found.", 4,
subscriptionDaos.size());
sendDeletedSubscriptionEvent(subscription);
final List<BandwidthAllocation> subscriptionDaosAfterDelete = bandwidthDao
.getBandwidthAllocations(subscription.getRoute());
assertEquals("Expected all subscription daos to have been deleted.", 0,
subscriptionDaosAfterDelete.size());
}
private void testSubscriptionCyclesAreAllocatedOncePerCyclePerPlanDay(
List<Integer> cycles) throws SerializationException {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
subscription.getTime().setCycleTimes(cycles);
try {
bandwidthManager.subscriptionUpdated(subscription);
} catch (Throwable t) {
t.printStackTrace();
}
assertEquals("Incorrect number of bandwidth allocations made!",
retrievalManager.getPlan(subscription.getRoute()).getPlanDays()
* cycles.size(),
bandwidthDao.getBandwidthAllocations(subscription.getRoute())
.size());
}
private void sendDeletedSubscriptionEvent(Subscription subscription) {
RemoveRegistryEvent event = new RemoveRegistryEvent(
subscription.getOwner(), subscription.getId());
event.setObjectType(DataDeliveryRegistryObjectTypes.SUBSCRIPTION);
BandwidthEventBus.publish(event);
}
/**
* @param subscription
* @return
*/
private List<BandwidthAllocation> getRetrievalManagerAllocationsForNetwork(
Network network) {
final SortedSet<BandwidthBucket> buckets = retrievalManager.getPlan(
network).getBucketsInWindow(Long.MIN_VALUE, Long.MAX_VALUE);
List<BandwidthAllocation> allocations = new ArrayList<BandwidthAllocation>();
for (BandwidthBucket bucket : buckets) {
allocations.addAll(bucket.getRequests());
}
return allocations;
}
}

View file

@ -0,0 +1,622 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0ONE_HUNDRED
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.bandwidth.BandwidthService;
import com.raytheon.uf.common.datadelivery.bandwidth.IBandwidthRequest;
import com.raytheon.uf.common.datadelivery.bandwidth.IProposeScheduleResponse;
import com.raytheon.uf.common.datadelivery.bandwidth.data.BandwidthGraphData;
import com.raytheon.uf.common.datadelivery.bandwidth.data.TimeWindowData;
import com.raytheon.uf.common.datadelivery.registry.AdhocSubscription;
import com.raytheon.uf.common.datadelivery.registry.AdhocSubscriptionFixture;
import com.raytheon.uf.common.datadelivery.registry.Network;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.serialization.SerializationUtil;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.BandwidthAllocation;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionRetrieval;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.BandwidthMap;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalPlan.BandwidthBucket;
import com.raytheon.uf.edex.datadelivery.bandwidth.util.BandwidthUtil;
/**
* Tests for the thrift service of {@link BandwidthManager}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 22, 2012 1286 djohnson Initial creation
* Nov 20, 2012 1286 djohnson Add tests for proposeSchedule methods.
* Dec 06, 2012 1397 djohnson Add tests for getting bandwidth graph data.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BandwidthServiceIntTest extends AbstractBandwidthManagerIntTest {
private static final int ONE_HUNDRED = 100;
private final BandwidthService service = new BandwidthService() {
@Override
protected Object sendRequest(IBandwidthRequest request)
throws Exception {
// Serialize and deserialize each call, this makes sure the dynamic
// serialize annotations are correct as well
return SerializationUtil
.transformFromThrift(
Object.class,
SerializationUtil
.transformToThrift(BandwidthServiceIntTest.this.bandwidthManager
.handleRequest(request)));
}
};
@Test
public void testRetrieveBandwidthFromServer() {
assertEquals("Incorrect bandwidth amount retrieved!", 768,
service.getBandwidthForNetworkInKilobytes(Network.OPSNET));
}
@Test
public void testProposeNetworkBandwidthReturnsSubscriptionsUnableToFit() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsHalfABucket();
Subscription subscription2 = createSubscriptionThatFillsHalfABucket();
bandwidthManager.schedule(subscription);
bandwidthManager.schedule(subscription2);
// Now we propose dropping the bandwidth by just one kb/s
Set<Subscription> results = service
.proposeBandwidthForNetworkInKilobytes(Network.OPSNET,
retrievalManager.getPlan(Network.OPSNET)
.getDefaultBandwidth() - 1);
assertEquals(
"Expected one subscription to not have been able to fit with the new bandwidth!",
1, results.size());
}
@Test
public void testProposeNetworkBandwidthReturnsNoSubscriptionsWhenAbleToFit() {
// Two subscriptions that will fill up only a third of a bucket
Subscription subscription = createSubscriptionThatFillsAThirdOfABucket();
Subscription subscription2 = createSubscriptionThatFillsAThirdOfABucket();
bandwidthManager.schedule(subscription);
bandwidthManager.schedule(subscription2);
// Now we propose dropping the bandwidth by just one kb/s
Set<Subscription> results = service
.proposeBandwidthForNetworkInKilobytes(Network.OPSNET,
retrievalManager.getPlan(Network.OPSNET)
.getDefaultBandwidth() - 1);
assertTrue(
"Expected to be able to fit all subscriptions with the new bandwidth!",
results.isEmpty());
}
@Test
public void testSaveBandwidthToServer() {
service.setBandwidthForNetworkInKilobytes(Network.OPSNET, ONE_HUNDRED);
assertEquals(
"Expected the bandwidth to have been saved to the in memory bandwidth route!",
ONE_HUNDRED,
service.getBandwidthForNetworkInKilobytes(Network.OPSNET));
}
@Test
public void testSaveBandwidthToServerUpdatesBandwidthMapFile() {
service.setBandwidthForNetworkInKilobytes(Network.OPSNET, ONE_HUNDRED);
File file = new IntegrationTestBandwidthContextFactory()
.getBandwidthMapConfigFile();
BandwidthMap map = BandwidthMap.load(file);
assertEquals(
"Expected the bandwidth to have been saved to the configuration file!",
ONE_HUNDRED, map.getRoute(Network.OPSNET).getDefaultBandwidth());
}
@Test
public void testSaveBandwidthToServerReinitializesBandwidthMap() {
service.setBandwidthForNetworkInKilobytes(Network.OPSNET, ONE_HUNDRED);
// Just check for a bucket with an expected amount of bytes size
SortedSet<BandwidthBucket> bucketsInWindow = EdexBandwidthContextFactory
.getInstance().retrievalManager.getPlan(Network.OPSNET)
.getBucketsInWindow(
TimeUtil.currentTimeMillis(),
TimeUtil.currentTimeMillis()
+ (5 * TimeUtil.MILLIS_PER_MINUTE));
BandwidthBucket bucket = bucketsInWindow.iterator().next();
assertEquals(
"The BandwidthManager does not seem to have been reinitialized!",
BandwidthUtil
.convertKilobytesPerSecondToBytesPerSpecifiedMinutes(
ONE_HUNDRED, 3), bucket.getBucketSize());
}
@Test
public void testScheduleTwoSubscriptionsThatFitReturnsEmptyList() {
// Two subscriptions, the sum of which will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsHalfABucket();
Subscription subscription2 = createSubscriptionThatFillsHalfABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.schedule(Arrays.asList(
subscription, subscription2));
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
}
@Test
public void testScheduleTwoSubscriptionsSecondDoesNotFitReturnsSecondsName() {
Subscription subscription = createSubscriptionThatFillsHalfABucket();
// Requires its own full bucket, so cycle hour 3 will succeed and cycle
// hour 8 will not
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.schedule(Arrays.asList(
subscription, subscription2));
verifySubscriptionWasNotAbleToBeFullyScheduled(
unscheduledSubscriptions, subscription2);
}
@Test
public void testScheduleSubscriptionReturnsNamesOfUnscheduledSubscriptions() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.schedule(subscription);
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
unscheduledSubscriptions = service.schedule(subscription2);
verifySubscriptionWasNotAbleToBeFullyScheduled(
unscheduledSubscriptions, subscription2);
}
@Test
public void testProposeScheduleTwoSubscriptionsThatFitReturnsEmptyList() {
// Two subscriptions, the sum of which will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsHalfABucket();
Subscription subscription2 = createSubscriptionThatFillsHalfABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
IProposeScheduleResponse response = service.proposeSchedule(Arrays
.asList(subscription, subscription2));
Set<String> unscheduledSubscriptions = response
.getUnscheduledSubscriptions();
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
}
@Test
public void testProposeScheduleTwoSubscriptionsThatFitReturnsNotSetRequiredLatency() {
// Two subscriptions, the sum of which will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsHalfABucket();
Subscription subscription2 = createSubscriptionThatFillsHalfABucket();
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
IProposeScheduleResponse response = service.proposeSchedule(Arrays
.asList(subscription, subscription2));
assertEquals(
"Expected the required latency to not be set when the propose schedule fits",
IProposeScheduleResponse.REQUIRED_LATENCY_NOT_SET,
response.getRequiredLatency());
}
@Test
public void testProposeScheduleTwoSubscriptionsSecondDoesNotFitReturnsSecondsName() {
// Two subscriptions, the sum of which will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsHalfABucket();
// Requires its own full bucket, so cycle hour 3 will succeed and cycle
// hour 8 will not
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.proposeSchedule(
Arrays.asList(subscription, subscription2))
.getUnscheduledSubscriptions();
verifySubscriptionWasNotAbleToBeFullyScheduled(
unscheduledSubscriptions, subscription2);
}
@Test
public void testProposeScheduleSubscriptionReturnsNamesOfUnscheduledSubscriptions() {
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.schedule(subscription);
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
unscheduledSubscriptions = service.proposeSchedule(subscription2)
.getUnscheduledSubscriptions();
verifySubscriptionWasNotAbleToBeFullyScheduled(
unscheduledSubscriptions, subscription2);
}
@Test
public void testProposeScheduleSubscriptionsSecondDoesntFitReturnsRequiredLatency() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(3), Integer.valueOf(8)));
Set<String> unscheduledSubscriptions = service.schedule(subscription);
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
int requiredLatency = service.proposeSchedule(subscription2)
.getRequiredLatency();
assertEquals(
"The required latency should have been returned from propose schedule!",
6, requiredLatency);
}
@Test
public void testReinitializeStartsNewBandwidthManager() {
BandwidthManager originalBandwidthManager = BandwidthServiceIntTest.this.bandwidthManager;
service.reinitialize();
assertNotSame(
"Expected the BandwidthManager instance to have been replaced",
originalBandwidthManager,
EdexBandwidthContextFactory.getInstance());
}
@Test
public void testGetEstimatedCompletionTimeReturnsLastBucketTimeForSubscription() {
AdhocSubscription subscription = AdhocSubscriptionFixture.INSTANCE
.get();
subscription.getTime().setCycleTimes(Arrays.asList(Integer.valueOf(0)));
subscription.setDataSetSize(createSubscriptionThatFillsUpABucket()
.getDataSetSize());
Set<String> unscheduledSubscriptions = service.schedule(subscription);
verifyNoSubscriptionsWereUnscheduled(unscheduledSubscriptions);
// Jan 2, 18:00 CST
Date expected = new Date(172800000L);
Date actual = service.getEstimatedCompletionTime(subscription);
assertEquals("Received incorrect estimated completion time!", expected,
actual);
}
@Test
public void testGetBandwidthGraphDataReturnsCorrectNumberOfSubscriptionNames() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime()
.setCycleTimes(Arrays.asList(Integer.valueOf(3)));
service.schedule(subscription);
service.schedule(subscription2);
BandwidthGraphData graphData = service.getBandwidthGraphData();
assertEquals("Incorrect number of subscriptions returned!", 2,
graphData.getNumberOfSubscriptions());
}
@Test
public void testGetBandwidthGraphDataReturnsCorrectBinMinutes() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime()
.setCycleTimes(Arrays.asList(Integer.valueOf(3)));
service.schedule(subscription);
service.schedule(subscription2);
BandwidthGraphData graphData = service.getBandwidthGraphData();
assertEquals("Incorrect number of subscriptions returned!",
retrievalManager.getPlan(Network.OPSNET).getBucketMinutes(),
graphData.getBinTimeInMinutes());
}
@Test
public void testGetBandwidthGraphDataForFragmentedSubscription() {
Subscription subscription = createSubscriptionThatFillsUpTwoBuckets();
subscription.setLatencyInMinutes(6);
subscription.setPriority(2);
// Reserves a full bucket at 19700103 18:03:00 which fragments the
// subscription to 19700103 18:00:00 and 18:06:00
BandwidthAllocation allocation = createAllocationToReserveMiddleBucket(subscription);
retrievalManager.schedule(Arrays.asList(allocation));
bandwidthManager.schedule(subscription);
BandwidthGraphData graphData = service.getBandwidthGraphData();
final Map<String, List<TimeWindowData>> dataMap = graphData
.getDataMap();
final List<TimeWindowData> subscriptionOneTimeWindows = dataMap
.get(subscription.getName());
assertEquals(
"Expected there to be two time windows for this subscription over 2 days",
2, subscriptionOneTimeWindows.size());
final TimeWindowData firstTimeWindow = subscriptionOneTimeWindows
.get(0);
final TimeWindowData secondTimeWindow = subscriptionOneTimeWindows
.get(1);
final List<Long> firstWindowBinStartTimes = firstTimeWindow.getBinStartTimes();
final List<Long> secondWindowBinStartTimes = secondTimeWindow
.getBinStartTimes();
assertEquals("Incorrect number of bin start times found.", 2,
firstWindowBinStartTimes.size());
assertEquals("Incorrect number of bin start times found.", 2,
secondWindowBinStartTimes.size());
final List<SubscriptionRetrieval> subscriptionRetrievals = bandwidthDao
.getSubscriptionRetrievals(subscription.getProvider(),
subscription.getDataSetName());
final Iterator<SubscriptionRetrieval> iter = subscriptionRetrievals
.iterator();
// First retrieval window
long expectedBinStartTime = iter.next().getStartTime()
.getTimeInMillis();
assertEquals(
"Incorrect first bin start time in the first time window.",
expectedBinStartTime, firstWindowBinStartTimes
.get(0).longValue());
expectedBinStartTime += (TimeUtil.MILLIS_PER_MINUTE * 3);
assertEquals(
"Incorrect second bin start time in the first time window.",
expectedBinStartTime,
firstWindowBinStartTimes.get(1).longValue());
// Second retrieval window
expectedBinStartTime = iter.next().getStartTime().getTimeInMillis();
assertEquals(
"Incorrect first bin start time in the second time window.",
expectedBinStartTime,
secondWindowBinStartTimes
.get(0).longValue());
// The middle bucket was already reserved, so we went ahead six minutes
// and used that bucket
expectedBinStartTime += (TimeUtil.MILLIS_PER_MINUTE * 6);
assertEquals(
"Incorrect second bin start time in the second time window.",
expectedBinStartTime,
secondWindowBinStartTimes.get(1).longValue());
}
@Test
public void testGetBandwidthGraphDataReturnsCorrectTimeWindowsForSubscriptions() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsUpABucket();
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime()
.setCycleTimes(Arrays.asList(Integer.valueOf(3)));
service.schedule(subscription);
service.schedule(subscription2);
BandwidthGraphData graphData = service.getBandwidthGraphData();
final Map<String, List<TimeWindowData>> dataMap = graphData
.getDataMap();
final List<TimeWindowData> subscriptionOneTimeWindows = dataMap
.get(subscription.getName());
final List<TimeWindowData> subscriptionTwoTimeWindows = dataMap
.get(subscription2.getName());
assertEquals(
"Expected there to be four retrievals for this subscription over 2 days",
4, subscriptionOneTimeWindows.size());
assertEquals(
"Expected there to be two retrievals for this subscription over 2 days",
2, subscriptionTwoTimeWindows.size());
}
@Test
public void testGetBandwidthGraphDataReturnsCorrectPrioritiesForSubscriptions() {
// Two subscriptions that will fill up a bucket exactly
Subscription subscription = createSubscriptionThatFillsUpABucket();
subscription.setPriority(2);
Subscription subscription2 = createSubscriptionThatFillsUpABucket();
subscription.setPriority(4);
// subscription2 will not be able to schedule for cycle hour 8
subscription.getTime().setCycleTimes(
Arrays.asList(Integer.valueOf(6), Integer.valueOf(8)));
subscription2.getTime()
.setCycleTimes(Arrays.asList(Integer.valueOf(3)));
service.schedule(subscription);
service.schedule(subscription2);
BandwidthGraphData graphData = service.getBandwidthGraphData();
final Map<String, Integer> priorityMap = graphData.getPriorityMap();
assertThat(priorityMap.get(subscription.getName()),
is(equalTo(subscription.getPriority())));
assertThat(priorityMap.get(subscription2.getName()),
is(equalTo(subscription2.getPriority())));
}
/**
* Creates a BandwidthAllocation that will fill up a bucket and reserve
* itself for 01/03/1970 18:03:00
*
* @return the allocation
*/
private BandwidthAllocation createAllocationToReserveMiddleBucket(
Subscription subscription) {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 3);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
BandwidthAllocation allocation = new BandwidthAllocation();
allocation.setStartTime(cal);
allocation.setEndTime(cal);
allocation.setNetwork(subscription.getRoute());
allocation.setPriority(2);
allocation.setAgentType("someAgent");
allocation.setEstimatedSize(subscription.getDataSetSize() / 2);
return allocation;
}
/**
* Verify that no subscriptions were unscheduled.
*
* @param unscheduledSubscriptions
* the set of subscription names returned from the operation
*/
private static void verifyNoSubscriptionsWereUnscheduled(
Set<String> unscheduledSubscriptions) {
assertTrue("There should not be any unscheduled subscriptions.",
unscheduledSubscriptions.isEmpty());
}
/**
* Verify that the specific subscription name was returned as unscheduled in
* the results.
*
* @param unscheduledSubscriptions
* the set of unscheduled subscription names
* @param subscription
* the subscription
*/
private static void verifySubscriptionWasNotAbleToBeFullyScheduled(
Set<String> unscheduledSubscriptions, Subscription subscription) {
assertEquals(
"One and only one subscription should not have been able to fully schedule",
1, unscheduledSubscriptions.size());
assertEquals("The wrong subscription name was returned as unscheduled",
subscription.getName(), unscheduledSubscriptions.iterator()
.next());
}
}

View file

@ -0,0 +1,74 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.BandwidthContextFactory;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDao;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDbInit;
import com.raytheon.uf.edex.datadelivery.bandwidth.interfaces.BandwidthInitializer;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalManager;
import com.raytheon.uf.edex.datadelivery.bandwidth.util.BandwidthDaoUtil;
/**
* The {@link BandwidthContextFactory} implementation for integration tests.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 24, 2012 1286 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class IntegrationTestBandwidthContextFactory extends
EdexBandwidthContextFactory {
/**
* {@inheritDoc}
*/
@Override
public IBandwidthDbInit getBandwidthDbInit() {
return new IntegrationTestDbInit();
}
/**
* {@inheritDoc}
*/
@Override
public BandwidthInitializer getBandwidthInitializer() {
return new IntegrationTestBandwidthInitializer();
}
/**
* {@inheritDoc}
*/
@Override
public IBandwidthManager getBandwidthManager(IBandwidthDbInit dbInit,
IBandwidthDao bandwidthDao, RetrievalManager retrievalManager,
BandwidthDaoUtil bandwidthDaoUtil) {
return new IntegrationTestBandwidthManager(dbInit, bandwidthDao,
retrievalManager, bandwidthDaoUtil);
}
}

View file

@ -0,0 +1,53 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDbInit;
import com.raytheon.uf.edex.datadelivery.bandwidth.interfaces.BandwidthInitializer;
/**
* Integration test {@link BandwidthInitializer}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 12, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class IntegrationTestBandwidthInitializer implements
BandwidthInitializer {
/**
* {@inheritDoc}
*/
@Override
public boolean init(IBandwidthManager instance, IBandwidthDbInit dbInit) {
return true;
}
}

View file

@ -0,0 +1,73 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import com.raytheon.uf.common.util.TestUtil;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDao;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDbInit;
import com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.RetrievalManager;
import com.raytheon.uf.edex.datadelivery.bandwidth.util.BandwidthDaoUtil;
/**
* An {@link IBandwidthManager} that runs as an integration test, outside of the
* EDEX container.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 30, 2012 1286 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class IntegrationTestBandwidthManager extends BandwidthManager {
static final String[] INTEGRATION_TEST_SPRING_FILES = new String[] {
"/bandwidth/bandwidth-datadelivery-integrationtest-impl.xml",
TestUtil.getResResourcePath("/spring/bandwidth-datadelivery.xml") };
/**
* Constructor.
*
* @param dbInit
* @param bandwidthDao
* @param retrievalManager
* @param bandwidthDaoUtil
*/
public IntegrationTestBandwidthManager(IBandwidthDbInit dbInit,
IBandwidthDao bandwidthDao, RetrievalManager retrievalManager,
BandwidthDaoUtil bandwidthDaoUtil) {
super(dbInit, bandwidthDao, retrievalManager, bandwidthDaoUtil);
}
/**
* {@inheritDoc}
*/
@Override
protected String[] getSpringFilesForNewInstance() {
return INTEGRATION_TEST_SPRING_FILES;
}
}

View file

@ -0,0 +1,72 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.datadelivery.bandwidth;
import java.sql.SQLException;
import org.hibernate.cfg.AnnotationConfiguration;
import com.raytheon.uf.edex.datadelivery.bandwidth.dao.IBandwidthDbInit;
/**
* Implements database initialization task to do nothing.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 12, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class IntegrationTestDbInit implements IBandwidthDbInit {
/**
* {@inheritDoc}
*/
@Override
public void init() {
// Nothing required
}
/**
* {@inheritDoc}
*/
@Override
public void dropTables(AnnotationConfiguration aConfig) throws SQLException {
// Nothing required
}
/**
* {@inheritDoc}
*/
@Override
public void createTables(AnnotationConfiguration aConfig)
throws SQLException {
// Nothing required
}
}

View file

@ -0,0 +1,6 @@
PROJECTS.DIR=${basedir}/..
BUILD.EDEX.DIR=${PROJECTS.DIR}/build.edex
BUILD.EDEX.DIST.DIR=${BUILD.EDEX.DIR}/edex/dist
# Currently can't run viz plugin based tests after build
TEST.EXCLUSION.PATTERN=**/uf/viz/**

BIN
tests/lib/hsqldb.jar Normal file

Binary file not shown.

View file

@ -0,0 +1,28 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="bandwidthContextFactory"
class="com.raytheon.uf.edex.datadelivery.bandwidth.IntegrationTestBandwidthContextFactory" />
<bean
class="com.raytheon.uf.edex.datadelivery.bandwidth.EdexBandwidthContextFactory">
<constructor-arg ref="bandwidthManager" />
</bean>
<bean id="registryManagerInstanceInitializer" class="java.lang.String">
<!-- required for depends-on -->
</bean>
<bean id="registerDataDeliveryHandlers" class="java.lang.String">
<!-- required for depends-on -->
</bean>
<bean id="retrievalAgents" class="java.util.Collections"
factory-method="emptyMap">
<!-- No retrievals for integration test -->
</bean>
</beans>

View file

@ -0,0 +1,8 @@
# BandwidthManagement properties for testing
bandwidth.dataSetMetaDataPoolSize=1
bandwidth.retrievalPoolSize=1
bandwidth.subscriptionPoolSize=1
# 0 availability delay to make math simple
bandwidth.dataSetAvailabilityCalculator.delay=0
bandwidth.subscription.latency=0
bandwidth.default.retrieval.priority=3

View file

@ -0,0 +1,39 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- These handlers are in-memory handlers -->
<bean name="SubscriptionHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemorySubscriptionHandler" />
<bean name="PendingSubscriptionHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryPendingSubscriptionHandler" />
<bean name="GroupDefinitionHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryGroupDefinitionHandler" />
<bean name="ProviderHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryProviderHandler" />
<bean name="DataSetNameHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryDataSetNameHandler" />
<bean name="ParameterHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryParameterHandler" />
<bean name="ParameterLevelHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryParameterLevelHandler" />
<bean name="DataSetMetaDataHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryDataSetMetaDataHandler" />
<bean name="GriddedDataSetMetaDataHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryGriddedDataSetMetaDataHandler" />
<bean name="DataSetHandler"
class="com.raytheon.uf.common.datadelivery.registry.handlers.MemoryDataSetHandler" />
</beans>

View file

@ -0,0 +1,70 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- These handlers are mock handlers create by Mockito,
which allow verifications of method invocations -->
<bean name="SubscriptionHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.ISubscriptionHandler" />
</bean>
<bean name="PendingSubscriptionHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IPendingSubscriptionHandler" />
</bean>
<bean name="GroupDefinitionHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IGroupDefinitionHandler" />
</bean>
<bean name="ProviderHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IProviderHandler" />
</bean>
<bean name="DataSetNameHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IDataSetNameHandler" />
</bean>
<bean name="ParameterHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IParameterHandler" />
</bean>
<bean name="ParameterLevelHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IParameterLevelHandler" />
</bean>
<bean name="DataSetMetaDataHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IDataSetMetaDataHandler" />
</bean>
<bean name="GriddedDataSetMetaDataHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IGriddedDataSetMetaDataHandler" />
</bean>
<bean name="DataSetHandler" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="com.raytheon.uf.common.datadelivery.registry.handlers.IDataSetHandler" />
</bean>
</beans>

View file

@ -0,0 +1,37 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:mem:unit-testing" />
<property name="username" value="sa" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="metadataSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.raytheon.uf.edex.datadelivery.bandwidth.dao.BandwidthAllocation</value>
<value>com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionRetrieval</value>
<value>com.raytheon.uf.edex.datadelivery.bandwidth.dao.DataSetMetaDataDao</value>
<value>com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionDao</value>
<value>com.raytheon.uf.edex.datadelivery.retrieval.db.RetrievalRequestRecord</value>
</list>
</property>
<property name="configLocation">
<value>classpath:unit-test-hibernate.cfg.xml</value>
</property>
</bean>
<bean id="metadataTxManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="metadataSessionFactory" />
</bean>
</beans>

View file

@ -0,0 +1,17 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">false</property>
<property name="hibenate.format_sql">false</property>
<property name="hibernate.use_sql_comments">false</property>
<property name="hibernate.generate_statistics">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.jdbc.use_streams_for_binary">false</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="cache.use_query_cache">false</property>
</session-factory>
</hibernate-configuration>

View file

@ -0,0 +1,60 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} for {@link AdhocSubscription}s.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Nov 7, 2012 1286 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class AdhocSubscriptionFixture extends
BaseSubscriptionFixture<AdhocSubscription> {
public static final AdhocSubscriptionFixture INSTANCE = new AdhocSubscriptionFixture();
/**
* Private constructor.
*/
private AdhocSubscriptionFixture() {
}
/**
* {@inheritDoc}
*/
@Override
protected AdhocSubscription getSubscription() {
return new AdhocSubscription();
}
}

View file

@ -0,0 +1,100 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.util.Date;
import java.util.Random;
import com.google.common.collect.Lists;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* Move in reusable code from {@link SubscriptionFixture}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 27, 2012 1187 djohnson Initial creation
* Oct 16, 2012 0726 djohnson Use other fixtures to get appropriate values.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public abstract class BaseSubscriptionFixture<T extends Subscription> extends
AbstractFixture<T> {
/**
* {@inheritDoc}
*/
@Override
public T get(long seedValue) {
Random random = new Random(seedValue);
T subscription = getSubscription();
subscription.setActive(random.nextBoolean());
subscription.setActivePeriodStart(TimeUtil.newDate());
subscription.setActivePeriodEnd(new Date(subscription
.getActivePeriodStart().getTime() + seedValue));
// TODO: Create coverage fixture
// subscription.setCoverage(coverage)
subscription
.setDataSetName(OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get(seedValue).getDataSetName());
subscription.setDataSetSize(seedValue);
subscription.setDataSetType(AbstractFixture.randomEnum(DataType.class,
random));
subscription.setDeleted(random.nextBoolean());
subscription.setDescription("description" + random.nextInt());
subscription.setFullDataSet(random.nextBoolean());
subscription.setGroupName("group" + random.nextInt());
subscription.setName("name" + random.nextInt());
subscription.setNotify(random.nextBoolean());
subscription.setOfficeID("officeID" + random.nextInt());
subscription.setOwner("owner" + random.nextInt());
subscription.setParameter(Lists.<Parameter> newArrayList());
// Same priority for all, individual tests needing to test specific
// priorities should set it manually anyway
subscription.setPriority(1);
subscription.setProvider(ProviderFixture.INSTANCE.get(seedValue)
.getName());
subscription.setSubscriptionStart(subscription.getActivePeriodStart());
subscription.setSubscriptionEnd(null);
subscription.setSubscriptionId("subscriptionId" + random.nextInt());
subscription.setTime(TimeFixture.INSTANCE.get(seedValue));
subscription.setUrl("http://someurl/" + random.nextInt());
subscription.setId(RegistryUtil.getRegistryObjectKey(subscription));
return subscription;
}
/**
* @return
*/
protected abstract T getSubscription();
}

View file

@ -0,0 +1,63 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for {@link DataLevelType} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 07, 2012 1104 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class DataLevelTypeFixture extends AbstractFixture<DataLevelType> {
public static final DataLevelTypeFixture INSTANCE = new DataLevelTypeFixture();
/**
* Disabled constructor.
*/
private DataLevelTypeFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public DataLevelType get(long seedValue) {
DataLevelType obj = new DataLevelType();
// TODO: Populate attributes
return obj;
}
}

View file

@ -0,0 +1,119 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import javax.xml.bind.JAXBException;
import org.junit.Test;
import com.raytheon.uf.common.serialization.SerializationUtil;
import com.raytheon.uf.common.serialization.SerializationUtilTest;
import com.raytheon.uf.common.time.util.ImmutableDate;
import com.raytheon.uf.common.util.TestUtil;
/**
* Test {@link DataSetMetaData}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 31, 2012 djohnson Initial creation
* Sep 07, 2012 1102 djohnson Add test for compareTo.
* Sep 19, 2012 726 jspinks Add test for Date serialization
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class DataSetMetaDataTest {
private final DataSetMetaData objectUnderTest = getDataSetMetaData(3L,
"someUrl");
private final DataSetMetaData equal = getDataSetMetaData(objectUnderTest
.getDate().getTime(), objectUnderTest.getUrl());
private final DataSetMetaData notEqual = getDataSetMetaData(4L,
"someOtherUrl");
@Test
public void testEqualsAndHashCodeContract() {
TestUtil.assertEqualsAndHashcodeContract(objectUnderTest,
Arrays.asList(equal), Arrays.asList(notEqual));
}
@Test
public void testDateComparator() {
final DataSetMetaData lessThan = getDataSetMetaData(1L, "someUrl");
final DataSetMetaData greaterThanObject = notEqual;
assertTrue(DataSetMetaData.DATE_COMPARATOR.compare(objectUnderTest,
lessThan) > 0);
assertTrue(DataSetMetaData.DATE_COMPARATOR.compare(objectUnderTest,
greaterThanObject) < 0);
assertEquals(0,
DataSetMetaData.DATE_COMPARATOR.compare(objectUnderTest, equal));
}
@Test
public void testDateSerialization() throws JAXBException {
SerializationUtilTest.initSerializationUtil();
OpenDapGriddedDataSetMetaData objectUnderTest =
OpenDapGriddedDataSetMetaDataFixture.INSTANCE.get();
final ImmutableDate original = objectUnderTest.getDate();
final String xml = SerializationUtil.marshalToXml(objectUnderTest);
OpenDapGriddedDataSetMetaData o = SerializationUtil.unmarshalFromXml(OpenDapGriddedDataSetMetaData.class, xml);
assertEquals(original, o.getDate());
}
/**
* Get a {@link DataSetMetaData} instance with the specified fields.
*
* @param dateAsTime
* the date as milliseconds
* @param url
* the url to use
* @return the instance
*/
private static DataSetMetaData getDataSetMetaData(long dateAsTime,
String url) {
final DataSetMetaData object = new DataSetMetaData() {
@Override
public void accept(IDataSetMetaDataVisitor visitor) {
}
};
object.setDate(new ImmutableDate(dateAsTime));
object.setUrl(url);
return object;
}
}

View file

@ -0,0 +1,49 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test {@link GriddedDataSetMetaData}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 26, 2012 955 djohnson Initial creation
* Aug 20, 2012 0743 djohnson Remove null/string cycle tests.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
@Ignore
public class GriddedDataSetMetaDataTest {
@Test
public void testSomething() {
}
}

View file

@ -0,0 +1,65 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for
* {@link OpenDapGriddedDataSetMetaData} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 05, 2012 1102 djohnson Initial creation
* Oct 16, 2012 0726 djohnson Always use OpenDAP service type, use TimeFixture.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class LevelsFixture extends AbstractFixture<Levels> {
public static final LevelsFixture INSTANCE = new LevelsFixture();
/**
* Disabled constructor.
*/
private LevelsFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public Levels get(long seedValue) {
Levels obj = new Levels();
// TODO: Populate attributes
return obj;
}
}

View file

@ -0,0 +1,86 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import com.raytheon.uf.common.util.AbstractFixture;
import com.raytheon.uf.common.util.CollectionUtil;
/**
* {@link AbstractFixture} implementation for {@link OpenDapGriddedDataSet}
* objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 07, 2012 1104 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class OpenDapGriddedDataSetFixture extends
AbstractFixture<OpenDapGriddedDataSet> {
public static final OpenDapGriddedDataSetFixture INSTANCE = new OpenDapGriddedDataSetFixture();
/**
* Disabled constructor.
*/
private OpenDapGriddedDataSetFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public OpenDapGriddedDataSet get(long seedValue) {
OpenDapGriddedDataSet obj = new OpenDapGriddedDataSet();
obj.setCollectionName("collectionName-" + seedValue);
// TODO: CoverageFixture
// obj.setCoverage(CoverageFixture.INSTANCE.get(seedValue));
obj.setCycles(new TreeSet<Integer>(Arrays.asList(TimeFixture.getCycleForSeed(seedValue))));
Map<Integer, String> cyclesToUrls = new HashMap<Integer, String>();
for (Integer cycle : obj.getCycles()) {
cyclesToUrls.put(cycle, "http://someurl");
obj.cycleUpdated(cycle);
}
obj.setCyclesToUrls(cyclesToUrls);
obj.setDataSetName("dataSetName" + seedValue);
obj.setDataSetType(DataType.GRID);
obj.setForecastHours(CollectionUtil.asSet(0));
// TODO: ParameterFixture
obj.setParameters(Collections.<String, Parameter> emptyMap());
obj.setProviderName(ProviderFixture.INSTANCE.get(seedValue).getName());
return obj;
}
}

View file

@ -0,0 +1,86 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.text.ParseException;
import com.raytheon.uf.common.time.util.ImmutableDate;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for
* {@link OpenDapGriddedDataSetMetaData} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 05, 2012 1102 djohnson Initial creation
* Oct 16, 2012 0726 djohnson Always use OpenDAP service type, use TimeFixture.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class OpenDapGriddedDataSetMetaDataFixture extends
AbstractFixture<OpenDapGriddedDataSetMetaData> {
public static final OpenDapGriddedDataSetMetaDataFixture INSTANCE = new OpenDapGriddedDataSetMetaDataFixture();
/**
* Disabled constructor.
*/
private OpenDapGriddedDataSetMetaDataFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public OpenDapGriddedDataSetMetaData get(long seedValue) {
final Time time = TimeFixture.INSTANCE.get(seedValue);
final OpenDapGriddedDataSet dataSet = OpenDapGriddedDataSetFixture.INSTANCE
.get(seedValue);
OpenDapGriddedDataSetMetaData obj = new OpenDapGriddedDataSetMetaData();
obj.setCycle(TimeFixture.getCycleForSeed(seedValue));
obj.setDataSetDescription("description" + seedValue);
obj.setDataSetName(dataSet.getDataSetName());
try {
obj.setDate(new ImmutableDate(time.getStartDate()));
} catch (ParseException e) {
throw new RuntimeException(e);
}
// TODO: Ensemble fixture
// obj.setEnsemble(new EnsembleFixture().get(seedValue));
// TODO: Levels fixture
// obj.setLevelTypes(levelTypes);
obj.setProviderName(dataSet.getProviderName());
obj.setTime(time);
obj.setUrl("http://" + seedValue);
return obj;
}
}

View file

@ -0,0 +1,125 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Iterator;
import org.junit.Test;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.serialization.SerializationUtil;
/**
* Test {@link OpenDapGriddedDataSet}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 10, 2012 1022 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class OpenDapGriddedDataSetTest {
@Test
public void testCombineWillOverwriteCycleInformation() {
OpenDapGriddedDataSet oldOne = new OpenDapGriddedDataSet();
oldOne.cycleUpdated(0);
oldOne.cycleUpdated(1);
oldOne.getCyclesToUrls().put(0, "url0");
oldOne.getCyclesToUrls().put(1, "url1");
OpenDapGriddedDataSet newOne = new OpenDapGriddedDataSet();
newOne.cycleUpdated(0);
newOne.getCyclesToUrls().put(0, "newurl0");
newOne.combine(oldOne);
Iterator<Integer> iter = newOne.newestToOldestIterator();
assertEquals(0, iter.next().intValue());
assertEquals(1, iter.next().intValue());
assertEquals("newurl0", newOne.getCyclesToUrls().get(0));
assertEquals("url1", newOne.getCyclesToUrls().get(1));
}
@Test
public void testRemovesAllOldVersionsOfElement() {
OpenDapGriddedDataSet dataSet = new OpenDapGriddedDataSet();
dataSet.cycleUpdated(1);
dataSet.cycleUpdated(1);
dataSet.cycleUpdated(1);
// Should still just have one occurrence
Iterator<Integer> cycleIter = dataSet.newestToOldestIterator();
assertTrue(cycleIter.hasNext());
cycleIter.next();
assertFalse(cycleIter.hasNext());
}
@Test
public void testIteratesFromNewestToOldest() {
OpenDapGriddedDataSet dataSet = new OpenDapGriddedDataSet();
dataSet.cycleUpdated(1);
dataSet.cycleUpdated(2);
Iterator<Integer> cycleIter = dataSet.newestToOldestIterator();
assertEquals(2, cycleIter.next().intValue());
assertEquals(1, cycleIter.next().intValue());
}
@Test
public void testIteratesFromOldestToNewest() {
OpenDapGriddedDataSet dataSet = new OpenDapGriddedDataSet();
dataSet.cycleUpdated(1);
dataSet.cycleUpdated(2);
Iterator<Integer> cycleIter = dataSet.oldestToNewestIterator();
assertEquals(1, cycleIter.next().intValue());
assertEquals(2, cycleIter.next().intValue());
}
@Test
public void testDynamicSerializeAndUnserializeRestoresProperCycleUpdates()
throws SerializationException {
OpenDapGriddedDataSet dataSet = new OpenDapGriddedDataSet();
dataSet.cycleUpdated(1);
dataSet.cycleUpdated(2);
byte[] serialized = SerializationUtil.transformToThrift(dataSet);
OpenDapGriddedDataSet unserialized = (OpenDapGriddedDataSet) SerializationUtil
.transformFromThrift(serialized);
Iterator<Integer> iter = unserialized.newestToOldestIterator();
assertEquals(2, iter.next().intValue());
assertEquals(1, iter.next().intValue());
}
}

View file

@ -0,0 +1,73 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.util.Arrays;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for {@link Parameter} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 07, 2012 1104 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class ParameterFixture extends AbstractFixture<Parameter> {
public static final ParameterFixture INSTANCE = new ParameterFixture();
/**
* Disabled constructor.
*/
private ParameterFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public Parameter get(long seedValue) {
Parameter obj = new Parameter();
obj.setBaseType("baseType" + seedValue);
obj.setDataType(DataType.GRID);
obj.setDefinition("definition" + seedValue);
obj.setEnsemble(0);
obj.setFillValue("fillValue" + seedValue);
obj.setLevels(LevelsFixture.INSTANCE.get(seedValue));
obj.setLevelType(Arrays.asList(DataLevelTypeFixture.INSTANCE
.get(seedValue)));
obj.setMissingValue("missingValue" + seedValue);
obj.setName("name" + seedValue);
return obj;
}
}

View file

@ -0,0 +1,72 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for {@link PendingSubscription}
* objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 28, 2012 1187 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class PendingSubscriptionFixture extends
BaseSubscriptionFixture<PendingSubscription> {
public static final PendingSubscriptionFixture INSTANCE = new PendingSubscriptionFixture();
/**
* Disabled constructor.
*/
private PendingSubscriptionFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public PendingSubscription get(long seedValue) {
PendingSubscription sub = super.get(seedValue);
sub.setChangeReqId("change" + seedValue);
return sub;
}
/**
* {@inheritDoc}
*/
@Override
protected PendingSubscription getSubscription() {
return new PendingSubscription();
}
}

View file

@ -0,0 +1,87 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Test {@link PendingSubscription}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 27, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class PendingSubscriptionTest {
@Test
public void testCopyConstructorSetsOriginalSubNameAsName() {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
PendingSubscription pendingSubscription = new PendingSubscription(
subscription, "djohnson");
assertEquals(
"The original subscription name should have been used for the pending subscription!",
subscription.getName(), pendingSubscription.getName());
}
@Test
public void testCopyConstructorSetsSubscriptionValuesOnPendingSubscription() {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
PendingSubscription copied = new PendingSubscription(
subscription, "djohnson");
assertEquals(subscription.getActivePeriodEnd(),
copied.getActivePeriodEnd());
assertEquals(subscription.getActivePeriodStart(),
copied.getActivePeriodStart());
assertEquals(subscription.getCoverage(), copied.getCoverage());
assertEquals(subscription.getDataSetName(), copied.getDataSetName());
assertEquals(subscription.getDataSetSize(), copied.getDataSetSize());
assertEquals(subscription.getDataSetType(), copied.getDataSetType());
assertEquals(subscription.getDescription(), copied.getDescription());
assertEquals(subscription.getGroupName(), copied.getGroupName());
assertEquals(subscription.getId(), copied.getId());
assertEquals(subscription.getOfficeID(), copied.getOfficeID());
assertEquals(subscription.getPriority(), copied.getPriority());
assertEquals(subscription.getProvider(), copied.getProvider());
assertEquals(subscription.getStatus(), copied.getStatus());
assertEquals(subscription.getSubscriptionEnd(),
copied.getSubscriptionEnd());
assertEquals(subscription.getSubscriptionStart(),
copied.getSubscriptionStart());
assertEquals(subscription.getSubscriptionId(),
copied.getSubscriptionId());
assertEquals(subscription.getTime(), copied.getTime());
assertEquals(subscription.getUrl(), copied.getUrl());
}
}

View file

@ -0,0 +1,79 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import com.raytheon.uf.common.datadelivery.registry.Provider.ProviderType;
import com.raytheon.uf.common.datadelivery.registry.Provider.ServiceType;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} for {@link Provider}s.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 5, 2012 1102 djohnson Initial creation
* Nov 19, 2012 1166 djohnson Clean up JAXB representation of registry objects.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class ProviderFixture extends AbstractFixture<Provider> {
public static final ProviderFixture INSTANCE = new ProviderFixture();
/**
* Disabled constructor.
*/
private ProviderFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public Provider get(long seedValue) {
Random random = new Random(seedValue);
Provider provider = new Provider();
// TODO: ConnectionFixture
// provider.setConnection(ConnectionFixture.INSTANCE.get(seedValue));
provider.setErrorResponsePattern("error");
provider.setName("providerName" + seedValue);
// TODO: ProjectionFixture
// provider.setProjection(ProjectionFixture.INSTANCE.get(seedValue));
provider.setServiceType(ServiceType.OPENDAP);
provider.setProviderType(new ArrayList<ProviderType>(Arrays
.asList(AbstractFixture.randomEnum(ProviderType.class, random))));
return provider;
}
}

View file

@ -0,0 +1,103 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.concurrent.TimeUnit;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.junit.Test;
import com.raytheon.uf.edex.datadelivery.harvester.config.HarvesterConfig;
import com.raytheon.uf.edex.datadelivery.harvester.config.HarvesterConfigFixture;
/**
* Test {@link Provider}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 11, 2012 1154 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class ProviderTest {
@Test
public void testSetPostedFileDelayAllowsSpacesSurrounding() {
Provider provider = new Provider();
provider.setPostedFileDelay(" 2 MICROSECONDS ");
assertEquals(2, provider.getPostedFileDelayValue());
assertEquals(TimeUnit.MICROSECONDS, provider.getPostedFileDelayUnits());
}
@Test
public void testSetPostedFileDelayCanParseText() {
Provider provider = new Provider();
provider.setPostedFileDelay("5 HOURS");
assertEquals(5, provider.getPostedFileDelayValue());
assertEquals(TimeUnit.HOURS, provider.getPostedFileDelayUnits());
}
@Test
public void testSetPostedFileDelayIsCalledOnJaxbUnmarshall()
throws JAXBException {
HarvesterConfig config = HarvesterConfigFixture.INSTANCE.get();
Provider provider = config.getProvider();
provider.setPostedFileDelay("3 DAYS");
Writer writer = new StringWriter();
JAXBContext ctx = JAXBContext.newInstance(HarvesterConfig.class);
ctx.createMarshaller().marshal(config, writer);
HarvesterConfig restored = (HarvesterConfig) ctx.createUnmarshaller()
.unmarshal(new StringReader(writer.toString()));
Provider restoredProvider = restored.getProvider();
assertEquals(3, restoredProvider.getPostedFileDelayValue());
assertEquals(TimeUnit.DAYS, restoredProvider.getPostedFileDelayUnits());
}
@Test(expected = IllegalArgumentException.class)
public void testSetPostedFileDelayThrowsExceptionOnInvalidUnits() {
Provider provider = new Provider();
provider.setPostedFileDelay("5 HOUR");
}
@Test(expected = IllegalArgumentException.class)
public void testSetPostedFileDelayThrowsExceptionOnValueLessThanZero() {
Provider provider = new Provider();
provider.setPostedFileDelay("-1 DAYS");
}
}

View file

@ -0,0 +1,291 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.util.Date;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.time.util.TimeUtil;
/**
* Build {@link Subscription} objects with custom values.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jan 07, 2013 1453 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SubscriptionBuilder {
private int latencyInMinutes = 0;
private boolean active = true;
private Date activePeriodStart;
private Date activePeriodEnd;
private String dataSetName = "someDataSet";
private long dataSetSize;
private DataType dataType = DataType.GRID;
private boolean deleted = false;
private String description = "someDescription";
private boolean fullDataSet = false;
private String groupName = "None";
private String name = "your_awesome_subscription";
private boolean notify = true;
private String officeId = "officeId";
private String owner = "your_user";
private int priority = 1;
private Date subscriptionStart = TimeUtil.newDate();
private Date subscriptionEnd;
private String url = "http://someurl";
/**
* Constructor.
*/
public SubscriptionBuilder() {
}
/**
* {@inheritDoc}
*/
public Subscription build() {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
subscription.setActive(active);
subscription.setActivePeriodStart(activePeriodStart);
subscription.setActivePeriodEnd(activePeriodEnd);
subscription.setDataSetName(dataSetName);
subscription.setDataSetSize(dataSetSize);
subscription.setDataSetType(dataType);
subscription.setDeleted(deleted);
subscription.setDescription(description);
subscription.setFullDataSet(fullDataSet);
subscription.setGroupName(groupName);
subscription.setLatencyInMinutes(latencyInMinutes);
subscription.setName(name);
subscription.setNotify(notify);
subscription.setOfficeID(officeId);
subscription.setOwner(owner);
subscription.setPriority(priority);
subscription.setSubscriptionStart(subscriptionStart);
subscription.setSubscriptionEnd(subscriptionEnd);
subscription.setUrl(url);
subscription.setId(RegistryUtil.getRegistryObjectKey(subscription));
return subscription;
}
/**
* @param latencyInMinutes
* the latencyInMinutes to set
*/
public SubscriptionBuilder withLatencyInMinutes(int latencyInMinutes) {
this.latencyInMinutes = latencyInMinutes;
return this;
}
/**
* @param active
* the active to set
*/
public SubscriptionBuilder withActive(boolean active) {
this.active = active;
return this;
}
/**
* @param activePeriodStart
* the activePeriodStart to set
*/
public SubscriptionBuilder withActivePeriodStart(Date activePeriodStart) {
this.activePeriodStart = activePeriodStart;
return this;
}
/**
* @param activePeriodEnd
* the activePeriodEnd to set
*/
public SubscriptionBuilder withActivePeriodEnd(Date activePeriodEnd) {
this.activePeriodEnd = activePeriodEnd;
return this;
}
/**
* @param dataSetName
* the dataSetName to set
*/
public SubscriptionBuilder withDataSetName(String dataSetName) {
this.dataSetName = dataSetName;
return this;
}
/**
* @param dataSetSize
* the dataSetSize to set
*/
public SubscriptionBuilder withDataSetSize(long dataSetSize) {
this.dataSetSize = dataSetSize;
return this;
}
/**
* @param dataType
* the dataType to set
*/
public SubscriptionBuilder withDataType(DataType dataType) {
this.dataType = dataType;
return this;
}
/**
* @param deleted
* the deleted to set
*/
public SubscriptionBuilder withDeleted(boolean deleted) {
this.deleted = deleted;
return this;
}
/**
* @param description
* the description to set
*/
public SubscriptionBuilder withDescription(String description) {
this.description = description;
return this;
}
/**
* @param fullDataSet
* the fullDataSet to set
*/
public SubscriptionBuilder withFullDataSet(boolean fullDataSet) {
this.fullDataSet = fullDataSet;
return this;
}
/**
* @param groupName
* the groupName to set
*/
public SubscriptionBuilder withGroupName(String groupName) {
this.groupName = groupName;
return this;
}
/**
* @param name
* the name to set
*/
public SubscriptionBuilder withName(String name) {
this.name = name;
return this;
}
/**
* @param notify
* the notify to set
*/
public SubscriptionBuilder withNotify(boolean notify) {
this.notify = notify;
return this;
}
/**
* @param officeId
* the officeId to set
*/
public SubscriptionBuilder withOfficeId(String officeId) {
this.officeId = officeId;
return this;
}
/**
* @param owner
* the owner to set
*/
public SubscriptionBuilder withOwner(String owner) {
this.owner = owner;
return this;
}
/**
* @param priority
* the priority to set
*/
public SubscriptionBuilder withPriority(int priority) {
this.priority = priority;
return this;
}
/**
* @param subscriptionStart
* the subscriptionStart to set
*/
public SubscriptionBuilder withSubscriptionStart(Date subscriptionStart) {
this.subscriptionStart = subscriptionStart;
return this;
}
/**
* @param subscriptionEnd
* the subscriptionEnd to set
*/
public SubscriptionBuilder withSubscriptionEnd(Date subscriptionEnd) {
this.subscriptionEnd = subscriptionEnd;
return this;
}
/**
* @param url
* the url to set
*/
public SubscriptionBuilder withUrl(String url) {
this.url = url;
return this;
}
}

View file

@ -0,0 +1,59 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* {@link AbstractFixture} implementation for {@link Subscription} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 27, 2012 0743 djohnson Initial creation
* Sep 28, 2012 1187 djohnson Move reusable code to {@link BaseSubscriptionFixture}.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SubscriptionFixture extends BaseSubscriptionFixture<Subscription> {
public static final SubscriptionFixture INSTANCE = new SubscriptionFixture();
/**
* Disabled constructor.
*/
private SubscriptionFixture() {
}
/**
* {@inheritDoc}
*/
@Override
protected Subscription getSubscription() {
return new Subscription();
}
}

View file

@ -0,0 +1,179 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Calendar;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.Utils.SubscriptionStatus;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.time.util.TimeUtilTest;
/**
* Test {@link Subscription}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 27, 2012 0743 djohnson Initial creation
* Jan 02, 2012 1345 djohnson Fix broken assertion that id matches copied object.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SubscriptionTest {
@Before
public void setUp() {
Calendar cal = TimeUtil.newGmtCalendar();
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 20);
cal.set(Calendar.YEAR, 2012);
TimeUtilTest.freezeTime(cal.getTimeInMillis());
}
@After
public void tearDown() {
TimeUtilTest.resumeTime();
}
@Test
public void testCopyConstructorSetsSpecifiedName() throws Exception {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
Subscription copied = new Subscription(subscription, "newName");
assertEquals("Expected the new name to be set on the subscription!",
"newName", copied.getName());
}
@Test
public void testCopyConstructorSetsValuesFromSourceSubscription()
throws Exception {
Subscription subscription = SubscriptionFixture.INSTANCE.get();
Subscription copied = new Subscription(subscription, "newName");
assertEquals(subscription.getActivePeriodEnd(),
copied.getActivePeriodEnd());
assertEquals(subscription.getActivePeriodStart(),
copied.getActivePeriodStart());
assertEquals(subscription.getCoverage(), copied.getCoverage());
assertEquals(subscription.getDataSetName(), copied.getDataSetName());
assertEquals(subscription.getDataSetSize(), copied.getDataSetSize());
assertEquals(subscription.getDataSetType(), copied.getDataSetType());
assertEquals(subscription.getDescription(), copied.getDescription());
assertEquals(subscription.getGroupName(), copied.getGroupName());
assertThat(copied.getId(), is(not(equalTo(subscription.getId()))));
assertEquals(subscription.getOfficeID(), copied.getOfficeID());
assertEquals(subscription.getPriority(), copied.getPriority());
assertEquals(subscription.getProvider(), copied.getProvider());
assertEquals(subscription.getStatus(), copied.getStatus());
assertEquals(subscription.getSubscriptionEnd(),
copied.getSubscriptionEnd());
assertEquals(subscription.getSubscriptionStart(),
copied.getSubscriptionStart());
assertEquals(subscription.getSubscriptionId(),
copied.getSubscriptionId());
assertEquals(subscription.getTime(), copied.getTime());
assertEquals(subscription.getUrl(), copied.getUrl());
}
@Test
public void testGetStatusReturnsActiveForSubscriptionWithinActiveWindowOfCurrentYear() {
final Date today = TimeUtil.newGmtCalendar().getTime();
final Date fiveDaysFromNow = new Date(today.getTime()
+ (TimeUtil.MILLIS_PER_DAY * 5));
Subscription subscription = new SubscriptionBuilder()
.withActivePeriodStart(today)
.withActivePeriodEnd(fiveDaysFromNow).build();
assertThat(subscription.getStatus(),
is(equalTo(SubscriptionStatus.ACTIVE.toString())));
}
@Test
public void testGetStatusReturnsInactiveForSubscriptionOutsideActiveWindowOfCurrentYear() {
final Date fiveDaysAgo = new Date(TimeUtil.currentTimeMillis()
- (TimeUtil.MILLIS_PER_DAY * 5));
final Date yesterday = new Date(TimeUtil.currentTimeMillis()
- TimeUtil.MILLIS_PER_DAY);
Subscription subscription = new SubscriptionBuilder()
.withActivePeriodStart(fiveDaysAgo)
.withActivePeriodEnd(yesterday).build();
assertThat(subscription.getStatus(),
is(equalTo(SubscriptionStatus.INACTIVE.toString())));
}
@Test
public void testGetStatusReturnsActiveForSubscriptionWithinActiveWindowOfStoredYear() {
Calendar cal = TimeUtil.newGmtCalendar();
cal.set(Calendar.YEAR, 1970);
final Date today1970 = cal.getTime();
final Date fiveDaysFromNow1970 = new Date(today1970.getTime()
+ (TimeUtil.MILLIS_PER_DAY * 5));
Subscription subscription = new SubscriptionBuilder()
.withActivePeriodStart(today1970)
.withActivePeriodEnd(fiveDaysFromNow1970).build();
assertThat(subscription.getStatus(),
is(equalTo(SubscriptionStatus.ACTIVE.toString())));
}
@Test
public void testGetStatusReturnsInactiveForSubscriptionOutsideActiveWindowOfStoredYear() {
Calendar cal = TimeUtil.newGmtCalendar();
cal.set(Calendar.YEAR, 1970);
cal.add(Calendar.DAY_OF_YEAR, -5);
final Date fiveDaysAgo1970 = cal.getTime();
cal.add(Calendar.DAY_OF_YEAR, 4);
final Date yesterday1970 = cal.getTime();
Subscription subscription = new SubscriptionBuilder()
.withActivePeriodStart(fiveDaysAgo1970)
.withActivePeriodEnd(yesterday1970).build();
assertThat(subscription.getStatus(),
is(equalTo(SubscriptionStatus.INACTIVE.toString())));
}
}

View file

@ -0,0 +1,86 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Calendar;
import com.raytheon.uf.common.time.util.ImmutableDate;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.util.AbstractFixture;
/**
* Fixture for {@link Time} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 28, 2012 1187 djohnson Initial creation
* Oct 16, 2012 0726 djohnson Use {@link TimeUtil}.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TimeFixture extends AbstractFixture<Time> {
public static final TimeFixture INSTANCE = new TimeFixture();
/**
* Disabled.
*/
private TimeFixture() {
}
/**
* {@inheritDoc}
*/
@Override
public Time get(long seedValue) {
Time time = new Time();
time.setFormat("HHddMMMyyyy");
time.setCycleTimes(Arrays.<Integer> asList(getCycleForSeed(seedValue)));
time.setStep((double) (seedValue + 1));
time.setStepUnit("hour");
time.setSelectedTimeIndices(time.getCycleTimes());
try {
time.setStartDate(new ImmutableDate(TimeUtil.currentTimeMillis()));
time.setEndDate(new ImmutableDate(TimeUtil.currentTimeMillis()
+ seedValue));
} catch (ParseException e) {
throw new RuntimeException(e);
}
return time;
}
public static int getCycleForSeed(long seedValue) {
Calendar cal = TimeUtil.newCalendar();
cal.setTimeInMillis(TimeUtil.currentTimeMillis());
return cal.get(Calendar.HOUR_OF_DAY);
}
}

View file

@ -0,0 +1,84 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.ebxml;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;
import java.util.List;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.RegistryObjectType;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.SlotType;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.DataSetMetaData;
import com.raytheon.uf.common.registry.ebxml.slots.DateSlotConverter;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.serialization.SerializationUtil;
import com.raytheon.uf.common.time.util.ImmutableDate;
/**
* Test {@link DataSetMetaDataDatesQuery}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 15, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class DataSetMetaDataDatesQueryTest {
@Test
public void testReturnsDateSlotValueAsImmutableDate()
throws SerializationException {
ImmutableDate date = new ImmutableDate();
List<SlotType> slots = new DateSlotConverter().getSlots(
DataSetMetaData.DATE_SLOT, date);
RegistryObjectType registryObject = new RegistryObjectType();
registryObject.setSlot(new HashSet<SlotType>(slots));
DataSetMetaDataDatesQuery query = new DataSetMetaDataDatesQuery();
ImmutableDate result = query.decodeObject(registryObject);
assertEquals(
"The result from the query should have matched the initial date!",
date, result);
}
@Test
public void testCanBeDynamicSerialized() throws SerializationException {
DataSetMetaDataDatesQuery query = new DataSetMetaDataDatesQuery();
query.setProviderName("someProvider");
query.setDataSetName("someName");
byte[] serialized = SerializationUtil.transformToThrift(query);
SerializationUtil.transformFromThrift(serialized);
}
}

View file

@ -0,0 +1,179 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.ebxml;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.DataLevelType;
import com.raytheon.uf.common.datadelivery.registry.DataLevelType.LevelType;
import com.raytheon.uf.common.datadelivery.registry.DataSet;
import com.raytheon.uf.common.datadelivery.registry.GriddedCoverage;
import com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSet;
import com.raytheon.uf.common.datadelivery.registry.Parameter;
import com.raytheon.uf.common.geospatial.MapUtil;
import com.raytheon.uf.common.gridcoverage.Corner;
import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage;
import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException;
import com.raytheon.uf.common.util.CollectionUtil;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
/**
* Test {@link DataSetWithFiltersQuery}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 31, 2012 955 djohnson Initial creation
* Aug 16, 2012 1022 djohnson Use concrete implementation of DataSet for test.
* Nov 19, 2012 1166 djohnson Clean up JAXB representation of registry objects.
* Dec 10, 2012 1259 bsteffen Switch Data Delivery from LatLon to referenced envelopes.
* Jan 02, 2012 1345 djohnson Fix broken code from referenced envelope switch.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class DataSetWithFiltersQueryTest {
@Test
public void testSatisfiesFilterCriteriaReturnsTrueIfNoLevelsOrAreaSpecified() {
assertTrue("Should return true when no filters specified!",
DataSetWithFiltersQuery.satisfiesFilterCriteria(null, null,
null));
}
@Test
public void testSatisfiesFilterCriteriaReturnsTrueWhenOnlySatisfiableLevelsSpecified() {
DataLevelType dataLevelType = new DataLevelType(LevelType.SFC);
Parameter parameter = new Parameter();
parameter.setLevelType(java.util.Arrays.asList(dataLevelType));
Map<String, Parameter> paramMap = new HashMap<String, Parameter>();
paramMap.put("whatShouldThisKeyBe?", parameter);
DataSet dataSet = new OpenDapGriddedDataSet();
dataSet.setParameters(paramMap);
assertTrue("Should return true when satisfiable levels specified!",
DataSetWithFiltersQuery.satisfiesFilterCriteria(dataSet,
CollectionUtil.asSet(LevelType.SFC), null));
}
@Test
public void testSatisfiesFilterCriteriaReturnsFalseWhenLevelsSpecifiedThatAreUnsatisfiable() {
DataLevelType dataLevelType = new DataLevelType(LevelType.SFC);
Parameter parameter = new Parameter();
parameter.setLevelType(java.util.Arrays.asList(dataLevelType));
Map<String, Parameter> paramMap = new HashMap<String, Parameter>();
paramMap.put("whatShouldThisKeyBe?", parameter);
DataSet dataSet = new OpenDapGriddedDataSet();
dataSet.setParameters(paramMap);
assertFalse("Should return false when unsatisfiable levels specified!",
DataSetWithFiltersQuery.satisfiesFilterCriteria(dataSet,
CollectionUtil.asSet(LevelType.CBL), null));
}
@Test
public void testSatisfiesFilterCriteriaReturnsTrueWhenOnlySatisfiableAreaSpecified()
throws GridCoverageException {
LatLonGridCoverage gridCoverage = new LatLonGridCoverage();
gridCoverage.setCrsWKT("BoundingBox");
gridCoverage.setLa1(89);
gridCoverage.setLo1(-179);
gridCoverage.setDx(1.0);
gridCoverage.setDy(1.0);
gridCoverage.setNx(360);
gridCoverage.setNy(180);
gridCoverage.setSpacingUnit("degree");
gridCoverage.setFirstGridPointCorner(Corner.UpperLeft);
gridCoverage.initialize();
GriddedCoverage coverage = new GriddedCoverage();
coverage.setGridCoverage(gridCoverage);
DataSet dataSet = new OpenDapGriddedDataSet();
dataSet.setCoverage(coverage);
// Choose a smaller bounding box inside the dataset's
ReferencedEnvelope selectedAreaCoordinates = new ReferencedEnvelope(
MapUtil.LATLON_PROJECTION);
final Coordinate upperLeft = coverage.getUpperLeft();
final Coordinate lowerRight = coverage.getLowerRight();
selectedAreaCoordinates.expandToInclude(upperLeft.x + 1,
upperLeft.y - 1);
selectedAreaCoordinates.expandToInclude(lowerRight.x - 1,
lowerRight.y + 1);
assertTrue("Should return true when satisfiable area is specified!",
DataSetWithFiltersQuery.satisfiesFilterCriteria(dataSet, null,
selectedAreaCoordinates));
}
@Test
public void testSatisfiesFilterCriteriaReturnsFalseWhenAreaIsSpecifiedThatIsUnsatisfiable()
throws GridCoverageException {
LatLonGridCoverage gridCoverage = new LatLonGridCoverage();
gridCoverage.setCrsWKT("Polygon");
gridCoverage.setLa1(10);
gridCoverage.setLo1(-10);
gridCoverage.setDx(1.0);
gridCoverage.setDy(1.0);
gridCoverage.setNx(21);
gridCoverage.setNy(21);
gridCoverage.setSpacingUnit("degree");
gridCoverage.setFirstGridPointCorner(Corner.UpperLeft);
gridCoverage.initialize();
GriddedCoverage coverage = new GriddedCoverage();
coverage.setGridCoverage(gridCoverage);
DataSet dataSet = new OpenDapGriddedDataSet();
dataSet.setCoverage(coverage);
// Choose a bounding box lying outside of the dataset's
ReferencedEnvelope selectedAreaCoordinates = new ReferencedEnvelope(
new Envelope(new Coordinate(-15, -14), new Coordinate(-14, -13)),
MapUtil.LATLON_PROJECTION);
assertFalse(
"Should return false when unsatisfiable area is specified!",
DataSetWithFiltersQuery.satisfiesFilterCriteria(dataSet, null,
selectedAreaCoordinates));
}
}

View file

@ -0,0 +1,87 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.raytheon.uf.common.datadelivery.registry.DataSetMetaData;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
import com.raytheon.uf.common.time.util.ImmutableDate;
/**
* {@link IBaseDataSetMetaDataHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BaseMemoryDataSetMetaDataHandler<T extends DataSetMetaData>
extends
BaseMemoryRegistryObjectHandler<T> implements
IBaseDataSetMetaDataHandler<T> {
/**
* {@inheritDoc}
*/
@Override
public Set<ImmutableDate> getDatesForDataSet(String dataSetName,
String providerName) throws RegistryHandlerException {
Set<ImmutableDate> dates = new HashSet<ImmutableDate>();
for (T obj : getAll()) {
if (matches(dataSetName, obj.getDataSetName())
&& matches(providerName, obj.getProviderName())) {
dates.add(obj.getDate());
}
}
return dates;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getByDataSet(String dataSetName,
String providerName) throws RegistryHandlerException {
List<T> retVal = new ArrayList<T>();
for (T obj : getAll()) {
if (matches(dataSetName, obj.getDataSetName())
&& matches(providerName, obj.getProviderName())) {
retVal.add(obj);
}
}
return retVal;
}
}

View file

@ -0,0 +1,170 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.registry.handler.IRegistryObjectHandler;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* Base memory registry object handler.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public abstract class BaseMemoryRegistryObjectHandler<T>
implements IRegistryObjectHandler<T> {
private final Map<String, T> map = new HashMap<String, T>();
/**
* {@inheritDoc}
*/
@Override
public T getById(String id) throws RegistryHandlerException {
return map.get(id);
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getAll() throws RegistryHandlerException {
return new ArrayList<T>(map.values());
}
/**
* {@inheritDoc}
*/
@Override
public void store(T obj) throws RegistryHandlerException {
map.put(RegistryUtil.getRegistryObjectKey(obj), obj);
}
/**
* {@inheritDoc}
*/
@Override
public void update(T obj) throws RegistryHandlerException {
store(obj);
}
/**
* {@inheritDoc}
*
*/
@Override
@SuppressWarnings("unchecked")
public final void delete(T obj) throws RegistryHandlerException {
delete(Arrays.asList(obj));
}
/**
* {@inheritDoc}
*
*/
@Override
public final void delete(Collection<T> objects)
throws RegistryHandlerException {
delete(null, objects);
}
/**
* {@inheritDoc}
*
*/
@Override
@SuppressWarnings("unchecked")
public final void delete(String username, T obj)
throws RegistryHandlerException {
delete(username, Arrays.asList(obj));
}
/**
* {@inheritDoc}
*
*/
@Override
public final void delete(String username, Collection<T> objects)
throws RegistryHandlerException {
List<String> ids = new ArrayList<String>(objects.size());
for (T obj : objects) {
ids.add(RegistryUtil.getRegistryObjectKey(obj));
}
deleteByIds(username, ids);
}
/**
* {@inheritDoc}
*/
@Override
public final void deleteById(String username, String registryId)
throws RegistryHandlerException {
deleteByIds(username, Arrays.asList(registryId));
}
/**
* {@inheritDoc}
*/
@Override
public void deleteByIds(String username, List<String> registryIds)
throws RegistryHandlerException {
for (String id : registryIds) {
map.remove(id);
}
}
/**
* Returns true if the attribute is null, or if the equals comparison
* between attribute and value resolves as true.
*
* @param <TYPE>
* the type of the attribute
* @param attribute
* the attribute
* @param value
* the value from the entity
* @return true if the attribute is null, or if the equals comparison
* between attribute and value resolves as true.
*/
protected <TYPE> boolean matches(TYPE attribute,
TYPE value) {
return attribute == null || attribute.equals(value);
}
}

View file

@ -0,0 +1,141 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IBaseSubscriptionHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BaseMemorySubscriptionHandler<T extends Subscription> extends
BaseMemoryRegistryObjectHandler<T> implements
IBaseSubscriptionHandler<T> {
/**
* {@inheritDoc}
*
* @throws RegistryHandlerException
*/
@Override
public T getByName(String name) throws RegistryHandlerException {
for (T obj : getAll()) {
if (matches(name, obj.getName())) {
return obj;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getByOwner(String owner) throws RegistryHandlerException {
List<T> retVal = new ArrayList<T>();
for (T obj : getAll()) {
if (matches(owner, obj.getOwner())) {
retVal.add(obj);
}
}
return retVal;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getByGroupName(String group) throws RegistryHandlerException {
List<T> retVal = new ArrayList<T>();
for (T obj : getAll()) {
if (matches(group, obj.getGroupName())) {
retVal.add(obj);
}
}
return retVal;
}
/**
* {@inheritDoc}
*/
@Override
public Set<String> getSubscribedToDataSetNames()
throws RegistryHandlerException {
Set<String> retVal = new HashSet<String>();
for (T obj : getAll()) {
retVal.add(obj.getDataSetName());
}
return retVal;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getByFilters(String group, String officeId)
throws RegistryHandlerException {
List<T> retVal = new ArrayList<T>();
for (T obj : getAll()) {
if (matches(group, obj.getGroupName())
&& matches(officeId, obj.getOfficeID())) {
retVal.add(obj);
}
}
return retVal;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> getActive() throws RegistryHandlerException {
List<T> retVal = new ArrayList<T>();
for (T obj : getAll()) {
if (obj.isActive()) {
retVal.add(obj);
}
}
return retVal;
}
}

View file

@ -0,0 +1,92 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.geotools.geometry.jts.ReferencedEnvelope;
import com.raytheon.uf.common.datadelivery.registry.DataLevelType.LevelType;
import com.raytheon.uf.common.datadelivery.registry.DataSet;
import com.raytheon.uf.common.datadelivery.registry.ebxml.DataSetWithFiltersQuery;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IDataSetHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
* Nov 19, 2012 1166 djohnson Clean up JAXB representation of registry objects.
* Dec 10, 2012 1259 bsteffen Switch Data Delivery from LatLon to referenced envelopes.
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryDataSetHandler extends
BaseMemoryRegistryObjectHandler<DataSet> implements IDataSetHandler {
/**
* {@inheritDoc}
*/
@Override
public DataSet getByNameAndProvider(String name, String providerName)
throws RegistryHandlerException {
for (DataSet obj : getAll()) {
if (matches(name, obj.getDataSetName())
&& matches(providerName, obj.getProviderName())) {
return obj;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public List<DataSet> getByFilters(List<String> providers,
List<String> dataSetNames, Set<LevelType> levels,
List<String> parameterNames, ReferencedEnvelope envelope)
throws RegistryHandlerException {
List<DataSet> retVal = new ArrayList<DataSet>();
for (DataSet obj : getAll()) {
if ((providers == null || providers.contains(obj.getProviderName()))
&& (dataSetNames == null || dataSetNames.contains(obj
.getDataSetName()))) {
if (DataSetWithFiltersQuery.satisfiesFilterCriteria(obj,
levels, envelope)) {
retVal.add(obj);
}
}
}
return retVal;
}
}

View file

@ -0,0 +1,44 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import com.raytheon.uf.common.datadelivery.registry.DataSetMetaData;
/**
* {@link IDataSetMetaDataHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryDataSetMetaDataHandler extends
BaseMemoryDataSetMetaDataHandler<DataSetMetaData> implements
IDataSetMetaDataHandler {
}

View file

@ -0,0 +1,67 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.raytheon.uf.common.datadelivery.registry.DataSetName;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IDataSetNameHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryDataSetNameHandler extends
BaseMemoryRegistryObjectHandler<DataSetName> implements
IDataSetNameHandler {
/**
* {@inheritDoc}
*/
@Override
public Set<String> getByDataTypes(List<String> dataTypes)
throws RegistryHandlerException {
Set<String> retVal = new HashSet<String>();
for (DataSetName obj : getAll()) {
if (dataTypes == null
|| dataTypes.contains(obj.getDataSetType().toString())) {
retVal.add(obj.getDataSetName());
}
}
return retVal;
}
}

View file

@ -0,0 +1,70 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.Date;
import com.raytheon.uf.common.datadelivery.registry.DataSetMetaData;
import com.raytheon.uf.common.datadelivery.registry.GriddedDataSetMetaData;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IGriddedDataSetMetaDataHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryGriddedDataSetMetaDataHandler extends
BaseMemoryDataSetMetaDataHandler<DataSetMetaData>
implements IGriddedDataSetMetaDataHandler {
/**
* {@inheritDoc}
*/
@Override
public GriddedDataSetMetaData getByDataSetDateAndCycle(String dataSetName,
String providerName, int cycle, Date date)
throws RegistryHandlerException {
for (DataSetMetaData obj : getByDataSet(dataSetName,
providerName)) {
if (obj instanceof GriddedDataSetMetaData) {
GriddedDataSetMetaData gdsdm = (GriddedDataSetMetaData) obj;
if (gdsdm.getCycle() == cycle && matches(date, gdsdm.getDate())) {
return gdsdm;
}
}
}
return null;
}
}

View file

@ -0,0 +1,91 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.raytheon.uf.common.datadelivery.registry.GroupDefinition;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IGroupDefinitionHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
* Jan 02, 2013 1441 djohnson Add deleteByName() and getGroupNames().
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryGroupDefinitionHandler extends
BaseMemoryRegistryObjectHandler<GroupDefinition> implements
IGroupDefinitionHandler {
/**
* {@inheritDoc}
*/
@Override
public GroupDefinition getByName(String groupName)
throws RegistryHandlerException {
for (GroupDefinition obj : getAll()) {
if (matches(groupName, obj.getGroupName())) {
return obj;
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void deleteByName(String groupName) throws RegistryHandlerException {
GroupDefinition entity = getByName(groupName);
if (entity != null) {
delete(entity);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getGroupNames() throws RegistryHandlerException {
return new ArrayList<String>(Lists.transform(getAll(),
new Function<GroupDefinition, String>() {
@Override
public String apply(GroupDefinition arg0) {
return arg0.getGroupName();
}
}));
}
}

View file

@ -0,0 +1,83 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.raytheon.uf.common.datadelivery.registry.DataLevelType;
import com.raytheon.uf.common.datadelivery.registry.Parameter;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IParameterHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryParameterHandler extends
BaseMemoryRegistryObjectHandler<Parameter> implements IParameterHandler {
/**
* {@inheritDoc}
*/
@Override
public Set<String> getNamesByDataTypes(List<String> dataTypes)
throws RegistryHandlerException {
Set<String> names = new HashSet<String>();
for (Parameter parameter : getAll()) {
if (dataTypes == null
|| dataTypes.contains(parameter.getDataType().toString())) {
names.add(parameter.getName());
}
}
return names;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getDataLevelTypeDescriptions(List<String> dataTypes)
throws RegistryHandlerException {
Set<String> descriptions = new HashSet<String>();
for (Parameter parameter : getAll()) {
List<DataLevelType> dataLevelTypes = parameter.getLevelType();
for (DataLevelType dataLevelType : dataLevelTypes) {
String description = dataLevelType.getDescription();
descriptions.add(description);
}
}
return new ArrayList<String>(descriptions);
}
}

View file

@ -0,0 +1,44 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import com.raytheon.uf.common.datadelivery.registry.ParameterLevel;
/**
* {@link IParameterLevelHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryParameterLevelHandler extends
BaseMemoryRegistryObjectHandler<ParameterLevel> implements
IParameterLevelHandler {
}

View file

@ -0,0 +1,120 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.raytheon.uf.common.datadelivery.registry.InitialPendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IPendingSubscriptionHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryPendingSubscriptionHandler extends
BaseMemorySubscriptionHandler<InitialPendingSubscription> implements
IPendingSubscriptionHandler {
/**
* {@inheritDoc}
*/
@Override
public void store(InitialPendingSubscription obj)
throws RegistryHandlerException {
// TODO: Store an in-memory association to the subscription
super.store(obj);
}
/**
* {@inheritDoc}
*/
@Override
public void deleteByIds(String username, List<String> registryIds)
throws RegistryHandlerException {
// TODO: Delete in-memory association to the subscription
super.deleteByIds(username, registryIds);
}
/**
* {@inheritDoc}
*/
@Override
public InitialPendingSubscription getBySubscription(
Subscription subscription) throws RegistryHandlerException {
return getBySubscriptionId(RegistryUtil
.getRegistryObjectKey(subscription));
}
/**
* {@inheritDoc}
*/
@Override
public InitialPendingSubscription getBySubscriptionId(String id)
throws RegistryHandlerException {
List<InitialPendingSubscription> results = getBySubscriptionIds(Arrays
.asList(id));
return (!results.isEmpty()) ? results.iterator().next() : null;
}
/**
* {@inheritDoc}
*/
@Override
public List<InitialPendingSubscription> getBySubscriptions(
Collection<Subscription> subscriptions)
throws RegistryHandlerException {
List<String> ids = new ArrayList<String>(subscriptions.size());
for (Subscription subscription : subscriptions) {
ids.add(RegistryUtil.getRegistryObjectKey(subscription));
}
return getBySubscriptionIds(ids);
}
/**
* {@inheritDoc}
*/
@Override
public List<InitialPendingSubscription> getBySubscriptionIds(
List<String> ids) throws RegistryHandlerException {
// TODO: Lookup via an in-memory association
return Collections.emptyList();
}
}

View file

@ -0,0 +1,58 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import com.raytheon.uf.common.datadelivery.registry.Provider;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
/**
* {@link IProviderHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemoryProviderHandler extends
BaseMemoryRegistryObjectHandler<Provider> implements IProviderHandler {
/**
* {@inheritDoc}
*/
@Override
public Provider getByName(String providerName)
throws RegistryHandlerException {
for (Provider provider : getAll()) {
if (matches(providerName, provider.getName())) {
return provider;
}
}
return null;
}
}

View file

@ -0,0 +1,115 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.datadelivery.registry.handlers;
import java.util.ArrayList;
import java.util.List;
import com.raytheon.uf.common.datadelivery.registry.InitialPendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.PendingSubscription;
import com.raytheon.uf.common.datadelivery.registry.Subscription;
import com.raytheon.uf.common.registry.ebxml.RegistryUtil;
import com.raytheon.uf.common.registry.handler.RegistryHandlerException;
import com.raytheon.uf.common.registry.handler.RegistryObjectHandlers;
import com.raytheon.uf.common.util.CollectionUtil;
/**
* {@link ISubscriptionHandler} in-memory implementation.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 17, 2012 0726 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MemorySubscriptionHandler extends
BaseMemorySubscriptionHandler<Subscription> implements
ISubscriptionHandler {
/**
* {@inheritDoc}
*/
@Override
public Subscription getByPendingSubscription(PendingSubscription pending)
throws RegistryHandlerException {
return getByPendingSubscriptionId(RegistryUtil
.getRegistryObjectKey(pending));
}
/**
* {@inheritDoc}
*/
@Override
public Subscription getByPendingSubscriptionId(final String id)
throws RegistryHandlerException {
// TODO: lookup via in-memory association
return null;
}
/**
* Overridden because subscriptions must also have their
* {@link PendingSubscription} object deleted.
*
* @param username
* the username of the requester
* @param ids
* the registry ids of the subscription objects
*/
@Override
public void deleteByIds(String username, List<String> ids)
throws RegistryHandlerException {
IPendingSubscriptionHandler handler = RegistryObjectHandlers
.get(IPendingSubscriptionHandler.class);
List<InitialPendingSubscription> pending = handler
.getBySubscriptionIds(ids);
if (!CollectionUtil.isNullOrEmpty(pending)) {
handler.delete(username, pending);
}
super.deleteByIds(username, ids);
}
/**
* {@inheritDoc}
*/
@Override
public List<Subscription> getActiveByDataSetAndProvider(String dataSetName,
String providerName) throws RegistryHandlerException {
List<Subscription> retVal = new ArrayList<Subscription>();
for (Subscription obj : getActive()) {
if (matches(dataSetName, obj.getDataSetName())
&& matches(providerName, obj.getProvider())) {
retVal.add(obj);
}
}
return retVal;
}
}

View file

@ -0,0 +1,63 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.localization;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import com.raytheon.uf.common.localization.TestPathManager.TestLocalizationAdapter;
/**
* {@link ILocalizationAdapter} implementation for running tests on the
* command-line.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 23, 2012 1286 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class CommandLineTestLocalizationAdapter extends TestLocalizationAdapter {
/**
* @param site
* @param savedLocalizationFileDir
*/
public CommandLineTestLocalizationAdapter(String site,
File savedLocalizationFileDir) {
super(site, savedLocalizationFileDir);
}
/**
* {@inheritDoc}
*/
@Override
List<File> getDirectoriesWithPlugins() {
return Arrays.asList(new File(".."));
}
}

View file

@ -0,0 +1,129 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.localization;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import com.raytheon.uf.common.localization.TestPathManager.TestLocalizationAdapter;
/**
* {@link ILocalizationAdapter} implementation for tests running in Eclipse. If
* your common baseline repository name is not "AWIPS2_baseline" then set a
* system property named "common.baseline.repo.name" to override it. i.e. in
* your Eclipse launcher you would add a VM argument
* "-Dcommon.baseline.repo.name=awips2_common_baseline" or something similar.
*
* TODO: Changes will need to be made somehow when this moves to the common
* baseline... How will we add work assignment specific tests while reusing old
* tests, perhaps linking source directories from a work-assignment specific
* project?
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 18, 2012 740 djohnson Initial creation
* Oct 23, 2012 1286 djohnson Create Eclipse and command-line specific versions.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class EclipseTestLocalizationAdapter extends TestLocalizationAdapter {
private static final String COMMON_BASELINE_REPO_NAME = System.getProperty(
"common.baseline.repo.name", "AWIPS2_baseline");
private static final String EDEX_OSGI = "edexOsgi";
private static final Pattern REPO_EDEX_OSGI_REGEX = Pattern
.compile("/[^/]+/" + EDEX_OSGI);
private static final File EDEX_OSGI_DIR = findEdexOsgiDir();
/**
* @param site
* @param savedLocalizationFileDir
*/
public EclipseTestLocalizationAdapter(String site,
File savedLocalizationFileDir) {
super(site, savedLocalizationFileDir);
}
/**
* {@inheritDoc}
*/
@Override
List<File> getDirectoriesWithPlugins() {
return Arrays.asList(EDEX_OSGI_DIR, new File("..", "edexOsgi"));
}
/**
* Finds the edexOsgi directory.
*
* @return the {@link File} reference to the edexOsgi directory
*/
private static File findEdexOsgiDir() {
File currentDir = new File(System.getProperty("user.dir"));
File edexOsgiDir = new File(currentDir, EDEX_OSGI);
while (!edexOsgiDir.isDirectory() && currentDir != null) {
currentDir = currentDir.getParentFile();
edexOsgiDir = new File(currentDir, EDEX_OSGI);
}
if (!edexOsgiDir.isDirectory()) {
throw new IllegalStateException(
"Unable to find the edexOsgi directory!");
}
edexOsgiDir = convertToCommonBaselineVersion(edexOsgiDir);
return edexOsgiDir;
}
/**
* Converts the data_delivery specific version of edexOsgi into the common
* baseline version. NOTE: This will be unnecessary once the tests project
* is moved into the common baseline.
*/
private static File convertToCommonBaselineVersion(File edexOsgiDir) {
String path = REPO_EDEX_OSGI_REGEX.matcher(
edexOsgiDir.getAbsolutePath()).replaceAll(
"/" + COMMON_BASELINE_REPO_NAME + "/" + EDEX_OSGI);
edexOsgiDir = new File(path);
if (!edexOsgiDir.isDirectory()) {
throw new IllegalStateException(
"Unable to find the edexOsgi directory! "
+ "Is your common baseline named something other than "
+ COMMON_BASELINE_REPO_NAME + "? ");
}
return edexOsgiDir;
}
}

View file

@ -0,0 +1,156 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.localization;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
import com.raytheon.uf.common.localization.TestPathManager.TestLocalizationAdapter;
import com.raytheon.uf.common.util.TestUtil;
/**
* Utility class to initialize the test {@link IPathManager} implementation.
* This allows tests to lookup baselined localization files.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 18, 2012 740 djohnson Initial creation
* Oct 23, 2012 1286 djohnson Handle executing tests in Eclipse/command-line transparently.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class PathManagerFactoryTest {
private static File savedLocalizationFileDir;
/**
* Creates a test-only PathManager that can be used during tests.
*/
public static void initLocalization() {
initLocalization("OAX");
}
/**
* Creates a test-only PathManager that can be used during tests, it is
* configured for the specified site.
*/
public static void initLocalization(final String site) {
// Clear known file cache and the directory each time
PathManager.fileCache.clear();
File file = TestUtil.setupTestClassDir(PathManagerFactoryTest.class);
savedLocalizationFileDir = new File(file, "utility");
savedLocalizationFileDir.mkdirs();
// But only install the path manager if the test version is not already
// installed
if (!(PathManagerFactory.pathManager instanceof TestPathManager)) {
TestLocalizationAdapter adapter = (isRunningInEclipse()) ? new EclipseTestLocalizationAdapter(
site, savedLocalizationFileDir)
: new CommandLineTestLocalizationAdapter(site,
savedLocalizationFileDir);
PathManagerFactory.pathManager = new TestPathManager(adapter);
}
}
/**
* Returns true if the JUnit test is running in Eclipse.
*
* @return true if running in Eclipse
*/
private static boolean isRunningInEclipse() {
return new File("..", "edexOsgi").isDirectory();
}
@Before
public void setUp() {
PathManagerFactoryTest.initLocalization();
}
@Test
public void testFindingCommonBaselineLocalizationFile() {
IPathManager pm = PathManagerFactory.getPathManager();
LocalizationContext lc = pm.getContext(LocalizationType.COMMON_STATIC,
LocalizationLevel.BASE);
LocalizationFile lf = pm.getLocalizationFile(lc,
"datadelivery/proxy.properties");
File file = lf.getFile();
assertTrue("Unable to find common baseline localization file!",
file.exists());
}
@Test
public void testFindingWorkAssignmentPluginLocalizationFile() {
IPathManager pm = PathManagerFactory.getPathManager();
LocalizationContext lc = pm.getContext(LocalizationType.COMMON_STATIC,
LocalizationLevel.BASE);
LocalizationFile lf = pm.getLocalizationFile(lc,
"datadelivery/bandwidthmap.xml");
File file = lf.getFile();
assertTrue(
"Unable to find work assignment plugin provided localization file!",
file.exists());
}
@Test
public void testFindingCommonBaselinePluginLocalizationFile() {
IPathManager pm = PathManagerFactory.getPathManager();
LocalizationContext lc = pm.getContext(LocalizationType.COMMON_STATIC,
LocalizationLevel.BASE);
LocalizationFile lf = pm.getLocalizationFile(lc,
"site3LetterTo4LetterOverride.dat");
File file = lf.getFile();
assertTrue(
"Unable to find common baseline plugin provided localization file!",
file.exists());
}
@Test
public void testFindingFileCreatesVersionInTestDirectory() {
IPathManager pm = PathManagerFactory.getPathManager();
LocalizationContext lc = pm.getContext(LocalizationType.COMMON_STATIC,
LocalizationLevel.BASE);
LocalizationFile lf = pm.getLocalizationFile(lc,
"site3LetterTo4LetterOverride.dat");
File file = lf.getFile();
assertTrue(
"Localization file does not seem to have been copied!",
file.getParentFile().getAbsolutePath()
.startsWith(savedLocalizationFileDir.getAbsolutePath()));
}
}

View file

@ -0,0 +1,219 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.localization;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.raytheon.edex.utility.EDEXLocalizationAdapter;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
import com.raytheon.uf.common.util.FileUtil;
/**
* {@link IPathManager} implementation for tests.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 18, 2012 740 djohnson Initial creation
* Oct 23, 2012 1286 djohnson Change to find more localization files.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TestPathManager extends PathManager {
/**
* Construct a {@link TestPathManager} with the appropriate extension of
* {@link TestLocalizationAdapter} to fit the environment tests are
* executing in.
*
* @param adapter
* the adapter
*/
TestPathManager(TestLocalizationAdapter adapter) {
super(adapter);
}
/**
* {@link ILocalizationAdapter} implementation for running tests.
*
*/
public static abstract class TestLocalizationAdapter extends
EDEXLocalizationAdapter {
private static final String UTILITY = "utility";
private final File savedLocalizationFileDir;
private final String site;
private List<File> utilityDirs;
/**
* @param site
* @param savedLocalizationFileDir
* @param pluginDirectories
*/
public TestLocalizationAdapter(String site,
File savedLocalizationFileDir) {
this.site = site;
this.savedLocalizationFileDir = savedLocalizationFileDir;
}
/*
* (non-Javadoc)
*
* @see com.raytheon.edex.utility.EDEXLocalizationAdapter#getSiteName()
*/
@Override
protected String getSiteName() {
return site;
}
/**
* Duplicates the {@link EDEXLocalizationAdapter} version, adding the
* ability to check multiple utility directories.
*/
@Override
public File getPath(LocalizationContext context, String fileName) {
File foundFile = null;
List<File> utilityDirs = getUtilityDirs();
if (context.getLocalizationLevel() == LocalizationLevel.UNKNOWN) {
throw new IllegalArgumentException(
"Unsupported localization level:"
+ context.getLocalizationLevel());
// } else if (false) {
// TODO: Check for invalid type / level combinations
// Change the above condition and add invalid type / level
// checking
// if needed
}
final int length = utilityDirs.size();
for (int i = 0; i < length; i++) {
File baseDir = new File(utilityDirs.get(i), context.toPath());
File file = new File(baseDir, fileName);
// If it's the final check or if a file exists
if (i == (length - 1) || file.exists()) {
foundFile = file;
break;
}
}
if (foundFile == null
|| !foundFile.exists()
|| foundFile.getAbsolutePath().startsWith(
savedLocalizationFileDir.getAbsolutePath())) {
return foundFile;
}
// Make a copy in the savedFile folder, this way if any
// modifications are performed we don't mess with the file in
// the baseline
File savedFileBaseDir = new File(savedLocalizationFileDir,
context.toPath());
File savedFile = new File(savedFileBaseDir, fileName);
savedFile.getParentFile().mkdirs();
try {
FileUtil.copyFile(foundFile, savedFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
return savedFile;
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.edex.utility.EDEXLocalizationAdapter#getUtilityDir()
*/
protected List<File> getUtilityDirs() {
if (utilityDirs == null) {
utilityDirs = new ArrayList<File>();
// The directory which will have "saved" utility files
utilityDirs.add(savedLocalizationFileDir);
// Test overrides
utilityDirs.add(new File(UTILITY));
List<File> pluginDirectories = getDirectoriesWithPlugins();
// Build.edex utility directory
File buildEdexDir = null;
for (File pluginDirectory : pluginDirectories) {
File potential = new File(pluginDirectory, "build.edex");
if (potential.isDirectory()) {
buildEdexDir = potential;
break;
}
}
if (buildEdexDir == null) {
throw new RuntimeException(
"Unable to find the build.edex directory!");
}
utilityDirs.add(new File(buildEdexDir, "esb/data/utility"));
// Plugin utility directories
for (File pluginDir : pluginDirectories) {
File[] plugins = pluginDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File plugin : plugins) {
File utilityDir = new File(plugin, UTILITY);
if (utilityDir.isDirectory()) {
utilityDirs.add(utilityDir);
}
}
}
}
return utilityDirs;
}
/**
* Return the list of directories that contain plugins. This will be
* used to find the build.edex directory, along with checking for any
* plugin-provided utility directories.
*
* @return
*/
abstract List<File> getDirectoriesWithPlugins();
}
}

View file

@ -0,0 +1,116 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.raytheon.uf.common.registry.BaseQuery;
import com.raytheon.uf.common.registry.RegistryResponse;
import com.raytheon.uf.common.registry.ebxml.AdhocRegistryQuery;
/**
* Test {@link BaseQuery}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 2, 2012 955 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BaseQueryTest {
private static final BaseQuery<String> BASE_QUERY = new AdhocRegistryQuery<String>() {
@Override
public Class<String> getObjectType() {
return String.class;
}
@Override
public Class<String> getResultType() {
return String.class;
}
};
@Test
public void testGetResultsReturnsEmptyListForNullResponseObjects()
{
RegistryResponse response = new RegistryResponse();
response.setRegistryObjects(null);
List<String> results = BASE_QUERY.getResults(response);
assertTrue(
"Expected an empty list if the results were null from the response!",
results.isEmpty());
}
@Test
public void testGetSingleResultReturnsNullForNullResponseObjects() {
RegistryResponse response = new RegistryResponse();
response.setRegistryObjects(null);
String result = BASE_QUERY.getSingleResult(response);
assertNull("Expected null if the results were null from the response!",
result);
}
@Test
public void testGetResultsReturnsListOfTypeSafeResultsForNonNullResponseObjects() {
final Object one = "one";
final Object two = "two";
RegistryResponse response = new RegistryResponse();
response.setRegistryObjects(Arrays.asList(one, two));
List<String> results = BASE_QUERY.getResults(response);
assertEquals("Incorrect results collection size!", 2, results.size());
assertTrue("Didn't find an expected result!", results.contains(one));
assertTrue("Didn't find an expected result!", results.contains(two));
}
@Test
public void testGetSingleResultReturnsTypeSafeResultForNonNullResponseObjects() {
final Object one = "one";
RegistryResponse response = new RegistryResponse();
response.setRegistryObjects(Arrays.asList(one));
String result = BASE_QUERY.getSingleResult(response);
assertEquals("Didn't find the expected result!", one, result);
}
}

View file

@ -0,0 +1,65 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry;
import com.raytheon.uf.common.datadelivery.registry.DataType;
import com.raytheon.uf.common.registry.annotations.RegistryObject;
import com.raytheon.uf.common.registry.annotations.SlotAttribute;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* A mock registry object.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 22, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
@RegistryObject
@DynamicSerialize
public class MockRegistryObject {
@SlotAttribute
@DynamicSerializeElement
private DataType dataType;
/**
* @return the dataType
*/
public DataType getDataType() {
return dataType;
}
/**
* @param dataType
* the dataType to set
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
}

View file

@ -0,0 +1,68 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry;
import org.junit.Ignore;
import org.mockito.Mockito;
/**
* Allows setting a specific {@link RegistryHandler} instance for test purposes.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 16, 2012 0743 djohnson Initial creation
* Oct 17, 2012 0726 djohnson Remove MockRegistryHandler.
* Nov 15, 2012 1286 djohnson Set handler instance via package-level constructor.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
@Ignore
public class RegistryManagerTest {
/**
* Sets the {@link RegistryManager#instance} to be a mock instance.
*
* @return the mock {@link RegistryHandler}.
*/
public static RegistryHandler setMockInstance() {
RegistryHandler mock = Mockito.mock(RegistryHandler.class);
RegistryManagerTest.setInstance(mock);
return mock;
}
/**
* Allows setting of the RegistyHandler instance on RegistryManager. Only
* allowed from tests. This is useful if you want to use a mocking library
* version of the handler, rather than an actual object.
*
* @param handler
* the handler to use
*/
public static void setInstance(RegistryHandler handler) {
new RegistryManager(handler);
}
}

View file

@ -0,0 +1,401 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.xml.ws.WebServiceException;
import oasis.names.tc.ebxml.regrep.wsdl.registry.services.v4.MsgRegistryException;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.RegistryObjectType;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.SlotType;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import com.raytheon.uf.common.comm.CommunicationException;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryResponse;
import com.raytheon.uf.common.registry.ebxml.encoder.RegistryEncoders;
import com.raytheon.uf.common.registry.ebxml.encoder.RegistryEncoders.Type;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.time.util.TimeUtilTest;
import com.raytheon.uf.common.util.CollectionUtil;
/**
* Test {@link FactoryRegistryHandler}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 12, 2012 740 djohnson Initial creation
* Aug 15, 2012 0743 djohnson Type-safe result formatters.
* Sep 07, 2012 1102 djohnson Setup the registry encoder.
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class FactoryRegistryHandlerTest {
private static final WebServiceException WEB_SERVICE_EXCEPTION = new WebServiceException(
"Thrown on purpose");
private static final CommunicationException COMMUNICATION_EXCEPTION = new CommunicationException(
RegistryUtil.DATABASE_ERROR_MESSAGE);
@BeforeClass
public static void classSetup() {
RegistryUtilTest.setEncoderStrategy(RegistryEncoders
.ofType(Type.DYNAMIC_SERIALIZE));
}
@After
public void cleanUp() {
TimeUtilTest.resumeTime();
}
@Test
public void testGetObjectsReturnsFailedStatusIfWebServiceExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).getObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsUnableToConnectMessageIfWebServiceExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).getObjects(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).removeObjects(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithObjectsReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testStoreObjectReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).storeObject(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).removeObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testRemoveObjectsWithObjectsReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testStoreObjectReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
WEB_SERVICE_EXCEPTION).storeObject(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).getObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsFailedToConnectToTheDatabaseIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).getObjects(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithObjectsReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testStoreObjectReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).storeObject(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testRemoveObjectsWithObjectsReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testStoreObjectReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).storeObject(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testNonResultFormatterWillReturnDecodedRegistryObjects()
throws SerializationException {
final String[] results = new String[] { "one", "two", "three" };
final List<RegistryObjectType> registryObjectTypes = java.util.Arrays
.asList(new RegistryObjectType(), new RegistryObjectType(),
new RegistryObjectType());
// Setup the encoded objects as if they were coming from the registry
for (int i = 0; i < registryObjectTypes.size(); i++) {
Set<SlotType> slotType = CollectionUtil.asSet(RegistryUtil
.encodeObject(results[i]));
registryObjectTypes.get(i).setSlot(slotType);
}
List<String> filteredResults = FactoryRegistryHandler.filterResults(
new StringQueryNonFormatter(), registryObjectTypes);
assertEquals("Incorrect number of results were returned!",
results.length, filteredResults.size());
for (String result : results) {
assertTrue("The filtered results should have contained result ["
+ result + "]", filteredResults.contains(result));
}
}
@Test
public void testResultFormatterThatReturnsSingleResultWillReturnsAllSingleResults() {
final String[] results = new String[]{"one", "two", "three"};
final List<RegistryObjectType> registryObjectTypes = java.util.Arrays.asList(new RegistryObjectType(), new RegistryObjectType(), new RegistryObjectType());
StringResultsQuery query = new StringResultsQuery(results);
List<String> filteredResults = FactoryRegistryHandler.filterResults(
query, registryObjectTypes);
assertEquals("Incorrect number of results were returned!", results.length, filteredResults.size());
for (String result : results) {
assertTrue("The filtered results should have contained result ["
+ result + "]", filteredResults.contains(result));
}
}
@Test
public void testResultFormatterThatReturnsMultipleResultsWillReturnAllMultipleResults() {
final String[][] results = new String[][] {
new String[] { "one", "two" },
new String[] { "three", "four" },
new String[] { "five", "six" } };
final List<RegistryObjectType> registryObjectTypes = java.util.Arrays
.asList(new RegistryObjectType(), new RegistryObjectType(),
new RegistryObjectType());
StringArrayResultsQuery query = new StringArrayResultsQuery(results);
List<String> filteredResults = FactoryRegistryHandler.filterResults(
query, registryObjectTypes);
assertEquals("Incorrect number of results were returned!", 6,
filteredResults.size());
for (String[] resultArray : results) {
for (String result : resultArray) {
assertTrue(
"The filtered results should have contained result ["
+ result + "]",
filteredResults.contains(result));
}
}
}
@Test
public void testNormalQueryWillReturnAllDecodedObjects() {
final String[][] results = new String[][] {
new String[] { "one", "two" },
new String[] { "three", "four" },
new String[] { "five", "six" } };
final List<RegistryObjectType> registryObjectTypes = java.util.Arrays
.asList(new RegistryObjectType(), new RegistryObjectType(),
new RegistryObjectType());
StringArrayResultsQuery query = new StringArrayResultsQuery(results);
List<String> filteredResults = FactoryRegistryHandler.filterResults(
query, registryObjectTypes);
assertEquals("Incorrect number of results were returned!", 6,
filteredResults.size());
for (String[] resultArray : results) {
for (String result : resultArray) {
assertTrue(
"The filtered results should have contained result ["
+ result + "]",
filteredResults.contains(result));
}
}
}
@Test
public void testWarningIsLoggedForExcessiveTimedQuery()
throws MsgRegistryException {
TimeUtilTest.installMockTimes(
FactoryRegistryHandler.QUERY_DURATION_WARN_LEVEL + 1,
TimeUnit.MILLISECONDS);
TestableFactoryRegistryHandler handler = new TestableFactoryRegistryHandler();
IUFStatusHandler statusHandler = mock(IUFStatusHandler.class);
IUFStatusHandler oldHandler = FactoryRegistryHandler.statusHandler;
try {
FactoryRegistryHandler.statusHandler = statusHandler;
IdQuery<String> registryQuery = new IdQuery<String>(String.class);
registryQuery.setID("someId");
handler.getObjects(registryQuery);
verify(statusHandler, never()).warn(anyString());
} finally {
FactoryRegistryHandler.statusHandler = oldHandler;
}
}
@Test
public void testWarningIsNotLoggedForNonExcessiveTimedQuery()
throws MsgRegistryException {
TimeUtilTest.installMockTimes(
FactoryRegistryHandler.QUERY_DURATION_WARN_LEVEL - 1,
TimeUnit.MILLISECONDS);
TestableFactoryRegistryHandler handler = new TestableFactoryRegistryHandler();
IUFStatusHandler statusHandler = mock(IUFStatusHandler.class);
IUFStatusHandler oldHandler = FactoryRegistryHandler.statusHandler;
try {
FactoryRegistryHandler.statusHandler = statusHandler;
IdQuery<String> registryQuery = new IdQuery<String>(String.class);
registryQuery.setID("someId");
handler.getObjects(registryQuery);
verify(statusHandler, never()).warn(anyString());
} finally {
FactoryRegistryHandler.statusHandler = oldHandler;
}
}
private static <T extends Exception> FactoryRegistryHandler getExceptionThrowingHandler(
final T t) {
FactoryRegistryHandler handler = new FactoryRegistryHandler();
handler.setTxManager(new RegistryTxManager() {
@Override
public TxManager getTxManager() {
return new TxManager() {
@Override
public void startTransaction() throws Exception {
throw t;
}
@Override
public void closeTransaction() {
}
};
}
});
return handler;
}
}

View file

@ -0,0 +1,61 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
/**
* Test {@link IntegerAttribute}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 20, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class IntegerAttributeTest {
@Test
public void testGetQueryValueCreatesCommaSeparatedListOfValues() {
IntegerAttribute attribute = IntegerAttribute.fromIntegers(Arrays
.asList(1, 2));
assertEquals("Incorrect query value string generated!", "1,2",
attribute.getQueryValue());
}
@Test
public void testGetQueryValueCreatesSingleValueString() {
IntegerAttribute attribute = new IntegerAttribute(1);
assertEquals("Incorrect query value string generated!", "1",
attribute.getQueryValue());
}
}

View file

@ -0,0 +1,97 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.RegistryObjectType;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.SlotType;
import org.junit.BeforeClass;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.DataType;
import com.raytheon.uf.common.registry.MockRegistryObject;
import com.raytheon.uf.common.registry.ebxml.encoder.IRegistryEncoder;
import com.raytheon.uf.common.registry.ebxml.encoder.RegistryEncoders;
import com.raytheon.uf.common.registry.ebxml.encoder.RegistryEncoders.Type;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.util.ReflectionException;
/**
* Test {@link RegistryUtil}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 22, 2012 0743 djohnson Initial creation
* Sep 07, 2012 1102 djohnson Setup the registry encoder.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class RegistryUtilTest {
/**
* Allows tests to set a specific registry encoding type to use.
*
* @param type
* the type
*/
public static void setEncoderStrategy(IRegistryEncoder encoder) {
RegistryUtil.ENCODER_STRATEGY = encoder;
}
@BeforeClass
public static void classSetup() {
RegistryUtilTest.setEncoderStrategy(RegistryEncoders
.ofType(Type.DYNAMIC_SERIALIZE));
}
@Test
public void newRegistryObjectCanConvertEnumValues()
throws ReflectionException, SerializationException {
MockRegistryObject registryObject = new MockRegistryObject();
registryObject.setDataType(DataType.GRID);
RegistryObjectType type = RegistryUtil
.newRegistryObject(registryObject);
SlotType slotToCheck = null;
for (SlotType slot : type.getSlot()) {
if (slot.getName().equals("dataType")) {
slotToCheck = slot;
break;
}
}
assertNotNull("Did not find the slot with the enumeration value!",
slotToCheck);
assertEquals(DataType.GRID.toString(), slotToCheck.getSlotValue()
.getValue());
}
}

View file

@ -0,0 +1,60 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.GriddedDataSetMetaData;
import com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSetMetaDataFixture;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 1, 2012 djohnson Initial creation
* Aug 10, 2012 1022 djohnson Remove generics from {@link GriddedDataSetMetaData}.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SetAssociationResolverTest {
@Test
public void testSetWithObjectThatSuperClassIsRegistryObjectIsAllowed() {
Set<GriddedDataSetMetaData> objects = Collections
.<GriddedDataSetMetaData> singleton(OpenDapGriddedDataSetMetaDataFixture.INSTANCE
.get());
SetAssociationResolver resolver = new SetAssociationResolver();
resolver.getRegistryObjects(objects);
}
}

View file

@ -0,0 +1,85 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.raytheon.uf.common.registry.IMultipleResultFormatter;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.RegistryObjectType;
/**
* Returns an arbitrary number of string results per {@link RegistryObjectType}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 15, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class StringArrayResultsQuery extends AdhocRegistryQuery<String>
implements IMultipleResultFormatter<String> {
private final String[][] resultsToReturn;
private int index;
public StringArrayResultsQuery(String[][] resultsToReturn) {
this.resultsToReturn = resultsToReturn;
}
/**
* {@inheritDoc}
*/
@Override
public Class<String> getObjectType() {
return String.class;
}
/**
* {@inheritDoc}
*/
@Override
public Class<String> getResultType() {
return String.class;
}
@Override
public Collection<String> decodeObject(RegistryObjectType registryObjectType) {
List<String> results = new ArrayList<String>();
String[] valuesToReturn = resultsToReturn[index++];
for (String value : valuesToReturn) {
results.add(value);
}
return results;
}
}

View file

@ -0,0 +1,58 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import com.raytheon.uf.common.registry.ebxml.AdhocRegistryQuery;
/**
* A query that states it return {@link String} objects.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 15, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class StringQueryNonFormatter extends AdhocRegistryQuery<String> {
/**
* {@inheritDoc}
*/
@Override
public Class<?> getObjectType() {
return String.class;
}
/**
* {@inheritDoc}
*/
@Override
public Class<String> getResultType() {
return String.class;
}
}

View file

@ -0,0 +1,73 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import com.raytheon.uf.common.registry.IResultFormatter;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.RegistryObjectType;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 15, 2012 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class StringResultsQuery extends AdhocRegistryQuery<String> implements
IResultFormatter<String> {
private final String[] resultsToReturn;
private int index;
public StringResultsQuery(String[] resultsToReturn) {
this.resultsToReturn = resultsToReturn;
}
/**
* {@inheritDoc}
*/
@Override
public Class<String> getObjectType() {
return String.class;
}
/**
* {@inheritDoc}
*/
@Override
public Class<String> getResultType() {
return String.class;
}
@Override
public String decodeObject(RegistryObjectType registryObjectType) {
return resultsToReturn[index++];
}
}

View file

@ -0,0 +1,151 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryQuery;
import com.raytheon.uf.common.registry.RegistryQueryResponse;
import oasis.names.tc.ebxml.regrep.wsdl.registry.services.v4.LifecycleManager;
import oasis.names.tc.ebxml.regrep.wsdl.registry.services.v4.MsgRegistryException;
import oasis.names.tc.ebxml.regrep.wsdl.registry.services.v4.QueryManager;
import oasis.names.tc.ebxml.regrep.xsd.lcm.v4.RemoveObjectsRequest;
import oasis.names.tc.ebxml.regrep.xsd.lcm.v4.SubmitObjectsRequest;
import oasis.names.tc.ebxml.regrep.xsd.lcm.v4.UpdateObjectsRequest;
import oasis.names.tc.ebxml.regrep.xsd.query.v4.QueryRequest;
import oasis.names.tc.ebxml.regrep.xsd.query.v4.QueryResponse;
import oasis.names.tc.ebxml.regrep.xsd.rs.v4.RegistryResponseType;
/**
* Extends {@link FactoryRegistryHandler} to allow it to be testable.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 20, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TestableFactoryRegistryHandler extends FactoryRegistryHandler
implements LifecycleManagerFactory, QueryManagerFactory,
RegistryTxManager, QueryManager, LifecycleManager {
public TestableFactoryRegistryHandler() {
setLcmFactory(this);
setQueryFactory(this);
setTxManager(this);
}
/**
* {@inheritDoc}
*/
@Override
public RegistryQueryResponse getObjects(RegistryQuery query) {
RegistryQueryResponse response = new RegistryQueryResponse();
response.setStatus(OperationStatus.SUCCESS);
return response;
}
/**
* {@inheritDoc}
*/
@Override
public TxManager getTxManager() {
return new TxManager() {
@Override
public void startTransaction() throws Exception {
}
@Override
public void closeTransaction() {
}
};
}
/**
* {@inheritDoc}
*/
@Override
public QueryManager getQueryManager() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LifecycleManager getLifeCycleManager() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public QueryResponse executeQuery(QueryRequest partQueryRequest)
throws MsgRegistryException {
return getQueryResponse();
}
/**
* {@inheritDoc}
*/
@Override
public RegistryResponseType removeObjects(
RemoveObjectsRequest partRemoveObjectsRequest)
throws MsgRegistryException {
return getQueryResponse();
}
/**
* {@inheritDoc}
*/
@Override
public RegistryResponseType submitObjects(
SubmitObjectsRequest partSubmitObjectsRequest)
throws MsgRegistryException {
return getQueryResponse();
}
/**
* {@inheritDoc}
*/
@Override
public RegistryResponseType updateObjects(
UpdateObjectsRequest partUpdateObjectsRequest)
throws MsgRegistryException {
return getQueryResponse();
}
/**
* @return
*/
private QueryResponse getQueryResponse() {
QueryResponse response = new QueryResponse();
response.setStatus(RegistryUtil.RESPONSE_SUCCESS);
return response;
}
}

View file

@ -0,0 +1,220 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml;
import static org.junit.Assert.assertEquals;
import java.net.ConnectException;
import java.rmi.RemoteException;
import java.util.Collections;
import org.apache.http.HttpHost;
import org.apache.http.conn.HttpHostConnectException;
import org.junit.Test;
import com.raytheon.uf.common.comm.CommunicationException;
import com.raytheon.uf.common.registry.IRegistryRequest;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryQueryResponse;
import com.raytheon.uf.common.registry.RegistryResponse;
import com.raytheon.uf.common.serialization.SerializationException;
/**
* Test {@link ThriftRegistryHandler}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 12, 2012 740 djohnson Initial creation
* Sep 12, 2012 1167 djohnson Use localization.
* Nov 15, 2012 1286 djohnson No constructor arguments for ThriftRegistryHandler.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class ThriftRegistryHandlerTest {
private static final HttpHostConnectException HTTP_HOST_CONNECT_EXCEPTION = new HttpHostConnectException(
new HttpHost("someHost"), new ConnectException(
"'cause I done thrown it."));
private static final CommunicationException COMMUNICATION_EXCEPTION = new CommunicationException(
RegistryUtil.DATABASE_ERROR_MESSAGE);
@Test
public void testGetObjectsReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryQueryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).getObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryQueryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).getObjects(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).removeObjects(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithObjectsReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testStoreObjectReturnsUnableToConnectMessageIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).storeObject(null);
assertEquals(RegistryUtil.UNABLE_TO_CONNECT_TO_REGISTRY, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).removeObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testRemoveObjectsWithObjectsReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testStoreObjectReturnsFailedStatusIfHttpHostConnectExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
HTTP_HOST_CONNECT_EXCEPTION).storeObject(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryQueryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).getObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testGetObjectsReturnsFailedToConnectToTheDatabaseIfCommunicationExceptionThrown() {
RegistryQueryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).getObjects(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithObjectsReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testStoreObjectReturnsUnableToConnectMessageIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).storeObject(null);
assertEquals(RegistryUtil.FAILED_TO_CONNECT_TO_DATABASE, response
.getErrors().iterator().next().getMessage());
}
@Test
public void testRemoveObjectsWithQueryReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testRemoveObjectsWithObjectsReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).removeObjects("someUsername",
Collections.emptyList());
assertEquals(OperationStatus.FAILED, response.getStatus());
}
@Test
public void testStoreObjectReturnsFailedStatusIfCommunicationExceptionThrown() {
RegistryResponse<Object> response = getExceptionThrowingHandler(
COMMUNICATION_EXCEPTION).storeObject(null);
assertEquals(OperationStatus.FAILED, response.getStatus());
}
private static <T extends Exception> ThriftRegistryHandler getExceptionThrowingHandler(
final T t) {
ThriftRegistryHandler handler = new ThriftRegistryHandler() {
@Override
<U> RegistryResponse<U> sendRequestViaThrift(
IRegistryRequest<U> request) throws SerializationException,
RemoteException {
throw new RemoteException(
"Error communicating with the server", t);
}
};
return handler;
}
}

View file

@ -0,0 +1,76 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.ebxml.slots;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.SlotType;
import oasis.names.tc.ebxml.regrep.xsd.rim.v4.ValueType;
import org.junit.Test;
/**
* Test {@link DateSlotConverter}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 6, 2012 955 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class DateSlotConverterTest {
private static final Date DATE = new Date();
@Test
public void testConvertingDateToSlotReturnsCorrectNumberOfSlots() {
List<SlotType> slots = DateSlotConverter.INSTANCE.getSlots("someName",
DATE);
assertEquals(1, slots.size());
}
@Test
public void testConvertingDateToSlotReturnsTimeInMillis() {
List<SlotType> slots = DateSlotConverter.INSTANCE.getSlots("someName",
DATE);
ValueType valueType = slots.iterator().next().getSlotValue();
Object object = valueType.getValue();
assertEquals("Expected the slot to have the time in millis!",
DATE.getTime(), ((BigInteger) object).longValue());
}
@Test(expected = IllegalArgumentException.class)
public void testConvertingDateToSlotThrowsIllegalArgumentExceptionIfNotDate() {
DateSlotConverter.INSTANCE.getSlots("someName", "notADate");
}
}

View file

@ -0,0 +1,71 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import java.util.Arrays;
import org.junit.Test;
import com.raytheon.uf.common.registry.MockRegistryObject;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryResponse;
/**
* Test {@link BaseRegistryObjectHandler}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 17, 2012 1169 djohnson Initial creation
* Oct 17, 2012 0726 djohnson Simplified test.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class BaseRegistryObjectHandlerTest {
@Test(expected = RegistryHandlerException.class)
public void testFailedStoreResponseThrowsException()
throws RegistryHandlerException {
RegistryResponse<MockRegistryObject> response = new RegistryResponse<MockRegistryObject>();
response.setRegistryObjects(Arrays.asList(new MockRegistryObject()));
response.setStatus(OperationStatus.FAILED);
MockRegistryObjectHandler.checkResponse(response,
new MockRegistryObject(), "store");
}
@Test
public void testSuccessfulStoreResponseDoesNotThrowException()
throws RegistryHandlerException {
RegistryResponse<MockRegistryObject> response = new RegistryResponse<MockRegistryObject>();
response.setRegistryObjects(Arrays.asList(new MockRegistryObject()));
response.setStatus(OperationStatus.SUCCESS);
MockRegistryObjectHandler.checkResponse(response,
new MockRegistryObject(), "store");
}
}

View file

@ -0,0 +1,43 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import com.raytheon.uf.common.registry.MockRegistryObject;
/**
* {@link IRegistryObjectHandler} interface for {@link MockRegistryObject}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 17, 2012 1169 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public interface IMockRegistryObjectHandler extends
IRegistryObjectHandler<MockRegistryObject> {
}

View file

@ -0,0 +1,63 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import org.junit.Ignore;
import com.raytheon.uf.common.registry.MockRegistryObject;
/**
* {@link IRegistryObjectHandler} for {@link MockRegistryObject}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 17, 2012 1169 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
@Ignore
public class MockRegistryObjectHandler extends
BaseRegistryObjectHandler<MockRegistryObject, MockRegistryObjectQuery>
implements
IMockRegistryObjectHandler {
/**
* {@inheritDoc}
*/
@Override
protected Class<MockRegistryObject> getRegistryObjectClass() {
return MockRegistryObject.class;
}
/**
* {@inheritDoc}
*/
@Override
protected MockRegistryObjectQuery getQuery() {
return new MockRegistryObjectQuery();
}
}

View file

@ -0,0 +1,60 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import com.raytheon.uf.common.registry.MockRegistryObject;
import com.raytheon.uf.common.registry.ebxml.AdhocRegistryQuery;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 27, 2012 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class MockRegistryObjectQuery extends
AdhocRegistryQuery<MockRegistryObject> {
/**
* {@inheritDoc}
*/
@Override
public Class<?> getObjectType() {
return MockRegistryObject.class;
}
/**
* {@inheritDoc}
*/
@Override
public Class<MockRegistryObject> getResultType() {
return MockRegistryObject.class;
}
}

View file

@ -0,0 +1,88 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import static org.junit.Assert.assertSame;
import org.junit.Before;
import org.junit.Test;
/**
* Test {@link RegistryObjectHandlers}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 17, 2012 1169 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class RegistryObjectHandlersTest {
/**
* Clears out all current handler registrations.
*/
public static void clear() {
RegistryObjectHandlers.clear();
}
@Before
public void setUp() {
RegistryObjectHandlersTest.clear();
}
@Test
public void testRegisteredHandlerIsRetrievable() {
final MockRegistryObjectHandler handler = new MockRegistryObjectHandler();
RegistryObjectHandlers.register(IMockRegistryObjectHandler.class,
handler);
assertSame(handler,
RegistryObjectHandlers.get(IMockRegistryObjectHandler.class));
}
@Test(expected = IllegalStateException.class)
public void testAssociatingTwoHandlersWithSameInterfaceThrowsException() {
RegistryObjectHandlers.register(IMockRegistryObjectHandler.class,
new MockRegistryObjectHandler());
RegistryObjectHandlers.register(IMockRegistryObjectHandler.class,
new MockRegistryObjectHandler());
}
@Test(expected = IllegalArgumentException.class)
public void testNoHandlerRegisteredThrowsExceptionOnGet() {
RegistryObjectHandlers.get(IMockRegistryObjectHandler.class);
}
@Test(expected = IllegalArgumentException.class)
public void testRegisterWithNonInterfaceArgumentThrowsException() {
RegistryObjectHandlers.register(MockRegistryObjectHandler.class,
new MockRegistryObjectHandler());
}
}

View file

@ -0,0 +1,88 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.registry.handler;
import org.mockito.Mockito;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.raytheon.uf.common.util.TestUtil;
/**
* Since the handlers are registered via Spring, this provides a one-stop shop
* for adding all registry object handlers. The list of handlers should grow as
* required for tests.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 4, 2012 1241 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class RegistryObjectHandlersUtil {
private static final String MOCK_DATADELIVERY_HANDLERS_XML = "/datadelivery/mock-datadelivery-handlers.xml";
private static final String SPRING_DATADELIVERY_HANDLERS_IMPL_XML = "/spring/datadelivery-handlers-impl.xml";
private static final String MEMORY_DATADELIVERY_HANDLERS_XML = "/datadelivery/memory-datadelivery-handlers.xml";
/**
* Initializes the handlers with the set of production implementations,
* which interact with the registry proper.
*/
public static void init() {
initHandlersFromSpringFile(SPRING_DATADELIVERY_HANDLERS_IMPL_XML);
}
/**
* Initializes the handlers with a set of {@link Mockito} provided handlers.
*/
public static void initMocks() {
initHandlersFromSpringFile(MOCK_DATADELIVERY_HANDLERS_XML);
}
/**
* Initializes the handlers with a set of in-memory implementations.
*/
public static void initMemory() {
initHandlersFromSpringFile(MEMORY_DATADELIVERY_HANDLERS_XML);
}
/**
* @param resResource
*/
private static void initHandlersFromSpringFile(String resResource) {
RegistryObjectHandlers.clear();
new ClassPathXmlApplicationContext(
new String[] {
TestUtil.getResResourcePath("/spring/datadelivery-handlers.xml"),
TestUtil.getResResourcePath(resResource) },
RegistryObjectHandlersUtil.class);
}
}

View file

@ -0,0 +1,206 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.serialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBException;
import oasis.names.tc.ebxml.regrep.wsdl.registry.services.v4.MsgRegistryException;
import oasis.names.tc.ebxml.regrep.xsd.rs.v4.RegistryExceptionType;
import org.junit.BeforeClass;
import org.junit.Test;
import com.raytheon.uf.common.datadelivery.registry.Provider;
import com.raytheon.uf.common.datadelivery.registry.ProviderFixture;
import com.raytheon.uf.common.registry.OperationStatus;
import com.raytheon.uf.common.registry.RegistryResponse;
import com.raytheon.uf.common.util.FileUtil;
import com.raytheon.uf.common.util.TestUtil;
/**
* Test {@link SerializationUtil}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 11, 2012 1102 djohnson Initial creation
* Sep 14, 2012 1169 djohnson Test dynamically serializing a throwable.
* Sep 28, 2012 1187 djohnson Test dynamically serializing with a field level adapter.
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SerializationUtilTest {
private static Provider PROVIDER;
private static String PROVIDER_XML;
/**
* An ever-growing list of JAXB-able classes. Basically this array should
* duplicate the contents of the ISerializableContext files at some point
* (as they are needed).
*/
private static final Class<?>[] JAXB_CLASSES = {
com.raytheon.uf.common.datadelivery.registry.AdhocSubscription.class,
com.raytheon.uf.common.datadelivery.registry.Connection.class,
com.raytheon.uf.common.datadelivery.registry.Coverage.class,
com.raytheon.uf.common.datadelivery.registry.DataLevelType.class,
com.raytheon.uf.common.datadelivery.registry.DataSet.class,
com.raytheon.uf.common.datadelivery.registry.DataSetMetaData.class,
com.raytheon.uf.common.datadelivery.registry.DataSetName.class,
com.raytheon.uf.common.datadelivery.registry.Ensemble.class,
com.raytheon.uf.common.datadelivery.registry.GriddedCoverage.class,
com.raytheon.uf.common.datadelivery.registry.GriddedDataSet.class,
com.raytheon.uf.common.datadelivery.registry.GriddedDataSetMetaData.class,
com.raytheon.uf.common.datadelivery.registry.GriddedProjection.class,
com.raytheon.uf.common.datadelivery.registry.GroupDefinition.class,
com.raytheon.uf.common.datadelivery.registry.Levels.class,
com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSet.class,
com.raytheon.uf.common.datadelivery.registry.OpenDapGriddedDataSetMetaData.class,
com.raytheon.uf.common.datadelivery.registry.Parameter.class,
com.raytheon.uf.common.datadelivery.registry.ParameterLevel.class,
com.raytheon.uf.common.datadelivery.registry.PendingSubscription.class,
com.raytheon.uf.common.datadelivery.registry.Projection.class,
com.raytheon.uf.common.datadelivery.registry.Provider.class,
com.raytheon.uf.common.datadelivery.registry.Subscription.class,
com.raytheon.uf.common.datadelivery.registry.SubscriptionBundle.class,
com.raytheon.uf.common.datadelivery.registry.Time.class,
com.raytheon.uf.edex.datadelivery.bandwidth.dao.DataSetMetaDataDao.class,
com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionDao.class,
com.raytheon.uf.edex.datadelivery.bandwidth.dao.SubscriptionRetrieval.class,
com.raytheon.uf.edex.datadelivery.bandwidth.dao.BandwidthAllocation.class,
com.raytheon.uf.edex.datadelivery.bandwidth.retrieval.BandwidthMap.class,
com.raytheon.uf.common.datadelivery.retrieval.xml.ServiceConfig.class,
com.raytheon.uf.common.datadelivery.retrieval.xml.UnitLookup.class,
com.raytheon.uf.common.datadelivery.retrieval.xml.LevelLookup.class };
/**
* Enables the use of {@link SerializationUtil} within tests.
*/
public static void initSerializationUtil() {
try {
SerializationUtil.jaxbManager = new JAXBManager(JAXB_CLASSES);
} catch (JAXBException e) {
throw new IllegalStateException(
"Unable to install the jaxbManager instance in SerializationUtil!");
}
}
@BeforeClass
public static void staticSetup() throws JAXBException {
SerializationUtilTest.initSerializationUtil();
PROVIDER = ProviderFixture.INSTANCE.get();
PROVIDER_XML = SerializationUtil.marshalToXml(PROVIDER);
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedJaxbUnmarshalFromInputStream()
throws SerializationException {
assertNotNull(SerializationUtil
.jaxbUnmarshalFromInputStream(new ByteArrayInputStream(
PROVIDER_XML.getBytes())));
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedJaxbUnmarshalFromXmlFile() throws IOException,
SerializationException {
File testDir = TestUtil.setupTestClassDir(SerializationUtilTest.class);
File file = new File(testDir, "test.xml");
FileUtil.bytes2File(PROVIDER_XML.getBytes(), file);
assertNotNull(SerializationUtil.jaxbUnmarshalFromXmlFile(file));
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedJaxbUnmarshalFromXmlFileStringParameter()
throws IOException, SerializationException {
File testDir = TestUtil.setupTestClassDir(SerializationUtilTest.class);
File file = new File(testDir, "test.xml");
FileUtil.bytes2File(PROVIDER_XML.getBytes(), file);
assertNotNull(SerializationUtil.jaxbUnmarshalFromXmlFile(file
.getAbsolutePath()));
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedTransformFromThrift()
throws SerializationException {
byte[] serialized = SerializationUtil.transformToThrift(PROVIDER);
assertNotNull(SerializationUtil.transformFromThrift(serialized));
}
@SuppressWarnings("deprecation")
@Test
public void testDeprecatedUnmarshalFromXml() throws JAXBException {
assertNotNull(SerializationUtil.unmarshalFromXml(PROVIDER_XML));
}
@Test
public void testDynamicallySerializeThrowable()
throws SerializationException {
final IOException exceptionOne = new IOException("Some IO issue");
final MsgRegistryException exceptionTwo = new MsgRegistryException(
"blah", new RegistryExceptionType());
RegistryResponse<String> response = new RegistryResponse<String>();
response.setRegistryObjects(Arrays.asList("one", "two"));
response.setErrors(Arrays
.<Throwable> asList(exceptionOne, exceptionTwo));
response.setStatus(OperationStatus.PARTIAL_SUCCESS);
byte[] serialized = SerializationUtil.transformToThrift(response);
@SuppressWarnings("unchecked")
RegistryResponse<String> restored = SerializationUtil
.transformFromThrift(RegistryResponse.class, serialized);
List<String> registryObjects = restored.getRegistryObjects();
assertEquals("Incorrect number of registry objects returned", 2,
registryObjects.size());
assertEquals("one", registryObjects.get(0));
assertEquals("two", registryObjects.get(1));
List<Throwable> throwables = restored.getErrors();
assertEquals("Incorrect number of throwables returned!", 2,
throwables.size());
assertEquals("Incorrect throwable message!", exceptionOne.getMessage(),
throwables.get(0).getMessage());
assertEquals("Incorrect throwable message!", exceptionTwo.getMessage(),
throwables.get(1).getMessage());
}
}

View file

@ -0,0 +1,134 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.serialization.comm;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import com.raytheon.uf.common.util.registry.RegistryException;
/**
* Test {@link RequestRouter}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Nov 14, 2012 1286 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class RequestRouterTest {
private static final String SERVICE1_KEY = "server1Key";
private static final String SERVICE2_KEY = "server2Key";
private final IRequestRouter requestServerRouter = mock(IRequestRouter.class);
private final IRequestRouter server1Router = mock(IRequestRouter.class);
private final IRequestRouter server2Router = mock(IRequestRouter.class);
private final IServerRequest serverRequest = mock(IServerRequest.class);
/**
* Registers a router for the specified server key.
*
* @param key
* the key
* @param router
* the router
* @throws RegistryException
* on error
*/
public static void register(String key, IRequestRouter router)
throws RegistryException {
RequestRouter.getRouterRegistry().register(key, router);
}
/**
* Clears the router registry.
*/
public static void clearRegistry() {
RequestRouter.getRouterRegistry().clear();
}
@Before
public void setUp() throws RegistryException {
clearRegistry();
register(RequestRouter.REQUEST_SERVICE, requestServerRouter);
register(SERVICE1_KEY, server1Router);
register(SERVICE2_KEY, server2Router);
}
@Test
public void testWithoutServiceSendsToDefaultRouter() throws Exception {
RequestRouter.route(serverRequest);
verify(requestServerRouter).route(serverRequest);
}
@Test
public void testWithServiceSendsToRegisteredRouter() throws Exception {
RequestRouter.route(serverRequest, SERVICE1_KEY);
verify(server1Router).route(serverRequest);
verify(server2Router, never()).route(serverRequest);
verify(requestServerRouter, never()).route(serverRequest);
}
@Test
public void testWithService2SendsToRegisteredRouter() throws Exception {
RequestRouter.route(serverRequest, SERVICE2_KEY);
verify(server2Router).route(serverRequest);
verify(server1Router, never()).route(serverRequest);
verify(requestServerRouter, never()).route(serverRequest);
}
@Test
public void testUnregisteredRouterWillRouteToRequestRouter()
throws Exception {
RequestRouter.route(serverRequest, "noRegisteredServer");
verify(requestServerRouter).route(serverRequest);
verify(server2Router, never()).route(serverRequest);
verify(server1Router, never()).route(serverRequest);
}
@Test(expected = RegistryException.class)
public void testRegisteringTwoRequestRoutersWithSameKeyThrowsException()
throws Exception {
register(SERVICE1_KEY, server2Router);
}
}

View file

@ -0,0 +1,187 @@
package com.raytheon.uf.common.stats.data;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.junit.Test;
import com.raytheon.uf.common.stats.AggregateRecord;
import com.raytheon.uf.common.stats.util.DataViewUtils;
public class DataPointTest {
private final String eventType = "com.raytheon.uf.common.stats.ProcessEvent";
private final String field = "processingTime";
private final String grouping = "pluginName:obs";
@Test
public void testObjectCreationReturnsCorrectCount() {
List<AggregateRecord> records = getTestRecords();
DataPoint point = new DataPoint();
for (AggregateRecord rec : records) {
// Check for an existing point object
point.setMax(rec.getMax());
point.setMin(rec.getMin());
point.setSum(rec.getSum());
point.addToCount(rec.getCount());
}
double expectedCount = 4; // sum of both test object's count value
assertEquals("Count does not match", expectedCount, point.getCount(), 0);
assertEquals("Count does not match", expectedCount,
point.getValue(DataViewUtils.DataView.COUNT.getView()), 0);
}
@Test
public void testObjectCreationReturnsCorrectSum() {
List<AggregateRecord> records = getTestRecords();
DataPoint point = new DataPoint();
for (AggregateRecord rec : records) {
// Check for an existing point object
point.setMax(rec.getMax());
point.setMin(rec.getMin());
point.setSum(rec.getSum());
point.addToCount(rec.getCount());
}
double expectedSum = 365; // sum of both test object's sum value
assertEquals("Sum does not match", expectedSum, point.getSum(), 0);
assertEquals("Sum does not match", expectedSum,
point.getValue(DataViewUtils.DataView.SUM.getView()), 0);
}
@Test
public void testObjectCreationReturnsCorrectMinValue() {
List<AggregateRecord> records = getTestRecords();
DataPoint point = new DataPoint();
for (AggregateRecord rec : records) {
// Check for an existing point object
point.setMax(rec.getMax());
point.setMin(rec.getMin());
point.setSum(rec.getSum());
point.addToCount(rec.getCount());
}
double expectedMin = 5; // smallest min value of both test objects
assertEquals("Min does not match", expectedMin, point.getMin(), 0);
assertEquals("Min does not match", expectedMin,
point.getValue(DataViewUtils.DataView.MIN.getView()), 0);
}
@Test
public void testObjectCreationReturnsCorrectMaxValue() {
List<AggregateRecord> records = getTestRecords();
DataPoint point = new DataPoint();
for (AggregateRecord rec : records) {
// Check for an existing point object
point.setMax(rec.getMax());
point.setMin(rec.getMin());
point.setSum(rec.getSum());
point.addToCount(rec.getCount());
}
double expectedMax = 200; // largest max value of both test objects
assertEquals("Max does not match", expectedMax, point.getMax(), 0);
assertEquals("Max does not match", expectedMax,
point.getValue(DataViewUtils.DataView.MAX.getView()), 0);
}
@Test
public void testObjectCreationReturnsCorrectAverage() {
List<AggregateRecord> records = getTestRecords();
DataPoint point = new DataPoint();
for (AggregateRecord rec : records) {
// Check for an existing point object
point.setMax(rec.getMax());
point.setMin(rec.getMin());
point.setSum(rec.getSum());
point.addToCount(rec.getCount());
}
double expectedCount = 4; // sum of both test object's count value
double expectedSum = 365; // sum of both test object's sum value
double expectedAvg = expectedSum / expectedCount;
assertEquals("Avg does not match", expectedAvg, point.getAvg(), 0.25);
assertEquals("Avg does not match", expectedAvg,
point.getValue(DataViewUtils.DataView.AVG.getView()), 0.25);
}
// Build the Aggregate records
private List<AggregateRecord> getTestRecords() {
List<AggregateRecord> records = new ArrayList<AggregateRecord>();
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
start.set(Calendar.MILLISECOND, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MINUTE, 0);
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
end.set(Calendar.MILLISECOND, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 5);
AggregateRecord r = new AggregateRecord();
r.setCount(2);
r.setEndDate(end);
r.setEventType(eventType);
r.setField(field);
r.setGrouping(grouping);
r.setId(1);
r.setMax(150);
r.setMin(5);
r.setStartDate(start);
r.setSum(155);
records.add(r);
start = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
start.set(Calendar.MILLISECOND, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MINUTE, 5);
end = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
end.set(Calendar.MILLISECOND, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 10);
AggregateRecord rr = new AggregateRecord();
rr.setCount(2);
rr.setEndDate(end);
rr.setEventType(eventType);
rr.setField(field);
rr.setGrouping(grouping);
rr.setId(1);
rr.setMax(200);
rr.setMin(10);
rr.setStartDate(start);
rr.setSum(210);
records.add(rr);
return records;
}
}

View file

@ -0,0 +1,111 @@
package com.raytheon.uf.common.stats.data;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import org.junit.Test;
import com.raytheon.uf.common.stats.AggregateRecord;
import com.raytheon.uf.common.stats.util.UnitUtils;
import com.raytheon.uf.common.time.util.TimeUtil;
public class StatsDataTest {
private final String eventType = "com.raytheon.uf.common.stats.ProcessEvent";
private final String field = "processingTime";
private final String grouping = "pluginName:obs";
final Map<Long, StatsBin> bins = new TreeMap<Long, StatsBin>();
@Test
public void testAccumulateCreatesPoints() {
List<AggregateRecord> records = getTestRecords();
long startMillis = records.get(0).getStartDate().getTimeInMillis();
long timeStep = 5;
long duration = 60 * TimeUtil.MILLIS_PER_MINUTE;
long numBins = duration / (timeStep * TimeUtil.MILLIS_PER_MINUTE);
for (long i = 0; i < numBins; i++) {
StatsBin sb = new StatsBin();
sb.setBinMillis(startMillis
+ (i * timeStep * TimeUtil.MILLIS_PER_MINUTE));
bins.put(i, sb);
}
UnitUtils unitUtils = new UnitUtils(eventType, field);
unitUtils.setDisplayUnit("ms");
StatsData statsData = new StatsData("key", TimeUtil.MILLIS_PER_MINUTE, null, unitUtils);
statsData.setBins(bins);
statsData.addRecord(records.get(0));
statsData.addRecord(records.get(1));
statsData.accumulate();
List<DataPoint> pointList = statsData.getData();
int expectedPointCount = 2;
assertEquals("Point Counts differ", expectedPointCount, pointList.size(), 0);
}
// Build the Aggregate records
private List<AggregateRecord> getTestRecords() {
List<AggregateRecord> records = new ArrayList<AggregateRecord>();
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
start.set(Calendar.MILLISECOND, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MINUTE, 0);
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
end.set(Calendar.MILLISECOND, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 5);
AggregateRecord r = new AggregateRecord();
r.setCount(2);
r.setEndDate(end);
r.setEventType(eventType);
r.setField(field);
r.setGrouping(grouping);
r.setId(1);
r.setMax(150);
r.setMin(5);
r.setStartDate(start);
r.setSum(155);
records.add(r);
start = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
start.set(Calendar.MILLISECOND, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MINUTE, 30);
end = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
end.set(Calendar.MILLISECOND, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 35);
AggregateRecord rr = new AggregateRecord();
rr.setCount(2);
rr.setEndDate(end);
rr.setEventType(eventType);
rr.setField(field);
rr.setGrouping(grouping);
rr.setId(1);
rr.setMax(200);
rr.setMin(10);
rr.setStartDate(start);
rr.setSum(210);
records.add(rr);
return records;
}
}

View file

@ -0,0 +1,76 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.time;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.After;
import org.junit.Test;
import com.raytheon.uf.common.util.TestUtil;
/**
* Test {@link SimulatedTime}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 24, 2012 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class SimulatedTimeTest {
@After
public void cleanUp() {
SimulatedTime.getSystemTime().setRealTime();
}
@Test
public void testFreezeTimeReturnsFrozenTime() throws Exception {
SimulatedTime simulatedTime = SimulatedTime.getSystemTime();
simulatedTime.setFrozen(true);
Date start = simulatedTime.getTime();
Thread.sleep(10L);
Date end = simulatedTime.getTime();
assertEquals("Time should have been frozen!", start, end);
}
@Test
public void testUnfrozenTimeReturnsRealTime() throws Exception {
SimulatedTime simulatedTime = SimulatedTime.getSystemTime();
simulatedTime.setFrozen(false);
Date start = simulatedTime.getTime();
Thread.sleep(10L);
Date end = simulatedTime.getTime();
TestUtil.assertNotEquals(start, end);
}
}

View file

@ -0,0 +1,117 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.time.util;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.Test;
import com.raytheon.uf.common.serialization.SerializationException;
import com.raytheon.uf.common.serialization.SerializationUtil;
/**
* Test {@link ImmutableDate}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 15, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class ImmutableDateTest {
private final Date date = new ImmutableDate();
@Test
public void testConstructorAcceptingDateSetsCorrectTime() {
Date date = new Date();
Date immutable = new ImmutableDate(date);
assertEquals("The two date objects should have the same time!",
date.getTime(), immutable.getTime());
}
@Test
public void testConstructorAcceptingLongSetsCorrectTime() {
long time = System.currentTimeMillis();
Date immutable = new ImmutableDate(time);
assertEquals("The date object should have the specified time!", time,
immutable.getTime());
}
@Test(expected = UnsupportedOperationException.class)
public void testSetYearThrowsUnsupportedOperationException() {
date.setYear(2012);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetMonthThrowsUnsupportedOperationException() {
date.setMonth(1);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetDateThrowsUnsupportedOperationException() {
date.setDate(1);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetHoursThrowsUnsupportedOperationException() {
date.setHours(1);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetMinutesThrowsUnsupportedOperationException() {
date.setMinutes(1);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetSecondsThrowsUnsupportedOperationException() {
date.setSeconds(1);
}
@Test(expected = UnsupportedOperationException.class)
public void testSetTimeThrowsUnsupportedOperationException() {
date.setTime(1L);
}
@Test
public void testCanBeThriftedAndRestoredAsImmutableDate()
throws SerializationException {
ImmutableDate date = new ImmutableDate();
byte[] serialized = SerializationUtil.transformToThrift(date);
ImmutableDate unserialized = (ImmutableDate) SerializationUtil
.transformFromThrift(serialized);
assertEquals(
"The unserialized version should have the same time as the serialized version!",
date.getTime(), unserialized.getTime());
}
}

View file

@ -0,0 +1,483 @@
package com.raytheon.uf.common.time.util;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import com.raytheon.edex.util.Util;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.SimulatedTime;
import com.raytheon.uf.common.util.TestUtil;
/**
*
* Test {@link TimeUtil}. Can also be used to {@link #freezeTime()}. When
* freezing time in a unit test, you should always have an "@After" annotated
* method that will resume time (or you can have the call in a try/finally).
* e.g.:
*
* <pre>
* {@code
*
* "@After" // without quotes
* public void afterTest() {
* // This is the after each test method of resuming time
* TimeUtilTest.resumeTime();
* }
*
* "@Test" // without quotes
* public void testSomethingHappensAtFrozenTime() {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* }
*
* "@Test"
* public void testSomethingHappensAtFrozenTimeTryFinally() {
* try {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* } finally {
* TimeUtilTest.resumeTime();
* }
* }
*
* }
*
* </pre>
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 16, 2012 0743 djohnson Initial creation
* Sep 11, 2012 1154 djohnson Tests for {@link TimeUtil#isNewerDay(Date, Date, TimeZone)}
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TimeUtilTest {
/**
* Allows time to be manipulated so that tests can be run assuming specific
* time frames.
*
* @author djohnson
*
*/
private static class MockTimeStrategy implements ITimeStrategy {
private final long[] times;
private int index;
public MockTimeStrategy(long[] times) {
if (times == null || times.length == 0) {
throw new IllegalArgumentException(
"Must specify at least one time!");
}
this.times = times;
}
@Override
public long currentTimeMillis() {
long value = times[index];
if (index < (times.length - 1)) {
index++;
}
return value;
}
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that each successive call will return the next element in the array,
* remaining at the last element in the array when reached. This is a
* low-level call to setup specific time instances to be returned, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(new long[] 10L, 20L, 30L});
* long time1 = TimeUtil.currentTimeMillis(); // 10L
* long time2 = TimeUtil.currentTimeMillis(); // 20L
* long time3 = TimeUtil.currentTimeMillis(): // 30L
* long time4 = TimeUtil.currentTimeMillis(): // 30L, out of new times
* }
* </pre>
*
* @param times
* the times to return
*/
public static void installMockTimes(long[] times) {
TimeUtil.timeStrategy = new MockTimeStrategy(times);
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that the first call will return the current time, and the second call
* will return the time after the specified duration has elapsed, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(5, TimeUnit.MINUTES);
* long time1 = TimeUtil.currentTimeMillis(); // current time
* long time2 = TimeUtil.currentTimeMillis(); // 5 minutes in the future
* }
* </pre>
*
* @param amount
* the amount for the specified {@link TimeUnit}
* @param unit
* the {@link TimeUnit}
*/
public static void installMockTimes(long amount, TimeUnit unit) {
long start = System.currentTimeMillis();
long end = start + unit.toMillis(amount);
TimeUtilTest.installMockTimes(new long[] { start, end });
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the current time. This
* is useful to remove time sensitive issues from testing, for instance if
* an operation that exceeds 10 seconds in production code should throw an
* exception but is allowable in test code, then time should be frozen.
*
* <pre>
* {@code
* TimeUtilTest.freezeTime();
* long time1 = TimeUtil.currentTimeMillis(); // 20000000L for example
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 20000000L, still
* }
* </pre>
*/
public static void freezeTime() {
freezeTime(System.currentTimeMillis());
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the specified time. This
* is useful to test specific scenarios, such as errors that occur on
* specific dates/times of the year (e.g. the switch to daylight savings
* time).
*
* <pre>
* {@code
* TimeUtilTest.freezeTime(15151515L);
* long time1 = TimeUtil.currentTimeMillis(); // 15151515L
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 15151515L, still
* }
* </pre>
*
* @param timeToFreezeAt
* the time that the system should be frozen to
*/
public static void freezeTime(long timeToFreezeAt) {
SimulatedTime systemTime = SimulatedTime.getSystemTime();
systemTime.setFrozen(true);
systemTime.setTime(timeToFreezeAt);
installMockTimes(new long[] { timeToFreezeAt });
}
/**
* Resumes using the system time, this can be called after time has been
* frozen to resume noticing time differences when
* {@link TimeUtil#currentTimeMillis()} is called.
*/
public static void resumeTime() {
TimeUtil.timeStrategy = TimeUtil.SYSTEM_TIME_STRATEGY;
SimulatedTime.getSystemTime().setRealTime();
}
@After
public void cleanUp() {
TimeUtilTest.resumeTime();
}
@Test
public void testFreezeTimeStopsTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
assertEquals("Time should have been frozen!", firstTime, secondTime);
}
@Test
public void testFreezeTimeStopsSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
assertEquals("SimulatedTime should have been frozen!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameter() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, TimeUtil.currentTimeMillis());
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameterForSimulatedTime() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, SimulatedTime.getSystemTime()
.getMillis());
}
@Test
public void testInstallMockTimesWithTimeUnitSetsUpCorrectTime() {
final long twoHoursInMillis = Util.MILLI_PER_HOUR * 2;
TimeUtilTest.installMockTimes(2, TimeUnit.HOURS);
long time1 = TimeUtil.currentTimeMillis();
long time2 = TimeUtil.currentTimeMillis();
assertEquals(
"Expected the second time to be 2 hours after the first time!",
twoHoursInMillis, time2 - time1);
}
@Test
public void testGetPriorityEnabledClockReturnsNullClockWhenPriorityNotEnabled() {
IUFStatusHandler handler = mock(IUFStatusHandler.class);
when(handler.isPriorityEnabled(Priority.VERBOSE)).thenReturn(false);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.VERBOSE);
assertSame("Expected to receive the null clock!", TimeUtil.NULL_CLOCK,
clock);
}
@Test
public void testGetPriorityEnabledClockReturnsClockImplWhenPriorityEnabled() {
IUFStatusHandler handler = UFStatus.getHandler(TimeUtilTest.class);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.CRITICAL);
assertTrue("Expected to receive a real clock!",
clock instanceof TimerImpl);
}
@Test
public void testNewDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newDate().getTime());
}
@Test
public void testNewImmutableDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newImmutableDate().getTime());
}
@Test
public void testNewCalendarDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newCalendar().getTime().getTime());
}
@Test
public void testIsNewerDayReturnsTrueForOneMillisecondIntoNewDate() {
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY - 1L);
Date later = new ImmutableDate(earlier.getTime() + 2L);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later,
TimeZone.getTimeZone("GMT")));
}
@Test
public void testIsNewerDayReturnsTrueForNewYear() {
// Jan 11, 1970
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 10);
// Jan 01, 1971
Date later = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 366);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later, TimeZone.getTimeZone("GMT")));
}
@Test
public void testMinCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMinimum(cal, Calendar.MONTH);
assertCalendarFieldIsMinimum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMinimum(cal, Calendar.SECOND);
}
@Test
public void testMinCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
@Test
public void testMaxCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.maxCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMaximum(cal, Calendar.MONTH);
assertCalendarFieldIsMaximum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMaximum(cal, Calendar.SECOND);
}
@Test
public void testMaxCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
/**
* Assert a calendar field was set to its minimum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMinimum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMinimum(field))));
}
/**
* Assert a calendar field was set to its maximum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMaximum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMaximum(field))));
}
}

View file

@ -0,0 +1,152 @@
package com.raytheon.uf.common.time.util;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
* Test {@link TimerImpl}.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 16, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TimerImplTest {
@Before
public void setUp() {
TimeUtilTest.installMockTimes(new long[] { 100L, 200L });
}
@After
public void cleanUp() {
TimeUtilTest.resumeTime();
}
@Test(expected = IllegalStateException.class)
public void testTimerImplCantBeStoppedIfHasntBeenStarted() {
TimerImpl timer = new TimerImpl();
timer.stop();
}
@Test
public void testRestartedTimerWillNotUseIntermediateTime() {
TimeUtilTest.installMockTimes(new long[] { 50L, 75L, 150L, 250L });
TimerImpl timer = new TimerImpl();
// Starts at 50L
timer.start();
// Stops at 75L: 25L elapsed time
timer.stop();
// Restart at 150L: still 25L elapsed time
timer.start();
// Stops again at 250L: 100L more elapsed time
timer.stop();
// 100L + 25L
assertEquals(
"The intermediate time the timer was stopped should not have counted toward the elapsed time!",
125L, timer.getElapsedTime());
}
@Test
public void testTimerImplReturnsElapsedTime() throws InterruptedException {
TimerImpl timer = new TimerImpl();
timer.start();
timer.stop();
assertEquals("Invalid elapsed time returned!", 100L,
timer.getElapsedTime());
}
@Test
public void testResetWillAllowTimerToBeReused() {
// The first difference will be 75-50 = 25L
// The second difference will be 250-150 = 100L
TimeUtilTest.installMockTimes(new long[] { 50L, 75L, 150L, 250L });
TimerImpl timer = new TimerImpl();
timer.start();
timer.stop();
assertEquals("Incorrect elapsed time returned!", 25L,
timer.getElapsedTime());
timer.reset();
timer.start();
timer.stop();
assertEquals("Incorrect elapsed time returned!", 100L,
timer.getElapsedTime());
}
@Test
public void testResetDoesNotUsePreviousElapsedTime() {
TimeUtilTest.installMockTimes(new long[] { 50L, 75L, 150L, 250L });
TimerImpl timer = new TimerImpl();
timer.start();
timer.stop();
assertEquals("Incorrect elapsed time returned!", 25L,
timer.getElapsedTime());
timer.reset();
assertEquals("A reset timer should not have elapsed time!", 0,
timer.getElapsedTime());
}
@Test(expected = IllegalStateException.class)
public void testStartBeingCalledTwiceThrowsException() {
TimerImpl timer = new TimerImpl();
timer.start();
timer.start();
}
@Test
public void testStoppingATimerTwiceDoesNotChangeStopTime() {
TimeUtilTest.installMockTimes(new long[] { 100L, 200L, 300L });
TimerImpl timer = new TimerImpl();
timer.start();
timer.stop();
// Elapsed time should still be 100L since the stop time should be stuck
// at 200L
timer.stop();
assertEquals(
"Expected the stop time to not have changed after the second invocation!",
100L, timer.getElapsedTime());
}
@Test
public void testGetElapsedTimeCanBeCalledOnARunningLock() {
TimeUtilTest.installMockTimes(new long[] { 100L, 200L, 300L });
TimerImpl timer = new TimerImpl();
timer.start();
// 200L - 100L
assertEquals("Incorrect amount of time has been elapsed!", 100L,
timer.getElapsedTime());
timer.stop();
// 300L - 100L
assertEquals("Incorrect amount of time has been elapsed!", 200L,
timer.getElapsedTime());
}
}

View file

@ -0,0 +1,78 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.util;
import java.util.Random;
/**
* A fixture class creates a domain object based on a seed value. Provided the
* same seed value, two instances retrieved from the fixture will be
* equals/hashcode compliant.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 27, 2012 0743 djohnson Initial creation
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public abstract class AbstractFixture<T> {
private static long DEFAULT_SEED = 1L;
/**
* Retrieve an instance using the default seed value.
*
* @return the instance
*/
public T get() {
return get(DEFAULT_SEED);
}
/**
* Retrieve an instance based on the specified seed value.
*
* @param seedValue
* the seed value
* @return the instance based on the seed value
*/
public abstract T get(long seedValue);
/**
* Get a random enum value.
*
* @param clazz
* the enum class
* @param random
* the random instance
* @return the enum value to use
*/
public static <E extends Enum<E>> E randomEnum(Class<E> clazz,
Random random) {
E[] values = clazz.getEnumConstants();
return values[random.nextInt(values.length)];
}
}

Some files were not shown because too many files have changed in this diff Show more